Python 3.7 的新功能

编者 :

Elvis Pranskevichus < elvis @ magic . io >

This article explains the new features in Python 3.7, compared to 3.6. Python 3.7 was released on June 27, 2018. For full details, see the changelog .

摘要 – 发行亮点

新句法特征:

  • PEP 563 , postponed evaluation of type annotations.

Backwards incompatible syntax changes:

新的库模块:

新的内置特征:

Python data model improvements:

  • 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 对象 has been declared to be an official part of the Python language spec.

Significant improvements in the standard library:

CPython 实现改进:

C API 改进:

  • PEP 539 ,用于线程局部存储的新 C API

文档编制改进:

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 章节。

新特征

PEP 563: Postponed Evaluation of Annotations

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:
        ...
class B:
    ...