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

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.



Solution 1:[1]

From Python 3.7 this can work without making it a string, if you opt in to the "postponed evaluation" behaviour (see PEP 563) with:

from __future__ import annotations

Solution 2:[2]

You need to disable Hyper-V which is incompatible with Workstation Pro or Workstation Player.

Go to Control Panel -> Program and Features -> Turn Windows features on or off.

Un-check Hyper-v and click "Ok"

Execute:

bcdedit /set hypervisorlaunchtype off

In an administrator cmd window

Then restart.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jonrsharpe
Solution 2 Rodolfo Ortega