问题
Python 3.6.1, there are several ways of type hinting, in the doc string or annotation. How can I achieve this using annotation?
Say I have a class, which have a class method load
to load data from somewhere, json or database for instance, and construct and return a instance of this class.
class Foo:
@classmethod
def load(cls, bar) -> Foo:
pass
I think this is quite straightforward, but python interpreter raised an error that Foo is not defined.
I know the reason, because when python loads Foo's load's function signature, the Foo class's definition is not finished, so the Foo is not defined yet.
Is this a drawback of function annotation? Can I find some way to achieve this goal, instead of using doc string to type hint, since I really like the clearness of function annotation.
回答1:
You can use string literals for forward references:
import typing
class Foo:
@classmethod
def load(cls, bar) -> 'Foo':
pass
class Bar:
@classmethod
def load(cls, bar) -> Foo:
pass
print(typing.get_type_hints(Foo.load)) # {'return': <class '__main__.Foo'>}
print(typing.get_type_hints(Bar.load)) # {'return': <class '__main__.Foo'>}
来源:https://stackoverflow.com/questions/43883100/python-function-annotation-in-class-return-type-is-the-class-raise-undefined