Python function annotations on return type class - raise undefined class

Python 3.6.1 there are several ways to enter a type, in a document line or annotation. How can I achieve this using annotation?

Let's say I have a class that has a class method load

to load data from somewhere like json or database and also build and return an instance of that class.

class Foo:

    @classmethod
    def load(cls, bar) -> Foo:
        pass

      

I think this is pretty simple, but the python interpreter raised an error that is not defined by Foo.

I know the reason because when python loads the signature of the load function Foo, the definition of the Foo class is not complete, so Foo is not yet defined.

Is this a downside to functional annotation? Can I find some way to achieve this goal, instead of using the doc string to enter the prompt, as I really like the clarity of the function annotations.

+3


source to share


1 answer


You can use string literals for forwarded links :



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'>}

      

+4


source







All Articles