Python 3.7 有什麼新功能¶
- 編輯者:
Elvis Pranskevichus <elvis@magic.io>
本文介紹了 Python 3.7 與 3.6 相比多了哪些新功能。Python 3.7 已於 2018 年 6 月 27 日發布。有關完整詳細資訊,請參閱 changelog。
發布重點摘要¶
新增語法特性:
PEP 563, postponed evaluation of type annotations.
Backwards incompatible syntax changes:
新的函式庫模組:
新的內建功能:
PEP 553, the new
breakpoint()function.
Python 資料模型改進:
PEP 562, customization of access to module attributes.
PEP 560, core support for typing module and generic types.
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
標準函式庫中的顯著改進
The
asynciomodule has received new features, significant usability and performance improvements.The
timemodule gained support for functions with nanosecond resolution.
CPython 實作改進:
Avoiding the use of ASCII as a default text encoding:
PEP 552, deterministic .pycs
PEP 565, improved
DeprecationWarninghandling
C API 改進:
PEP 539, new C API for thread-local storage
Documentation improvements:
PEP 545, Python documentation translations
New documentation translations: Japanese, French, and Korean.
This release features notable performance improvements in many areas. The 最佳化 section lists them in detail.
For a list of changes that may affect compatibility with previous Python releases please refer to the 移植至 Python 3.7 section.
新增功能¶
PEP 563:延後評估註釋¶
The advent of type hints in Python uncovered two glaring usability issues with the functionality of annotations added in PEP 3107 and refined further in PEP 526:
annotations could only use names which were already available in the current scope, in other words they didn't support forward references of any kind; and
annotating source code had adverse effects on startup time of Python programs.
Both of these issues are fixed by postponing the evaluation of
annotations. Instead of compiling code which executes expressions in
annotations at their definition time, the compiler stores the annotation
in a string form equivalent to the AST of the expression in question.
If needed, annotations can be resolved at runtime using
typing.get_type_hints(). In the common case where this is not
required, the annotations are cheaper to store (since short strings
are interned by the interpreter) and make startup time faster.
Usability-wise, annotations now support forward references, making the following syntax valid:
class C:
@classmethod
def from_string(cls, source: str) -> C:
...
def validate_b(self, obj: B) -> bool