Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

python - from __future__ import annotations

Python doc __future__

In python doc about __future__ there is a table below where it shows that annotations "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 then what is the use of it.

>>> def add_int(a:int, b:int) -> int:
...     return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

I doubt I don't clearly understand the meaning of "optional in" and "mandatory in" here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 annotations

It will become the default in Python 3.10.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...