1

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.

wim
  • 338,267
  • 99
  • 616
  • 750
uuu777
  • 765
  • 4
  • 21

1 Answers1

1

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.

wim
  • 338,267
  • 99
  • 616
  • 750
  • Try putting your annotation in quotation marks. mypy knows how to handle it, and python thinks it's just a string. `def aaa(aaa: 'mmm.XxxValue') -> None` – Frank Yellin Sep 15 '20 at 02:14
  • @FrankYellin. I found it and it worked. But it is annoying to say the least. I would expect python proper to be agnostic of annotations and use external tools only to deal with them. – uuu777 Sep 15 '20 at 02:41