python function annotation in class return type is the class raise undefined

允我心安 提交于 2019-12-09 03:15:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!