Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type hint for class method return error – name is not defined?

The following class has a class method create(), which as a type hint for return type, for creating an instance of the class.

class X:
   @classmethod
   def create(cls) -> X:
     pass

However, it got the following error?

NameError: name ‘X’ is not defined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The name X doesn’t exist until the class is fully defined. You can fix this by importing a __future__ feature called annotations. Just put this at the top of your file.

from __future__ import annotations

This wraps all annotations in quotation marks, to suppress errors like this. It’s the same as doing this

class X:
  @classmethod
  def create(cls) -> 'X': # <-- Note the quotes
    pass

but automatically. This will be the default behavior in some future Python version (originally, it was going to be 3.10, but it’s been pushed back due to compatibility issues), but for now the import will make it behave the way you want.

The future import was added in Python 3.7. If you’re on an older version of Python, you’ll have to manually wrap the types in strings, as I did in the example above.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading