ca9163d9
ca9163d9

Reputation: 29179

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

Upvotes: 7

Views: 3915

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

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.

Upvotes: 9

Related Questions