pythonpython-typingmypygrpc-python

python3 raising attribute-error on type annotation


Some background information: I am using mypy_protobuf package. For the type checking purpose it generates .pyi files, and for every enum wrapper Xxx in module mmm it will generate type mmm.XxxValue. So I have a function.

def aaa(aaa: mmm.XxxValue) -> None:

It passes mypy checks. When I start the program execution, on importing the module python3 raises AttributeError because mmm does not have XxxValue, this is right but I would expect that python3 executable would simply ignore annotations.


Solution

  • PEP 3107 says:

    All annotation expressions are evaluated when the function definition is executed, just like default values.

    So the expectation that python3 executable would simply ignore annotations is incorrect. In your case, they're evaluated and the results stored in aaa.__annotations__ mapping.

    However, since Python 3.7 you can postpone the evaluation with a future statement:

    from __future__ import annotations
    

    Now they'll be stored in the __annotations__ mapping as strings. Further details in PEP 563 – Postponed Evaluation of Annotations and, more recently, PEP 649 – Deferred Evaluation Of Annotations Using Descriptors.