Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 719
ca9163d9 Avatar asked Apr 26 '26 03:04

ca9163d9


1 Answers

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.

like image 105
Silvio Mayolo Avatar answered Apr 27 '26 17:04

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!