[Python] Type hinting with self-referencing classes in Python
Type hinting with self-referencing classes in Python
Issue
When using a class inside its own type hints, Python can't recognize the class until it's fully defined.
class User:
@staticmethod
def find_user(...) -> User: # Error: 'User' not defined yet
...
Solution
Use a forward reference by wrapping the class name in quotes delays its evaluation.
class User:
@staticmethod
def find_user(...) -> 'User':
...
Comments
Post a Comment