I have a class that looks like this:
class CareerTransition(object):
def __init__(self, title_from: str, title_to: str)->None:
self.title_from = title_from # type: str
self.title_to = title_to # type: str
@staticmethod
def from_file(fname: str, verbose : bool = False)->List[CareerTransition]:
#Do some stuff
pass
I get this error when I try to instantiate that class:
Traceback (most recent call last):
File "/Users/simon.hughes/GitHub/analytics-py-careerpathing/careerpathing/data/employment_history.py", line 8, in <module>
class CareerTransition(object):
File "/Users/simon.hughes/GitHub/analytics-py-careerpathing/careerpathing/data/employment_history.py", line 17, in CareerTransition
def from_file(fname: str, verbose : bool = False)->List[CareerTransition]:
NameError: name 'CareerTransition' is not defined
Is it not possible to use type annotations to refer to generic types that reference the current class? To clarify (as it may not be obvious) it's throwing that error as the class is not defined yet. Is there a way around this?
Use a string literal for a forward reference:
@staticmethod
def from_file(fname: str, verbose : bool = False)->List['CareerTransition']:
#Do some stuff
pass
An even nicer way then writing the concrete class as stated by @chepner is to use the literal __class__
. The whole thing would look like this:
@staticmethod
def from_file(fname: str, verbose : bool = False) -> List['__class__']:
# Do some stuff
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With