Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Type Hinting - Method Returns a List of the Current Class [duplicate]

Tags:

python

types

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?

like image 529
Simon Avatar asked Apr 01 '16 01:04

Simon


2 Answers

Use a string literal for a forward reference:

@staticmethod
def from_file(fname: str, verbose : bool = False)->List['CareerTransition']:
    #Do some stuff
    pass
like image 192
chepner Avatar answered Oct 04 '22 16:10

chepner


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
like image 35
melbic Avatar answered Oct 04 '22 15:10

melbic