from __future__ import annotations
May 1
In the Python docs about __future__, there is a table where it shows that annotations are "optional in" 3.7.0b1 and "mandatory in" 4.0, but I am still able to use annotations in 3.8.2 without importing annotations. Given that, what is the use of it? What do "optional" and "mandatory" here mean?
>>> def add_int(a:int, b:int) -> int:
... return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
1 answer
Accepted answer · original discussion
May 1
Mandatory is an interesting word choice. I guess it means that it's by default in the language. You don't have to enable it with from __future__ import annotations
The annotations feature are referring to the PEP 563: Postponed evaluation of annotations. It's an enhancement to the existing annotations feature which was initially introduced in python 3.0 and redefined as type hints in python 3.5, that's why your code works under python 3.8.
Here's what optional from __future__ import annotations changes in python 3.7+:
class A:
def f(self) -> A: # NameError: name 'A' is not defined
pass
but this works
from __future__ import annotations
class A:
def f(self) -> A:
pass
See this chapter in python 3.7 what's new about postponed annotations:
Since this change breaks compatibility, the new behavior needs to be enabled on a per-module basis in Python 3.7 using a
__future__import:
from __future__ import annotationsIt will become the default in Python 3.10*.
* it was announced to be default in 3.10 (when python3.7 was released), but it was now moved to a later release
0 question comments
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.