简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM