### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](3.5.xhtml "Python 3.5 有什么新變化") |
- [上一頁](3.7.xhtml "Python 3.7 有什么新變化") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 有什么新變化?](index.xhtml) ?
- $('.inline-search').show(0); |
# Python 3.6 有什么新變化A
作者Elvis Pranskevichus <[elvis@magic.io](mailto:elvis%40magic.io)>, Yury Selivanov <[yury@magic.io](mailto:yury%40magic.io)>
本文解釋了與3.5相比,Python 3.6中的新功能。 Python 3.6于2016年12月23日發布。請參閱 [changelog](https://docs.python.org/3.6/whatsnew/changelog.html) \[https://docs.python.org/3.6/whatsnew/changelog.html\] 以獲取完整的更改列表。
參見
[**PEP 494**](https://www.python.org/dev/peps/pep-0494) \[https://www.python.org/dev/peps/pep-0494\] - Python 3.6發布計劃
## 摘要 - 發布重點
新的語法特性:
- [PEP 498](#whatsnew36-pep498), 格式化的字符串文字
- [PEP 515](#whatsnew36-pep515), 數字文字中的下劃線。
- [PEP 526](#whatsnew36-pep526) , 變量注釋的語法。
- [PEP 525](#whatsnew36-pep525), 異步生成器。
- [PEP 530](#whatsnew36-pep530): 異步推導。
新的庫模塊:
- [`secrets`](../library/secrets.xhtml#module-secrets "secrets: Generate secure random numbers for managing secrets."): [PEP 506 -- Adding A Secrets Module To The Standard Library](#whatsnew36-pep506).
CPython 實現的改進:
- The [dict](../library/stdtypes.xhtml#typesmapping) type has been reimplemented to use a [more compact representation](#whatsnew36-compactdict)based on [a proposal by Raymond Hettinger](https://mail.python.org/pipermail/python-dev/2012-December/123028.html) \[https://mail.python.org/pipermail/python-dev/2012-December/123028.html\]and similar to the [PyPy dict implementation](https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html) \[https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html\]. This resulted in dictionaries using 20% to 25% less memory when compared to Python 3.5.
- Customization of class creation has been simplified with the [new protocol](#whatsnew36-pep487).
- The class attribute definition order is [now preserved](#whatsnew36-pep520).
- The order of elements in `**kwargs` now [corresponds to the order](#whatsnew36-pep468) in which keyword arguments were passed to the function.
- DTrace and SystemTap [probing support](#whatsnew36-tracing) has been added.
- The new [PYTHONMALLOC](#whatsnew36-pythonmalloc) environment variable can now be used to debug the interpreter memory allocation and access errors.
標準庫中的重大改進:
- The [`asyncio`](../library/asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O.") module has received new features, significant usability and performance improvements, and a fair amount of bug fixes. Starting with Python 3.6 the `asyncio` module is no longer provisional and its API is considered stable.
- A new [file system path protocol](#whatsnew36-pep519) has been implemented to support [path-like objects](../glossary.xhtml#term-path-like-object). All standard library functions operating on paths have been updated to work with the new protocol.
- The [`datetime`](../library/datetime.xhtml#module-datetime "datetime: Basic date and time types.") module has gained support for [Local Time Disambiguation](#whatsnew36-pep495).
- The [`typing`](../library/typing.xhtml#module-typing "typing: Support for type hints (see PEP 484).") module received a number of [improvements](#whatsnew36-typing).
- The [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") module has been significantly reworked and is now used to provide better output for [`ResourceWarning`](../library/exceptions.xhtml#ResourceWarning "ResourceWarning")as well as provide better diagnostics for memory allocation errors. See the [PYTHONMALLOC section](#whatsnew36-pythonmalloc) for more information.
安全改進:
- The new [`secrets`](../library/secrets.xhtml#module-secrets "secrets: Generate secure random numbers for managing secrets.") module has been added to simplify the generation of cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar.
- On Linux, [`os.urandom()`](../library/os.xhtml#os.urandom "os.urandom") now blocks until the system urandom entropy pool is initialized to increase the security. See the [**PEP 524**](https://www.python.org/dev/peps/pep-0524) \[https://www.python.org/dev/peps/pep-0524\] for the rationale.
- The [`hashlib`](../library/hashlib.xhtml#module-hashlib "hashlib: Secure hash and message digest algorithms.") and [`ssl`](../library/ssl.xhtml#module-ssl "ssl: TLS/SSL wrapper for socket objects") modules now support OpenSSL 1.1.0.
- The default settings and feature set of the [`ssl`](../library/ssl.xhtml#module-ssl "ssl: TLS/SSL wrapper for socket objects") module have been improved.
- The [`hashlib`](../library/hashlib.xhtml#module-hashlib "hashlib: Secure hash and message digest algorithms.") module received support for the BLAKE2, SHA-3 and SHAKE hash algorithms and the [`scrypt()`](../library/hashlib.xhtml#hashlib.scrypt "hashlib.scrypt") key derivation function.
Windows改進:
- [PEP 528](#whatsnew36-pep528) and [PEP 529](#whatsnew36-pep529), Windows filesystem and console encoding changed to UTF-8.
- The `py.exe` launcher, when used interactively, no longer prefers Python 2 over Python 3 when the user doesn't specify a version (via command line arguments or a config file). Handling of shebang lines remains unchanged - "python" refers to Python 2 in that case.
- `python.exe` and `pythonw.exe` have been marked as long-path aware, which means that the 260 character path limit may no longer apply. See [removing the MAX\_PATH limitation](../using/windows.xhtml#max-path) for details.
- A `._pth` file can be added to force isolated mode and fully specify all search paths to avoid registry and environment lookup. See [the documentation](../using/windows.xhtml#finding-modules) for more information.
- A `python36.zip` file now works as a landmark to infer [`PYTHONHOME`](../using/cmdline.xhtml#envvar-PYTHONHOME). See [the documentation](../using/windows.xhtml#finding-modules) for more information.
## 新的特性
### PEP 498: 格式化的字符串文字
[**PEP 498**](https://www.python.org/dev/peps/pep-0498) \[https://www.python.org/dev/peps/pep-0498\] introduces a new kind of string literals: *f-strings*, or [formatted string literals](../reference/lexical_analysis.xhtml#f-strings).
Formatted string literals are prefixed with `'f'` and are similar to the format strings accepted by [`str.format()`](../library/stdtypes.xhtml#str.format "str.format"). They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the [`format()`](../library/functions.xhtml#format "format") protocol:
```
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
```
參見
[**PEP 498**](https://www.python.org/dev/peps/pep-0498) \[https://www.python.org/dev/peps/pep-0498\] -- 文字字符串插值。PEP 由 Eric V. Smith 撰寫并實現
[Feature documentation](../reference/lexical_analysis.xhtml#f-strings).
### PEP 526: 變量注釋的語法
[**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\] introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:
```
primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: Dict[str, int] = {}
```
Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the `__annotations__` attribute of a class or module.
In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the `__annotations__` attribute.
參見
[**PEP 526**](https://www.python.org/dev/peps/pep-0526) \[https://www.python.org/dev/peps/pep-0526\] -- 變量注釋的語法。PEP written by Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, and Guido van Rossum. Implemented by Ivan Levkivskyi.
Tools that use or will use the new syntax: [mypy](http://www.mypy-lang.org/) \[http://www.mypy-lang.org/\], [pytype](https://github.com/google/pytype) \[https://github.com/google/pytype\], PyCharm, etc.
### PEP 515: 數字文字中的下劃線。
[**PEP 515**](https://www.python.org/dev/peps/pep-0515) \[https://www.python.org/dev/peps/pep-0515\] adds the ability to use underscores in numeric literals for improved readability. For example:
```
>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295
```
Single underscores are allowed between digits and after any base specifier. Leading, trailing, or multiple underscores in a row are not allowed.
The [string formatting](../library/string.xhtml#formatspec) language also now has support for the `'_'` option to signal the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type `'d'`. For integer presentation types `'b'`, `'o'`, `'x'`, and `'X'`, underscores will be inserted every 4 digits:
```
>>> '{:_}'.format(1000000)
'1_000_000'
>>> '{:_x}'.format(0xFFFFFFFF)
'ffff_ffff'
```
參見
[**PEP 515**](https://www.python.org/dev/peps/pep-0515) \[https://www.python.org/dev/peps/pep-0515\] -- 數字文字中的下劃線。PEP 由 Georg Brandl 和 Serhiy Storchaka 撰寫
### PEP 525: 異步生成器
[**PEP 492**](https://www.python.org/dev/peps/pep-0492) \[https://www.python.org/dev/peps/pep-0492\] introduced support for native coroutines and `async` / `await`syntax to Python 3.5. A notable limitation of the Python 3.5 implementation is that it was not possible to use `await` and `yield` in the same function body. In Python 3.6 this restriction has been lifted, making it possible to define *asynchronous generators*:
```
async def ticker(delay, to):
"""Yield numbers from 0 to *to* every *delay* seconds."""
for i in range(to):
yield i
await asyncio.sleep(delay)
```
The new syntax allows for faster and more concise code.
參見
[**PEP 525**](https://www.python.org/dev/peps/pep-0525) \[https://www.python.org/dev/peps/pep-0525\] -- 異步生成器PEP 由 Yury Selivanov 撰寫并實現
### PEP 530: Asynchronous Comprehensions
[**PEP 530**](https://www.python.org/dev/peps/pep-0530) \[https://www.python.org/dev/peps/pep-0530\] adds support for using `async for` in list, set, dict comprehensions and generator expressions:
```
result = [i async for i in aiter() if i % 2]
```
Additionally, `await` expressions are supported in all kinds of comprehensions:
```
result = [await fun() for fun in funcs if await condition()]
```
參見
[**PEP 530**](https://www.python.org/dev/peps/pep-0530) \[https://www.python.org/dev/peps/pep-0530\] -- Asynchronous ComprehensionsPEP 由 Yury Selivanov 撰寫并實現
### PEP 487: Simpler customization of class creation
It is now possible to customize subclass creation without using a metaclass. The new `__init_subclass__` classmethod will be called on the base class whenever a new subclass is created:
```
class PluginBase:
subclasses = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.subclasses.append(cls)
class Plugin1(PluginBase):
pass
class Plugin2(PluginBase):
pass
```
In order to allow zero-argument [`super()`](../library/functions.xhtml#super "super") calls to work correctly from [`__init_subclass__()`](../reference/datamodel.xhtml#object.__init_subclass__ "object.__init_subclass__") implementations, custom metaclasses must ensure that the new `__classcell__` namespace entry is propagated to `type.__new__` (as described in [創建類對象](../reference/datamodel.xhtml#class-object-creation)).
參見
[**PEP 487**](https://www.python.org/dev/peps/pep-0487) \[https://www.python.org/dev/peps/pep-0487\] -- Simpler customization of class creationPEP 由 Martin Teichmann 撰寫并實現。
[Feature documentation](../reference/datamodel.xhtml#class-customization)
### PEP 487: Descriptor Protocol Enhancements
[**PEP 487**](https://www.python.org/dev/peps/pep-0487) \[https://www.python.org/dev/peps/pep-0487\] extends the descriptor protocol to include the new optional [`__set_name__()`](../reference/datamodel.xhtml#object.__set_name__ "object.__set_name__") method. Whenever a new class is defined, the new method will be called on all descriptors included in the definition, providing them with a reference to the class being defined and the name given to the descriptor within the class namespace. In other words, instances of descriptors can now know the attribute name of the descriptor in the owner class:
```
class IntField:
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError(f'expecting integer in {self.name}')
instance.__dict__[self.name] = value
# this is the new initializer:
def __set_name__(self, owner, name):
self.name = name
class Model:
int_field = IntField()
```
參見
[**PEP 487**](https://www.python.org/dev/peps/pep-0487) \[https://www.python.org/dev/peps/pep-0487\] -- Simpler customization of class creationPEP 由 Martin Teichmann 撰寫并實現。
[Feature documentation](../reference/datamodel.xhtml#descriptors)
### PEP 519: Adding a file system path protocol
File system paths have historically been represented as [`str`](../library/stdtypes.xhtml#str "str")or [`bytes`](../library/stdtypes.xhtml#bytes "bytes") objects. This has led to people who write code which operate on file system paths to assume that such objects are only one of those two types (an [`int`](../library/functions.xhtml#int "int") representing a file descriptor does not count as that is not a file path). Unfortunately that assumption prevents alternative object representations of file system paths like [`pathlib`](../library/pathlib.xhtml#module-pathlib "pathlib: Object-oriented filesystem paths") from working with pre-existing code, including Python's standard library.
To fix this situation, a new interface represented by [`os.PathLike`](../library/os.xhtml#os.PathLike "os.PathLike") has been defined. By implementing the [`__fspath__()`](../library/os.xhtml#os.PathLike.__fspath__ "os.PathLike.__fspath__") method, an object signals that it represents a path. An object can then provide a low-level representation of a file system path as a [`str`](../library/stdtypes.xhtml#str "str") or [`bytes`](../library/stdtypes.xhtml#bytes "bytes") object. This means an object is considered [path-like](../glossary.xhtml#term-path-like-object) if it implements [`os.PathLike`](../library/os.xhtml#os.PathLike "os.PathLike") or is a [`str`](../library/stdtypes.xhtml#str "str") or [`bytes`](../library/stdtypes.xhtml#bytes "bytes") object which represents a file system path. Code can use [`os.fspath()`](../library/os.xhtml#os.fspath "os.fspath"), [`os.fsdecode()`](../library/os.xhtml#os.fsdecode "os.fsdecode"), or [`os.fsencode()`](../library/os.xhtml#os.fsencode "os.fsencode") to explicitly get a [`str`](../library/stdtypes.xhtml#str "str") and/or [`bytes`](../library/stdtypes.xhtml#bytes "bytes") representation of a path-like object.
The built-in [`open()`](../library/functions.xhtml#open "open") function has been updated to accept [`os.PathLike`](../library/os.xhtml#os.PathLike "os.PathLike") objects, as have all relevant functions in the [`os`](../library/os.xhtml#module-os "os: Miscellaneous operating system interfaces.") and [`os.path`](../library/os.path.xhtml#module-os.path "os.path: Operations on pathnames.") modules, and most other functions and classes in the standard library. The [`os.DirEntry`](../library/os.xhtml#os.DirEntry "os.DirEntry") class and relevant classes in [`pathlib`](../library/pathlib.xhtml#module-pathlib "pathlib: Object-oriented filesystem paths") have also been updated to implement [`os.PathLike`](../library/os.xhtml#os.PathLike "os.PathLike").
The hope is that updating the fundamental functions for operating on file system paths will lead to third-party code to implicitly support all [path-like objects](../glossary.xhtml#term-path-like-object) without any code changes, or at least very minimal ones (e.g. calling [`os.fspath()`](../library/os.xhtml#os.fspath "os.fspath") at the beginning of code before operating on a path-like object).
Here are some examples of how the new interface allows for [`pathlib.Path`](../library/pathlib.xhtml#pathlib.Path "pathlib.Path") to be used more easily and transparently with pre-existing code:
```
>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
... contents = f.read()
...
>>> import os.path
>>> os.path.splitext(pathlib.Path("some_file.txt"))
('some_file', '.txt')
>>> os.path.join("/a/b", pathlib.Path("c"))
'/a/b/c'
>>> import os
>>> os.fspath(pathlib.Path("some_file.txt"))
'some_file.txt'
```
(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra.)
參見
[**PEP 519**](https://www.python.org/dev/peps/pep-0519) \[https://www.python.org/dev/peps/pep-0519\] -- Adding a file system path protocolPEP written by Brett Cannon and Koos Zevenhoven.
### PEP 495: Local Time Disambiguation
In most world locations, there have been and will be times when local clocks are moved back. In those times, intervals are introduced in which local clocks show the same time twice in the same day. In these situations, the information displayed on a local clock (or stored in a Python datetime instance) is insufficient to identify a particular moment in time.
[**PEP 495**](https://www.python.org/dev/peps/pep-0495) \[https://www.python.org/dev/peps/pep-0495\] adds the new *fold* attribute to instances of [`datetime.datetime`](../library/datetime.xhtml#datetime.datetime "datetime.datetime") and [`datetime.time`](../library/datetime.xhtml#datetime.time "datetime.time") classes to differentiate between two moments in time for which local times are the same:
```
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
... u = u0 + i*HOUR
... t = u.astimezone(Eastern)
... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
```
The values of the [`fold`](../library/datetime.xhtml#datetime.datetime.fold "datetime.datetime.fold") attribute have the value `0` for all instances except those that represent the second (chronologically) moment in time in an ambiguous case.
參見
[**PEP 495**](https://www.python.org/dev/peps/pep-0495) \[https://www.python.org/dev/peps/pep-0495\] -- Local Time DisambiguationPEP written by Alexander Belopolsky and Tim Peters, implementation by Alexander Belopolsky.
### PEP 529: Change Windows filesystem encoding to UTF-8
Representing filesystem paths is best performed with str (Unicode) rather than bytes. However, there are some situations where using bytes is sufficient and correct.
Prior to Python 3.6, data loss could result when using bytes paths on Windows. With this change, using bytes to represent paths is now supported on Windows, provided those bytes are encoded with the encoding returned by [`sys.getfilesystemencoding()`](../library/sys.xhtml#sys.getfilesystemencoding "sys.getfilesystemencoding"), which now defaults to `'utf-8'`.
Applications that do not use str to represent paths should use [`os.fsencode()`](../library/os.xhtml#os.fsencode "os.fsencode") and [`os.fsdecode()`](../library/os.xhtml#os.fsdecode "os.fsdecode") to ensure their bytes are correctly encoded. To revert to the previous behaviour, set [`PYTHONLEGACYWINDOWSFSENCODING`](../using/cmdline.xhtml#envvar-PYTHONLEGACYWINDOWSFSENCODING) or call [`sys._enablelegacywindowsfsencoding()`](../library/sys.xhtml#sys._enablelegacywindowsfsencoding "sys._enablelegacywindowsfsencoding").
See [**PEP 529**](https://www.python.org/dev/peps/pep-0529) \[https://www.python.org/dev/peps/pep-0529\] for more information and discussion of code modifications that may be required.
### PEP 528: Change Windows console encoding to UTF-8
The default console on Windows will now accept all Unicode characters and provide correctly read str objects to Python code. `sys.stdin`, `sys.stdout` and `sys.stderr` now default to utf-8 encoding.
This change only applies when using an interactive console, and not when redirecting files or pipes. To revert to the previous behaviour for interactive console use, set [`PYTHONLEGACYWINDOWSSTDIO`](../using/cmdline.xhtml#envvar-PYTHONLEGACYWINDOWSSTDIO).
參見
[**PEP 528**](https://www.python.org/dev/peps/pep-0528) \[https://www.python.org/dev/peps/pep-0528\] -- Change Windows console encoding to UTF-8PEP written and implemented by Steve Dower.
### PEP 520: Preserving Class Attribute Definition Order
Attributes in a class definition body have a natural ordering: the same order in which the names appear in the source. This order is now preserved in the new class's [`__dict__`](../library/stdtypes.xhtml#object.__dict__ "object.__dict__") attribute.
Also, the effective default class *execution* namespace (returned from [type.\_\_prepare\_\_()](../reference/datamodel.xhtml#prepare)) is now an insertion-order-preserving mapping.
參見
[**PEP 520**](https://www.python.org/dev/peps/pep-0520) \[https://www.python.org/dev/peps/pep-0520\] -- Preserving Class Attribute Definition OrderPEP written and implemented by Eric Snow.
### PEP 468: Preserving Keyword Argument Order
`**kwargs` in a function signature is now guaranteed to be an insertion-order-preserving mapping.
參見
[**PEP 468**](https://www.python.org/dev/peps/pep-0468) \[https://www.python.org/dev/peps/pep-0468\] -- Preserving Keyword Argument OrderPEP written and implemented by Eric Snow.
### New [dict](../library/stdtypes.xhtml#typesmapping) implementation
The [dict](../library/stdtypes.xhtml#typesmapping) type now uses a "compact" representation based on [a proposal by Raymond Hettinger](https://mail.python.org/pipermail/python-dev/2012-December/123028.html) \[https://mail.python.org/pipermail/python-dev/2012-December/123028.html\]which was [first implemented by PyPy](https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html) \[https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html\]. The memory usage of the new [`dict()`](../library/stdtypes.xhtml#dict "dict") is between 20% and 25% smaller compared to Python 3.5.
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).
(Contributed by INADA Naoki in [bpo-27350](https://bugs.python.org/issue27350) \[https://bugs.python.org/issue27350\]. Idea [originally suggested by Raymond Hettinger](https://mail.python.org/pipermail/python-dev/2012-December/123028.html) \[https://mail.python.org/pipermail/python-dev/2012-December/123028.html\].)
### PEP 523: Adding a frame evaluation API to CPython
While Python provides extensive support to customize how code executes, one place it has not done so is in the evaluation of frame objects. If you wanted some way to intercept frame evaluation in Python there really wasn't any way without directly manipulating function pointers for defined functions.
[**PEP 523**](https://www.python.org/dev/peps/pep-0523) \[https://www.python.org/dev/peps/pep-0523\] changes this by providing an API to make frame evaluation pluggable at the C level. This will allow for tools such as debuggers and JITs to intercept frame evaluation before the execution of Python code begins. This enables the use of alternative evaluation implementations for Python code, tracking frame evaluation, etc.
This API is not part of the limited C API and is marked as private to signal that usage of this API is expected to be limited and only applicable to very select, low-level use-cases. Semantics of the API will change with Python as necessary.
參見
[**PEP 523**](https://www.python.org/dev/peps/pep-0523) \[https://www.python.org/dev/peps/pep-0523\] -- Adding a frame evaluation API to CPythonPEP written by Brett Cannon and Dino Viehland.
### PYTHONMALLOC environment variable
The new [`PYTHONMALLOC`](../using/cmdline.xhtml#envvar-PYTHONMALLOC) environment variable allows setting the Python memory allocators and installing debug hooks.
It is now possible to install debug hooks on Python memory allocators on Python compiled in release mode using `PYTHONMALLOC=debug`. Effects of debug hooks:
- Newly allocated memory is filled with the byte `0xCB`
- Freed memory is filled with the byte `0xDB`
- Detect violations of the Python memory allocator API. For example, [`PyObject_Free()`](../c-api/memory.xhtml#c.PyObject_Free "PyObject_Free") called on a memory block allocated by [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc").
- Detect writes before the start of a buffer (buffer underflows)
- Detect writes after the end of a buffer (buffer overflows)
- Check that the [GIL](../glossary.xhtml#term-global-interpreter-lock) is held when allocator functions of [`PYMEM_DOMAIN_OBJ`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") (ex: [`PyObject_Malloc()`](../c-api/memory.xhtml#c.PyObject_Malloc "PyObject_Malloc")) and [`PYMEM_DOMAIN_MEM`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") (ex: [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc")) domains are called.
Checking if the GIL is held is also a new feature of Python 3.6.
See the [`PyMem_SetupDebugHooks()`](../c-api/memory.xhtml#c.PyMem_SetupDebugHooks "PyMem_SetupDebugHooks") function for debug hooks on Python memory allocators.
It is now also possible to force the usage of the `malloc()` allocator of the C library for all Python memory allocations using `PYTHONMALLOC=malloc`. This is helpful when using external memory debuggers like Valgrind on a Python compiled in release mode.
On error, the debug hooks on Python memory allocators now use the [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") module to get the traceback where a memory block was allocated.
Example of fatal error on buffer overflow using `python3.6 -X tracemalloc=5` (store 5 frames in traces):
```
Debug memory block at address p=0x7fbcd41666f8: API 'o'
4 bytes originally requested
The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
at tail+0: 0x02 *** OUCH
at tail+1: 0xfb
at tail+2: 0xfb
at tail+3: 0xfb
at tail+4: 0xfb
at tail+5: 0xfb
at tail+6: 0xfb
at tail+7: 0xfb
The block was made by call #1233329 to debug malloc/realloc.
Data at p: 1a 2b 30 00
Memory block allocated at (most recent call first):
File "test/test_bytes.py", line 323
File "unittest/case.py", line 600
File "unittest/case.py", line 648
File "unittest/suite.py", line 122
File "unittest/suite.py", line 84
Fatal Python error: bad trailing pad byte
Current thread 0x00007fbcdbd32700 (most recent call first):
File "test/test_bytes.py", line 323 in test_hex
File "unittest/case.py", line 600 in run
File "unittest/case.py", line 648 in __call__
File "unittest/suite.py", line 122 in run
File "unittest/suite.py", line 84 in __call__
File "unittest/suite.py", line 122 in run
File "unittest/suite.py", line 84 in __call__
...
```
(Contributed by Victor Stinner in [bpo-26516](https://bugs.python.org/issue26516) \[https://bugs.python.org/issue26516\] and [bpo-26564](https://bugs.python.org/issue26564) \[https://bugs.python.org/issue26564\].)
### DTrace and SystemTap probing support
Python can now be built `--with-dtrace` which enables static markers for the following events in the interpreter:
- function call/return
- garbage collection started/finished
- 執行的代碼行。
This can be used to instrument running interpreters in production, without the need to recompile specific debug builds or providing application-specific profiling/debugging code.
More details in [使用 DTrace 和 SystemTap 檢測CPython](../howto/instrumentation.xhtml#instrumentation).
The current implementation is tested on Linux and macOS. Additional markers may be added in the future.
(Contributed by ?ukasz Langa in [bpo-21590](https://bugs.python.org/issue21590) \[https://bugs.python.org/issue21590\], based on patches by Jesús Cea Avión, David Malcolm, and Nikhil Benesch.)
## 其他語言特性修改
Some smaller changes made to the core Python language are:
- A `global` or `nonlocal` statement must now textually appear before the first use of the affected name in the same scope. Previously this was a [`SyntaxWarning`](../library/exceptions.xhtml#SyntaxWarning "SyntaxWarning").
- It is now possible to set a [special method](../reference/datamodel.xhtml#specialnames) to `None` to indicate that the corresponding operation is not available. For example, if a class sets [`__iter__()`](../reference/datamodel.xhtml#object.__iter__ "object.__iter__") to `None`, the class is not iterable. (Contributed by Andrew Barnert and Ivan Levkivskyi in [bpo-25958](https://bugs.python.org/issue25958) \[https://bugs.python.org/issue25958\].)
- Long sequences of repeated traceback lines are now abbreviated as `"[Previous line repeated {count} more times]"` (see [traceback](#whatsnew36-traceback) for an example). (Contributed by Emanuel Barry in [bpo-26823](https://bugs.python.org/issue26823) \[https://bugs.python.org/issue26823\].)
- Import now raises the new exception [`ModuleNotFoundError`](../library/exceptions.xhtml#ModuleNotFoundError "ModuleNotFoundError")(subclass of [`ImportError`](../library/exceptions.xhtml#ImportError "ImportError")) when it cannot find a module. Code that currently checks for ImportError (in try-except) will still work. (Contributed by Eric Snow in [bpo-15767](https://bugs.python.org/issue15767) \[https://bugs.python.org/issue15767\].)
- Class methods relying on zero-argument `super()` will now work correctly when called from metaclass methods during class creation. (Contributed by Martin Teichmann in [bpo-23722](https://bugs.python.org/issue23722) \[https://bugs.python.org/issue23722\].)
## 新增模塊
### secrets
The main purpose of the new [`secrets`](../library/secrets.xhtml#module-secrets "secrets: Generate secure random numbers for managing secrets.") module is to provide an obvious way to reliably generate cryptographically strong pseudo-random values suitable for managing secrets, such as account authentication, tokens, and similar.
警告
Note that the pseudo-random generators in the [`random`](../library/random.xhtml#module-random "random: Generate pseudo-random numbers with various common distributions.") module should *NOT* be used for security purposes. Use [`secrets`](../library/secrets.xhtml#module-secrets "secrets: Generate secure random numbers for managing secrets.")on Python 3.6+ and [`os.urandom()`](../library/os.xhtml#os.urandom "os.urandom") on Python 3.5 and earlier.
參見
[**PEP 506**](https://www.python.org/dev/peps/pep-0506) \[https://www.python.org/dev/peps/pep-0506\] -- Adding A Secrets Module To The Standard LibraryPEP written and implemented by Steven D'Aprano.
## 改進的模塊
### array
Exhausted iterators of [`array.array`](../library/array.xhtml#array.array "array.array") will now stay exhausted even if the iterated array is extended. This is consistent with the behavior of other mutable sequences.
Contributed by Serhiy Storchaka in [bpo-26492](https://bugs.python.org/issue26492) \[https://bugs.python.org/issue26492\].
### ast
The new `ast.Constant` AST node has been added. It can be used by external AST optimizers for the purposes of constant folding.
Contributed by Victor Stinner in [bpo-26146](https://bugs.python.org/issue26146) \[https://bugs.python.org/issue26146\].
### asyncio
Starting with Python 3.6 the `asyncio` module is no longer provisional and its API is considered stable.
Notable changes in the [`asyncio`](../library/asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O.") module since Python 3.5.0 (all backported to 3.5.x due to the provisional status):
- The [`get_event_loop()`](../library/asyncio-eventloop.xhtml#asyncio.get_event_loop "asyncio.get_event_loop") function has been changed to always return the currently running loop when called from coroutines and callbacks. (Contributed by Yury Selivanov in [bpo-28613](https://bugs.python.org/issue28613) \[https://bugs.python.org/issue28613\].)
- The [`ensure_future()`](../library/asyncio-future.xhtml#asyncio.ensure_future "asyncio.ensure_future") function and all functions that use it, such as [`loop.run_until_complete()`](../library/asyncio-eventloop.xhtml#asyncio.loop.run_until_complete "asyncio.loop.run_until_complete"), now accept all kinds of [awaitable objects](../glossary.xhtml#term-awaitable). (Contributed by Yury Selivanov.)
- New [`run_coroutine_threadsafe()`](../library/asyncio-task.xhtml#asyncio.run_coroutine_threadsafe "asyncio.run_coroutine_threadsafe") function to submit coroutines to event loops from other threads. (Contributed by Vincent Michel.)
- New [`Transport.is_closing()`](../library/asyncio-protocol.xhtml#asyncio.BaseTransport.is_closing "asyncio.BaseTransport.is_closing")method to check if the transport is closing or closed. (Contributed by Yury Selivanov.)
- The [`loop.create_server()`](../library/asyncio-eventloop.xhtml#asyncio.loop.create_server "asyncio.loop.create_server")method can now accept a list of hosts. (Contributed by Yann Sionneau.)
- New [`loop.create_future()`](../library/asyncio-eventloop.xhtml#asyncio.loop.create_future "asyncio.loop.create_future")method to create Future objects. This allows alternative event loop implementations, such as [uvloop](https://github.com/MagicStack/uvloop) \[https://github.com/MagicStack/uvloop\], to provide a faster [`asyncio.Future`](../library/asyncio-future.xhtml#asyncio.Future "asyncio.Future") implementation. (Contributed by Yury Selivanov in [bpo-27041](https://bugs.python.org/issue27041) \[https://bugs.python.org/issue27041\].)
- New [`loop.get_exception_handler()`](../library/asyncio-eventloop.xhtml#asyncio.loop.get_exception_handler "asyncio.loop.get_exception_handler")method to get the current exception handler. (Contributed by Yury Selivanov in [bpo-27040](https://bugs.python.org/issue27040) \[https://bugs.python.org/issue27040\].)
- New [`StreamReader.readuntil()`](../library/asyncio-stream.xhtml#asyncio.StreamReader.readuntil "asyncio.StreamReader.readuntil")method to read data from the stream until a separator bytes sequence appears. (Contributed by Mark Korenberg.)
- The performance of [`StreamReader.readexactly()`](../library/asyncio-stream.xhtml#asyncio.StreamReader.readexactly "asyncio.StreamReader.readexactly")has been improved. (Contributed by Mark Korenberg in [bpo-28370](https://bugs.python.org/issue28370) \[https://bugs.python.org/issue28370\].)
- The [`loop.getaddrinfo()`](../library/asyncio-eventloop.xhtml#asyncio.loop.getaddrinfo "asyncio.loop.getaddrinfo")method is optimized to avoid calling the system `getaddrinfo`function if the address is already resolved. (Contributed by A. Jesse Jiryu Davis.)
- The [`loop.stop()`](../library/asyncio-eventloop.xhtml#asyncio.loop.stop "asyncio.loop.stop")method has been changed to stop the loop immediately after the current iteration. Any new callbacks scheduled as a result of the last iteration will be discarded. (Contributed by Guido van Rossum in [bpo-25593](https://bugs.python.org/issue25593) \[https://bugs.python.org/issue25593\].)
- `Future.set_exception`will now raise [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") when passed an instance of the [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") exception. (Contributed by Chris Angelico in [bpo-26221](https://bugs.python.org/issue26221) \[https://bugs.python.org/issue26221\].)
- New [`loop.connect_accepted_socket()`](../library/asyncio-eventloop.xhtml#asyncio.loop.connect_accepted_socket "asyncio.loop.connect_accepted_socket")method to be used by servers that accept connections outside of asyncio, but that use asyncio to handle them. (Contributed by Jim Fulton in [bpo-27392](https://bugs.python.org/issue27392) \[https://bugs.python.org/issue27392\].)
- `TCP_NODELAY` flag is now set for all TCP transports by default. (Contributed by Yury Selivanov in [bpo-27456](https://bugs.python.org/issue27456) \[https://bugs.python.org/issue27456\].)
- New [`loop.shutdown_asyncgens()`](../library/asyncio-eventloop.xhtml#asyncio.loop.shutdown_asyncgens "asyncio.loop.shutdown_asyncgens")to properly close pending asynchronous generators before closing the loop. (Contributed by Yury Selivanov in [bpo-28003](https://bugs.python.org/issue28003) \[https://bugs.python.org/issue28003\].)
- [`Future`](../library/asyncio-future.xhtml#asyncio.Future "asyncio.Future") and [`Task`](../library/asyncio-task.xhtml#asyncio.Task "asyncio.Task")classes now have an optimized C implementation which makes asyncio code up to 30% faster. (Contributed by Yury Selivanov and INADA Naoki in [bpo-26081](https://bugs.python.org/issue26081) \[https://bugs.python.org/issue26081\]and [bpo-28544](https://bugs.python.org/issue28544) \[https://bugs.python.org/issue28544\].)
### binascii
The [`b2a_base64()`](../library/binascii.xhtml#binascii.b2a_base64 "binascii.b2a_base64") function now accepts an optional *newline*keyword argument to control whether the newline character is appended to the return value. (Contributed by Victor Stinner in [bpo-25357](https://bugs.python.org/issue25357) \[https://bugs.python.org/issue25357\].)
### cmath
The new [`cmath.tau`](../library/cmath.xhtml#cmath.tau "cmath.tau") (*τ*) constant has been added. (Contributed by Lisa Roach in [bpo-12345](https://bugs.python.org/issue12345) \[https://bugs.python.org/issue12345\], see [**PEP 628**](https://www.python.org/dev/peps/pep-0628) \[https://www.python.org/dev/peps/pep-0628\] for details.)
New constants: [`cmath.inf`](../library/cmath.xhtml#cmath.inf "cmath.inf") and [`cmath.nan`](../library/cmath.xhtml#cmath.nan "cmath.nan") to match [`math.inf`](../library/math.xhtml#math.inf "math.inf") and [`math.nan`](../library/math.xhtml#math.nan "math.nan"), and also [`cmath.infj`](../library/cmath.xhtml#cmath.infj "cmath.infj")and [`cmath.nanj`](../library/cmath.xhtml#cmath.nanj "cmath.nanj") to match the format used by complex repr. (Contributed by Mark Dickinson in [bpo-23229](https://bugs.python.org/issue23229) \[https://bugs.python.org/issue23229\].)
### collections
The new [`Collection`](../library/collections.abc.xhtml#collections.abc.Collection "collections.abc.Collection") abstract base class has been added to represent sized iterable container classes. (Contributed by Ivan Levkivskyi, docs by Neil Girdhar in [bpo-27598](https://bugs.python.org/issue27598) \[https://bugs.python.org/issue27598\].)
The new [`Reversible`](../library/collections.abc.xhtml#collections.abc.Reversible "collections.abc.Reversible") abstract base class represents iterable classes that also provide the [`__reversed__()`](../reference/datamodel.xhtml#object.__reversed__ "object.__reversed__") method. (Contributed by Ivan Levkivskyi in [bpo-25987](https://bugs.python.org/issue25987) \[https://bugs.python.org/issue25987\].)
The new [`AsyncGenerator`](../library/collections.abc.xhtml#collections.abc.AsyncGenerator "collections.abc.AsyncGenerator") abstract base class represents asynchronous generators. (Contributed by Yury Selivanov in [bpo-28720](https://bugs.python.org/issue28720) \[https://bugs.python.org/issue28720\].)
The [`namedtuple()`](../library/collections.xhtml#collections.namedtuple "collections.namedtuple") function now accepts an optional keyword argument *module*, which, when specified, is used for the `__module__` attribute of the returned named tuple class. (Contributed by Raymond Hettinger in [bpo-17941](https://bugs.python.org/issue17941) \[https://bugs.python.org/issue17941\].)
The *verbose* and *rename* arguments for [`namedtuple()`](../library/collections.xhtml#collections.namedtuple "collections.namedtuple") are now keyword-only. (Contributed by Raymond Hettinger in [bpo-25628](https://bugs.python.org/issue25628) \[https://bugs.python.org/issue25628\].)
Recursive [`collections.deque`](../library/collections.xhtml#collections.deque "collections.deque") instances can now be pickled. (Contributed by Serhiy Storchaka in [bpo-26482](https://bugs.python.org/issue26482) \[https://bugs.python.org/issue26482\].)
### concurrent.futures
The [`ThreadPoolExecutor`](../library/concurrent.futures.xhtml#concurrent.futures.ThreadPoolExecutor "concurrent.futures.ThreadPoolExecutor")class constructor now accepts an optional *thread\_name\_prefix* argument to make it possible to customize the names of the threads created by the pool. (Contributed by Gregory P. Smith in [bpo-27664](https://bugs.python.org/issue27664) \[https://bugs.python.org/issue27664\].)
### contextlib
The [`contextlib.AbstractContextManager`](../library/contextlib.xhtml#contextlib.AbstractContextManager "contextlib.AbstractContextManager") class has been added to provide an abstract base class for context managers. It provides a sensible default implementation for \_\_enter\_\_() which returns `self` and leaves \_\_exit\_\_() an abstract method. A matching class has been added to the [`typing`](../library/typing.xhtml#module-typing "typing: Support for type hints (see PEP 484).") module as [`typing.ContextManager`](../library/typing.xhtml#typing.ContextManager "typing.ContextManager"). (Contributed by Brett Cannon in [bpo-25609](https://bugs.python.org/issue25609) \[https://bugs.python.org/issue25609\].)
### datetime
The [`datetime`](../library/datetime.xhtml#datetime.datetime "datetime.datetime") and [`time`](../library/datetime.xhtml#datetime.time "datetime.time") classes have the new `fold` attribute used to disambiguate local time when necessary. Many functions in the [`datetime`](../library/datetime.xhtml#module-datetime "datetime: Basic date and time types.") have been updated to support local time disambiguation. See [Local Time Disambiguation](#whatsnew36-pep495) section for more information. (Contributed by Alexander Belopolsky in [bpo-24773](https://bugs.python.org/issue24773) \[https://bugs.python.org/issue24773\].)
The [`datetime.strftime()`](../library/datetime.xhtml#datetime.datetime.strftime "datetime.datetime.strftime") and [`date.strftime()`](../library/datetime.xhtml#datetime.date.strftime "datetime.date.strftime") methods now support ISO 8601 date directives `%G`, `%u` and `%V`. (Contributed by Ashley Anderson in [bpo-12006](https://bugs.python.org/issue12006) \[https://bugs.python.org/issue12006\].)
The [`datetime.isoformat()`](../library/datetime.xhtml#datetime.datetime.isoformat "datetime.datetime.isoformat") function now accepts an optional *timespec* argument that specifies the number of additional components of the time value to include. (Contributed by Alessandro Cucci and Alexander Belopolsky in [bpo-19475](https://bugs.python.org/issue19475) \[https://bugs.python.org/issue19475\].)
The [`datetime.combine()`](../library/datetime.xhtml#datetime.datetime.combine "datetime.datetime.combine") now accepts an optional *tzinfo* argument. (Contributed by Alexander Belopolsky in [bpo-27661](https://bugs.python.org/issue27661) \[https://bugs.python.org/issue27661\].)
### decimal
New [`Decimal.as_integer_ratio()`](../library/decimal.xhtml#decimal.Decimal.as_integer_ratio "decimal.Decimal.as_integer_ratio")method that returns a pair `(n, d)` of integers that represent the given [`Decimal`](../library/decimal.xhtml#decimal.Decimal "decimal.Decimal") instance as a fraction, in lowest terms and with a positive denominator:
```
>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)
```
(Contributed by Stefan Krah amd Mark Dickinson in [bpo-25928](https://bugs.python.org/issue25928) \[https://bugs.python.org/issue25928\].)
### distutils
The `default_format` attribute has been removed from `distutils.command.sdist.sdist` and the `formats`attribute defaults to `['gztar']`. Although not anticipated, any code relying on the presence of `default_format` may need to be adapted. See [bpo-27819](https://bugs.python.org/issue27819) \[https://bugs.python.org/issue27819\] for more details.
### email
The new email API, enabled via the *policy* keyword to various constructors, is no longer provisional. The [`email`](../library/email.xhtml#module-email "email: Package supporting the parsing, manipulating, and generating email messages.") documentation has been reorganized and rewritten to focus on the new API, while retaining the old documentation for the legacy API. (Contributed by R. David Murray in [bpo-24277](https://bugs.python.org/issue24277) \[https://bugs.python.org/issue24277\].)
The [`email.mime`](../library/email.mime.xhtml#module-email.mime "email.mime: Build MIME messages.") classes now all accept an optional *policy* keyword. (Contributed by Berker Peksag in [bpo-27331](https://bugs.python.org/issue27331) \[https://bugs.python.org/issue27331\].)
The [`DecodedGenerator`](../library/email.generator.xhtml#email.generator.DecodedGenerator "email.generator.DecodedGenerator") now supports the *policy*keyword.
There is a new [`policy`](../library/email.policy.xhtml#module-email.policy "email.policy: Controlling the parsing and generating of messages") attribute, [`message_factory`](../library/email.policy.xhtml#email.policy.Policy.message_factory "email.policy.Policy.message_factory"), that controls what class is used by default when the parser creates new message objects. For the [`email.policy.compat32`](../library/email.policy.xhtml#email.policy.compat32 "email.policy.compat32") policy this is [`Message`](../library/email.compat32-message.xhtml#email.message.Message "email.message.Message"), for the new policies it is [`EmailMessage`](../library/email.message.xhtml#email.message.EmailMessage "email.message.EmailMessage"). (Contributed by R. David Murray in [bpo-20476](https://bugs.python.org/issue20476) \[https://bugs.python.org/issue20476\].)
### encodings
On Windows, added the `'oem'` encoding to use `CP_OEMCP`, and the `'ansi'`alias for the existing `'mbcs'` encoding, which uses the `CP_ACP` code page. (Contributed by Steve Dower in [bpo-27959](https://bugs.python.org/issue27959) \[https://bugs.python.org/issue27959\].)
### enum
Two new enumeration base classes have been added to the [`enum`](../library/enum.xhtml#module-enum "enum: Implementation of an enumeration class.") module: [`Flag`](../library/enum.xhtml#enum.Flag "enum.Flag") and `IntFlags`. Both are used to define constants that can be combined using the bitwise operators. (Contributed by Ethan Furman in [bpo-23591](https://bugs.python.org/issue23591) \[https://bugs.python.org/issue23591\].)
Many standard library modules have been updated to use the `IntFlags` class for their constants.
The new [`enum.auto`](../library/enum.xhtml#enum.auto "enum.auto") value can be used to assign values to enum members automatically:
```
>>> from enum import Enum, auto
>>> class Color(Enum):
... red = auto()
... blue = auto()
... green = auto()
...
>>> list(Color)
[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]
```
### faulthandler
On Windows, the [`faulthandler`](../library/faulthandler.xhtml#module-faulthandler "faulthandler: Dump the Python traceback.") module now installs a handler for Windows exceptions: see [`faulthandler.enable()`](../library/faulthandler.xhtml#faulthandler.enable "faulthandler.enable"). (Contributed by Victor Stinner in [bpo-23848](https://bugs.python.org/issue23848) \[https://bugs.python.org/issue23848\].)
### fileinput
[`hook_encoded()`](../library/fileinput.xhtml#fileinput.hook_encoded "fileinput.hook_encoded") now supports the *errors* argument. (Contributed by Joseph Hackman in [bpo-25788](https://bugs.python.org/issue25788) \[https://bugs.python.org/issue25788\].)
### hashlib
[`hashlib`](../library/hashlib.xhtml#module-hashlib "hashlib: Secure hash and message digest algorithms.") supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2. (Contributed by Christian Heimes in [bpo-26470](https://bugs.python.org/issue26470) \[https://bugs.python.org/issue26470\].)
BLAKE2 hash functions were added to the module. [`blake2b()`](../library/hashlib.xhtml#hashlib.blake2b "hashlib.blake2b")and [`blake2s()`](../library/hashlib.xhtml#hashlib.blake2s "hashlib.blake2s") are always available and support the full feature set of BLAKE2. (Contributed by Christian Heimes in [bpo-26798](https://bugs.python.org/issue26798) \[https://bugs.python.org/issue26798\] based on code by Dmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)
The SHA-3 hash functions `sha3_224()`, `sha3_256()`, `sha3_384()`, `sha3_512()`, and SHAKE hash functions `shake_128()` and `shake_256()` were added. (Contributed by Christian Heimes in [bpo-16113](https://bugs.python.org/issue16113) \[https://bugs.python.org/issue16113\]. Keccak Code Package by Guido Bertoni, Joan Daemen, Micha?l Peeters, Gilles Van Assche, and Ronny Van Keer.)
The password-based key derivation function [`scrypt()`](../library/hashlib.xhtml#hashlib.scrypt "hashlib.scrypt") is now available with OpenSSL 1.1.0 and newer. (Contributed by Christian Heimes in [bpo-27928](https://bugs.python.org/issue27928) \[https://bugs.python.org/issue27928\].)
### http.client
[`HTTPConnection.request()`](../library/http.client.xhtml#http.client.HTTPConnection.request "http.client.HTTPConnection.request") and [`endheaders()`](../library/http.client.xhtml#http.client.HTTPConnection.endheaders "http.client.HTTPConnection.endheaders") both now support chunked encoding request bodies. (Contributed by Demian Brecht and Rolf Krahl in [bpo-12319](https://bugs.python.org/issue12319) \[https://bugs.python.org/issue12319\].)
### idlelib 與 IDLE
The idlelib package is being modernized and refactored to make IDLE look and work better and to make the code easier to understand, test, and improve. Part of making IDLE look better, especially on Linux and Mac, is using ttk widgets, mostly in the dialogs. As a result, IDLE no longer runs with tcl/tk 8.4. It now requires tcl/tk 8.5 or 8.6. We recommend running the latest release of either.
'Modernizing' includes renaming and consolidation of idlelib modules. The renaming of files with partial uppercase names is similar to the renaming of, for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0. As a result, imports of idlelib files that worked in 3.5 will usually not work in 3.6. At least a module name change will be needed (see idlelib/README.txt), sometimes more. (Name changes contributed by Al Swiegart and Terry Reedy in [bpo-24225](https://bugs.python.org/issue24225) \[https://bugs.python.org/issue24225\]. Most idlelib patches since have been and will be part of the process.)
In compensation, the eventual result with be that some idlelib classes will be easier to use, with better APIs and docstrings explaining them. Additional useful information will be added to idlelib when available.
New in 3.6.2:
多個對自動補全的修正。 (由 Louie Lu 在 [bpo-15786](https://bugs.python.org/issue15786) \[https://bugs.python.org/issue15786\] 中貢獻。)
New in 3.6.3:
Module Browser (在 File 菜單中,之前稱為 Class Browser) 現在會在最高層級函數和類之外顯示嵌套的函數和類。 (由 Guilherme Polo, Cheryl Sabella 和 Terry Jan Reedy 在 [bpo-1612262](https://bugs.python.org/issue1612262) \[https://bugs.python.org/issue1612262\] 中貢獻。)
之前以擴展形式實現的 IDLE 特性已作為正常特性重新實現。 它們的設置已從 Extensions 選項卡移至其他對話框選項卡。 (由 Charles Wohlganger 和 Terry Jan Reedy 在 [bpo-27099](https://bugs.python.org/issue27099) \[https://bugs.python.org/issue27099\] 中實現。)
Settings 對話框 (Options 中的 Configure IDLE) 已經被部分重寫以改進外觀和功能。 (由 Cheryl Sabella 和 Terry Jan Reedy 在多個問題項中貢獻。)
New in 3.6.4:
字體樣本現在包括一組非拉丁字符以便用戶能更好地查看所選特定字體的效果。 (由 Terry Jan Reedy 在 [bpo-13802](https://bugs.python.org/issue13802) \[https://bugs.python.org/issue13802\] 中貢獻。) 樣本可以被修改以包括其他字符。 (由 Serhiy Storchaka 在 [bpo-31860](https://bugs.python.org/issue31860) \[https://bugs.python.org/issue31860\] 中貢獻。)
New in 3.6.6:
編輯器代碼上下文選項已經過修改。 Box 會顯示所有上下文行直到最大行數。 點擊一個上下文行會使編輯器跳轉到該行。 自定義主題的上下文顏色已添加到 Settings 對話框的 Highlights 選項卡。 (由 Cheryl Sabella 和 Terry Jan Reedy 在 [bpo-33642](https://bugs.python.org/issue33642) \[https://bugs.python.org/issue33642\], [bpo-33768](https://bugs.python.org/issue33768) \[https://bugs.python.org/issue33768\] 和 [bpo-33679](https://bugs.python.org/issue33679) \[https://bugs.python.org/issue33679\] 中貢獻。)
在 Windows 上,會有新的 API 調用將 tk 對 DPI 的調整告知 Windows。 在 Windows 8.1+ 或 10 上,如果 Python 二進制碼的 DPI 兼容屬性未改變,并且監視器分辨率大于 96 DPI,這應該會令文本和線條更清晰。 否則的話它應該不造成影響。 (由 Terry Jan Reedy 在 [bpo-33656](https://bugs.python.org/issue33656) \[https://bugs.python.org/issue33656\] 中貢獻。)
New in 3.6.7:
超過 N 行(默認值為 50)的輸出將被折疊為一個按鈕。 N 可以在 Settings 對話框的 General 頁的 PyShell 部分中進行修改。 數量較少但是超長的行可以通過在輸出上右擊來折疊。 被折疊的輸出可通過雙擊按鈕來展開,或是通過右擊按鈕來放入剪貼板或是單獨的窗口。 (由 Tal Einat 在 [bpo-1529353](https://bugs.python.org/issue1529353) \[https://bugs.python.org/issue1529353\] 中貢獻。)
### importlib
Import now raises the new exception [`ModuleNotFoundError`](../library/exceptions.xhtml#ModuleNotFoundError "ModuleNotFoundError")(subclass of [`ImportError`](../library/exceptions.xhtml#ImportError "ImportError")) when it cannot find a module. Code that current checks for `ImportError` (in try-except) will still work. (Contributed by Eric Snow in [bpo-15767](https://bugs.python.org/issue15767) \[https://bugs.python.org/issue15767\].)
[`importlib.util.LazyLoader`](../library/importlib.xhtml#importlib.util.LazyLoader "importlib.util.LazyLoader") now calls [`create_module()`](../library/importlib.xhtml#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") on the wrapped loader, removing the restriction that [`importlib.machinery.BuiltinImporter`](../library/importlib.xhtml#importlib.machinery.BuiltinImporter "importlib.machinery.BuiltinImporter") and [`importlib.machinery.ExtensionFileLoader`](../library/importlib.xhtml#importlib.machinery.ExtensionFileLoader "importlib.machinery.ExtensionFileLoader") couldn't be used with [`importlib.util.LazyLoader`](../library/importlib.xhtml#importlib.util.LazyLoader "importlib.util.LazyLoader").
[`importlib.util.cache_from_source()`](../library/importlib.xhtml#importlib.util.cache_from_source "importlib.util.cache_from_source"), [`importlib.util.source_from_cache()`](../library/importlib.xhtml#importlib.util.source_from_cache "importlib.util.source_from_cache"), and [`importlib.util.spec_from_file_location()`](../library/importlib.xhtml#importlib.util.spec_from_file_location "importlib.util.spec_from_file_location") now accept a [path-like object](../glossary.xhtml#term-path-like-object).
### inspect
The [`inspect.signature()`](../library/inspect.xhtml#inspect.signature "inspect.signature") function now reports the implicit `.0` parameters generated by the compiler for comprehension and generator expression scopes as if they were positional-only parameters called `implicit0`. (Contributed by Jelle Zijlstra in [bpo-19611](https://bugs.python.org/issue19611) \[https://bugs.python.org/issue19611\].)
To reduce code churn when upgrading from Python 2.7 and the legacy [`inspect.getargspec()`](../library/inspect.xhtml#inspect.getargspec "inspect.getargspec") API, the previously documented deprecation of [`inspect.getfullargspec()`](../library/inspect.xhtml#inspect.getfullargspec "inspect.getfullargspec") has been reversed. While this function is convenient for single/source Python 2/3 code bases, the richer [`inspect.signature()`](../library/inspect.xhtml#inspect.signature "inspect.signature") interface remains the recommended approach for new code. (Contributed by Nick Coghlan in [bpo-27172](https://bugs.python.org/issue27172) \[https://bugs.python.org/issue27172\])
### json
[`json.load()`](../library/json.xhtml#json.load "json.load") and [`json.loads()`](../library/json.xhtml#json.loads "json.loads") now support binary input. Encoded JSON should be represented using either UTF-8, UTF-16, or UTF-32. (Contributed by Serhiy Storchaka in [bpo-17909](https://bugs.python.org/issue17909) \[https://bugs.python.org/issue17909\].)
### logging
The new [`WatchedFileHandler.reopenIfNeeded()`](../library/logging.handlers.xhtml#logging.handlers.WatchedFileHandler.reopenIfNeeded "logging.handlers.WatchedFileHandler.reopenIfNeeded")method has been added to add the ability to check if the log file needs to be reopened. (Contributed by Marian Horban in [bpo-24884](https://bugs.python.org/issue24884) \[https://bugs.python.org/issue24884\].)
### math
The tau (*τ*) constant has been added to the [`math`](../library/math.xhtml#module-math "math: Mathematical functions (sin() etc.).") and [`cmath`](../library/cmath.xhtml#module-cmath "cmath: Mathematical functions for complex numbers.")modules. (Contributed by Lisa Roach in [bpo-12345](https://bugs.python.org/issue12345) \[https://bugs.python.org/issue12345\], see [**PEP 628**](https://www.python.org/dev/peps/pep-0628) \[https://www.python.org/dev/peps/pep-0628\] for details.)
### multiprocessing
[Proxy Objects](../library/multiprocessing.xhtml#multiprocessing-proxy-objects) returned by `multiprocessing.Manager()` can now be nested. (Contributed by Davin Potts in [bpo-6766](https://bugs.python.org/issue6766) \[https://bugs.python.org/issue6766\].)
### os
See the summary of [PEP 519](#whatsnew36-pep519) for details on how the [`os`](../library/os.xhtml#module-os "os: Miscellaneous operating system interfaces.") and [`os.path`](../library/os.path.xhtml#module-os.path "os.path: Operations on pathnames.") modules now support [path-like objects](../glossary.xhtml#term-path-like-object).
[`scandir()`](../library/os.xhtml#os.scandir "os.scandir") now supports [`bytes`](../library/stdtypes.xhtml#bytes "bytes") paths on Windows.
A new [`close()`](../library/os.xhtml#os.scandir.close "os.scandir.close") method allows explicitly closing a [`scandir()`](../library/os.xhtml#os.scandir "os.scandir") iterator. The [`scandir()`](../library/os.xhtml#os.scandir "os.scandir") iterator now supports the [context manager](../glossary.xhtml#term-context-manager) protocol. If a `scandir()`iterator is neither exhausted nor explicitly closed a [`ResourceWarning`](../library/exceptions.xhtml#ResourceWarning "ResourceWarning")will be emitted in its destructor. (Contributed by Serhiy Storchaka in [bpo-25994](https://bugs.python.org/issue25994) \[https://bugs.python.org/issue25994\].)
On Linux, [`os.urandom()`](../library/os.xhtml#os.urandom "os.urandom") now blocks until the system urandom entropy pool is initialized to increase the security. See the [**PEP 524**](https://www.python.org/dev/peps/pep-0524) \[https://www.python.org/dev/peps/pep-0524\] for the rationale.
The Linux `getrandom()` syscall (get random bytes) is now exposed as the new [`os.getrandom()`](../library/os.xhtml#os.getrandom "os.getrandom") function. (Contributed by Victor Stinner, part of the [**PEP 524**](https://www.python.org/dev/peps/pep-0524) \[https://www.python.org/dev/peps/pep-0524\])
### pathlib
[`pathlib`](../library/pathlib.xhtml#module-pathlib "pathlib: Object-oriented filesystem paths") now supports [path-like objects](../glossary.xhtml#term-path-like-object). (Contributed by Brett Cannon in [bpo-27186](https://bugs.python.org/issue27186) \[https://bugs.python.org/issue27186\].)
See the summary of [PEP 519](#whatsnew36-pep519) for details.
### pdb
The [`Pdb`](../library/pdb.xhtml#pdb.Pdb "pdb.Pdb") class constructor has a new optional *readrc* argument to control whether `.pdbrc` files should be read.
### pickle
Objects that need `__new__` called with keyword arguments can now be pickled using [pickle protocols](../library/pickle.xhtml#pickle-protocols) older than protocol version 4. Protocol version 4 already supports this case. (Contributed by Serhiy Storchaka in [bpo-24164](https://bugs.python.org/issue24164) \[https://bugs.python.org/issue24164\].)
### pickletools
[`pickletools.dis()`](../library/pickletools.xhtml#pickletools.dis "pickletools.dis") now outputs the implicit memo index for the `MEMOIZE` opcode. (Contributed by Serhiy Storchaka in [bpo-25382](https://bugs.python.org/issue25382) \[https://bugs.python.org/issue25382\].)
### pydoc
The [`pydoc`](../library/pydoc.xhtml#module-pydoc "pydoc: Documentation generator and online help system.") module has learned to respect the `MANPAGER`environment variable. (Contributed by Matthias Klose in [bpo-8637](https://bugs.python.org/issue8637) \[https://bugs.python.org/issue8637\].)
[`help()`](../library/functions.xhtml#help "help") and [`pydoc`](../library/pydoc.xhtml#module-pydoc "pydoc: Documentation generator and online help system.") can now list named tuple fields in the order they were defined rather than alphabetically. (Contributed by Raymond Hettinger in [bpo-24879](https://bugs.python.org/issue24879) \[https://bugs.python.org/issue24879\].)
### random
The new [`choices()`](../library/random.xhtml#random.choices "random.choices") function returns a list of elements of specified size from the given population with optional weights. (Contributed by Raymond Hettinger in [bpo-18844](https://bugs.python.org/issue18844) \[https://bugs.python.org/issue18844\].)
### re
Added support of modifier spans in regular expressions. Examples: `'(?i:p)ython'` matches `'python'` and `'Python'`, but not `'PYTHON'`; `'(?i)g(?-i:v)r'` matches `'GvR'` and `'gvr'`, but not `'GVR'`. (Contributed by Serhiy Storchaka in [bpo-433028](https://bugs.python.org/issue433028) \[https://bugs.python.org/issue433028\].)
Match object groups can be accessed by `__getitem__`, which is equivalent to `group()`. So `mo['name']` is now equivalent to `mo.group('name')`. (Contributed by Eric Smith in [bpo-24454](https://bugs.python.org/issue24454) \[https://bugs.python.org/issue24454\].)
`Match` objects now support [`index-like objects`](../reference/datamodel.xhtml#object.__index__ "object.__index__") as group indices. (Contributed by Jeroen Demeyer and Xiang Zhang in [bpo-27177](https://bugs.python.org/issue27177) \[https://bugs.python.org/issue27177\].)
### readline
Added [`set_auto_history()`](../library/readline.xhtml#readline.set_auto_history "readline.set_auto_history") to enable or disable automatic addition of input to the history list. (Contributed by Tyler Crompton in [bpo-26870](https://bugs.python.org/issue26870) \[https://bugs.python.org/issue26870\].)
### rlcompleter
Private and special attribute names now are omitted unless the prefix starts with underscores. A space or a colon is added after some completed keywords. (Contributed by Serhiy Storchaka in [bpo-25011](https://bugs.python.org/issue25011) \[https://bugs.python.org/issue25011\] and [bpo-25209](https://bugs.python.org/issue25209) \[https://bugs.python.org/issue25209\].)
### shlex
The [`shlex`](../library/shlex.xhtml#shlex.shlex "shlex.shlex") has much [improved shell compatibility](../library/shlex.xhtml#improved-shell-compatibility)through the new *punctuation\_chars* argument to control which characters are treated as punctuation. (Contributed by Vinay Sajip in [bpo-1521950](https://bugs.python.org/issue1521950) \[https://bugs.python.org/issue1521950\].)
### site
When specifying paths to add to [`sys.path`](../library/sys.xhtml#sys.path "sys.path") in a .pth file, you may now specify file paths on top of directories (e.g. zip files). (Contributed by Wolfgang Langner in [bpo-26587](https://bugs.python.org/issue26587) \[https://bugs.python.org/issue26587\]).
### sqlite3
[`sqlite3.Cursor.lastrowid`](../library/sqlite3.xhtml#sqlite3.Cursor.lastrowid "sqlite3.Cursor.lastrowid") now supports the `REPLACE` statement. (Contributed by Alex LordThorsen in [bpo-16864](https://bugs.python.org/issue16864) \[https://bugs.python.org/issue16864\].)
### socket
The [`ioctl()`](../library/socket.xhtml#socket.socket.ioctl "socket.socket.ioctl") function now supports the [`SIO_LOOPBACK_FAST_PATH`](../library/socket.xhtml#socket.SIO_LOOPBACK_FAST_PATH "socket.SIO_LOOPBACK_FAST_PATH") control code. (Contributed by Daniel Stokes in [bpo-26536](https://bugs.python.org/issue26536) \[https://bugs.python.org/issue26536\].)
The [`getsockopt()`](../library/socket.xhtml#socket.socket.getsockopt "socket.socket.getsockopt") constants `SO_DOMAIN`, `SO_PROTOCOL`, `SO_PEERSEC`, and `SO_PASSSEC` are now supported. (Contributed by Christian Heimes in [bpo-26907](https://bugs.python.org/issue26907) \[https://bugs.python.org/issue26907\].)
The [`setsockopt()`](../library/socket.xhtml#socket.socket.setsockopt "socket.socket.setsockopt") now supports the `setsockopt(level, optname, None, optlen: int)` form. (Contributed by Christian Heimes in [bpo-27744](https://bugs.python.org/issue27744) \[https://bugs.python.org/issue27744\].)
The socket module now supports the address family [`AF_ALG`](../library/socket.xhtml#socket.AF_ALG "socket.AF_ALG") to interface with Linux Kernel crypto API. `ALG_*`, `SOL_ALG` and [`sendmsg_afalg()`](../library/socket.xhtml#socket.socket.sendmsg_afalg "socket.socket.sendmsg_afalg") were added. (Contributed by Christian Heimes in [bpo-27744](https://bugs.python.org/issue27744) \[https://bugs.python.org/issue27744\] with support from Victor Stinner.)
New Linux constants `TCP_USER_TIMEOUT` and `TCP_CONGESTION` were added. (Contributed by Omar Sandoval, issue:26273).
### socketserver
Servers based on the [`socketserver`](../library/socketserver.xhtml#module-socketserver "socketserver: A framework for network servers.") module, including those defined in [`http.server`](../library/http.server.xhtml#module-http.server "http.server: HTTP server and request handlers."), [`xmlrpc.server`](../library/xmlrpc.server.xhtml#module-xmlrpc.server "xmlrpc.server: Basic XML-RPC server implementations.") and [`wsgiref.simple_server`](../library/wsgiref.xhtml#module-wsgiref.simple_server "wsgiref.simple_server: A simple WSGI HTTP server."), now support the [context manager](../glossary.xhtml#term-context-manager)protocol. (Contributed by Aviv Palivoda in [bpo-26404](https://bugs.python.org/issue26404) \[https://bugs.python.org/issue26404\].)
The `wfile` attribute of [`StreamRequestHandler`](../library/socketserver.xhtml#socketserver.StreamRequestHandler "socketserver.StreamRequestHandler") classes now implements the [`io.BufferedIOBase`](../library/io.xhtml#io.BufferedIOBase "io.BufferedIOBase") writable interface. In particular, calling [`write()`](../library/io.xhtml#io.BufferedIOBase.write "io.BufferedIOBase.write") is now guaranteed to send the data in full. (Contributed by Martin Panter in [bpo-26721](https://bugs.python.org/issue26721) \[https://bugs.python.org/issue26721\].)
### ssl
[`ssl`](../library/ssl.xhtml#module-ssl "ssl: TLS/SSL wrapper for socket objects") supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2. (Contributed by Christian Heimes in [bpo-26470](https://bugs.python.org/issue26470) \[https://bugs.python.org/issue26470\].)
3DES has been removed from the default cipher suites and ChaCha20 Poly1305 cipher suites have been added. (Contributed by Christian Heimes in [bpo-27850](https://bugs.python.org/issue27850) \[https://bugs.python.org/issue27850\] and [bpo-27766](https://bugs.python.org/issue27766) \[https://bugs.python.org/issue27766\].)
[`SSLContext`](../library/ssl.xhtml#ssl.SSLContext "ssl.SSLContext") has better default configuration for options and ciphers. (Contributed by Christian Heimes in [bpo-28043](https://bugs.python.org/issue28043) \[https://bugs.python.org/issue28043\].)
SSL session can be copied from one client-side connection to another with the new [`SSLSession`](../library/ssl.xhtml#ssl.SSLSession "ssl.SSLSession") class. TLS session resumption can speed up the initial handshake, reduce latency and improve performance (Contributed by Christian Heimes in [bpo-19500](https://bugs.python.org/issue19500) \[https://bugs.python.org/issue19500\] based on a draft by Alex Warhawk.)
The new [`get_ciphers()`](../library/ssl.xhtml#ssl.SSLContext.get_ciphers "ssl.SSLContext.get_ciphers") method can be used to get a list of enabled ciphers in order of cipher priority.
All constants and flags have been converted to [`IntEnum`](../library/enum.xhtml#enum.IntEnum "enum.IntEnum") and `IntFlags`. (Contributed by Christian Heimes in [bpo-28025](https://bugs.python.org/issue28025) \[https://bugs.python.org/issue28025\].)
Server and client-side specific TLS protocols for [`SSLContext`](../library/ssl.xhtml#ssl.SSLContext "ssl.SSLContext")were added. (Contributed by Christian Heimes in [bpo-28085](https://bugs.python.org/issue28085) \[https://bugs.python.org/issue28085\].)
### statistics
A new [`harmonic_mean()`](../library/statistics.xhtml#statistics.harmonic_mean "statistics.harmonic_mean") function has been added. (Contributed by Steven D'Aprano in [bpo-27181](https://bugs.python.org/issue27181) \[https://bugs.python.org/issue27181\].)
### struct
[`struct`](../library/struct.xhtml#module-struct "struct: Interpret bytes as packed binary data.") now supports IEEE 754 half-precision floats via the `'e'`format specifier. (Contributed by Eli Stevens, Mark Dickinson in [bpo-11734](https://bugs.python.org/issue11734) \[https://bugs.python.org/issue11734\].)
### subprocess
[`subprocess.Popen`](../library/subprocess.xhtml#subprocess.Popen "subprocess.Popen") destructor now emits a [`ResourceWarning`](../library/exceptions.xhtml#ResourceWarning "ResourceWarning") warning if the child process is still running. Use the context manager protocol (
```
with
proc: ...
```
) or explicitly call the [`wait()`](../library/subprocess.xhtml#subprocess.Popen.wait "subprocess.Popen.wait") method to read the exit status of the child process. (Contributed by Victor Stinner in [bpo-26741](https://bugs.python.org/issue26741) \[https://bugs.python.org/issue26741\].)
The [`subprocess.Popen`](../library/subprocess.xhtml#subprocess.Popen "subprocess.Popen") constructor and all functions that pass arguments through to it now accept *encoding* and *errors* arguments. Specifying either of these will enable text mode for the *stdin*, *stdout* and *stderr* streams. (Contributed by Steve Dower in [bpo-6135](https://bugs.python.org/issue6135) \[https://bugs.python.org/issue6135\].)
### sys
The new [`getfilesystemencodeerrors()`](../library/sys.xhtml#sys.getfilesystemencodeerrors "sys.getfilesystemencodeerrors") function returns the name of the error mode used to convert between Unicode filenames and bytes filenames. (Contributed by Steve Dower in [bpo-27781](https://bugs.python.org/issue27781) \[https://bugs.python.org/issue27781\].)
On Windows the return value of the [`getwindowsversion()`](../library/sys.xhtml#sys.getwindowsversion "sys.getwindowsversion") function now includes the *platform\_version* field which contains the accurate major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process (Contributed by Steve Dower in [bpo-27932](https://bugs.python.org/issue27932) \[https://bugs.python.org/issue27932\].)
### telnetlib
[`Telnet`](../library/telnetlib.xhtml#telnetlib.Telnet "telnetlib.Telnet") is now a context manager (contributed by Stéphane Wirtel in [bpo-25485](https://bugs.python.org/issue25485) \[https://bugs.python.org/issue25485\]).
### time
The [`struct_time`](../library/time.xhtml#time.struct_time "time.struct_time") attributes `tm_gmtoff` and `tm_zone` are now available on all platforms.
### timeit
The new [`Timer.autorange()`](../library/timeit.xhtml#timeit.Timer.autorange "timeit.Timer.autorange") convenience method has been added to call [`Timer.timeit()`](../library/timeit.xhtml#timeit.Timer.timeit "timeit.Timer.timeit")repeatedly so that the total run time is greater or equal to 200 milliseconds. (Contributed by Steven D'Aprano in [bpo-6422](https://bugs.python.org/issue6422) \[https://bugs.python.org/issue6422\].)
[`timeit`](../library/timeit.xhtml#module-timeit "timeit: Measure the execution time of small code snippets.") now warns when there is substantial (4x) variance between best and worst times. (Contributed by Serhiy Storchaka in [bpo-23552](https://bugs.python.org/issue23552) \[https://bugs.python.org/issue23552\].)
### tkinter
Added methods `trace_add()`, `trace_remove()` and `trace_info()`in the `tkinter.Variable` class. They replace old methods `trace_variable()`, `trace()`, `trace_vdelete()` and `trace_vinfo()` that use obsolete Tcl commands and might not work in future versions of Tcl. (Contributed by Serhiy Storchaka in [bpo-22115](https://bugs.python.org/issue22115) \[https://bugs.python.org/issue22115\]).
### traceback
Both the traceback module and the interpreter's builtin exception display now abbreviate long sequences of repeated lines in tracebacks as shown in the following example:
```
>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in f
File "<stdin>", line 1, in f
File "<stdin>", line 1, in f
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
```
(Contributed by Emanuel Barry in [bpo-26823](https://bugs.python.org/issue26823) \[https://bugs.python.org/issue26823\].)
### tracemalloc
The [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") module now supports tracing memory allocations in multiple different address spaces.
The new [`DomainFilter`](../library/tracemalloc.xhtml#tracemalloc.DomainFilter "tracemalloc.DomainFilter") filter class has been added to filter block traces by their address space (domain).
(Contributed by Victor Stinner in [bpo-26588](https://bugs.python.org/issue26588) \[https://bugs.python.org/issue26588\].)
### typing
Since the [`typing`](../library/typing.xhtml#module-typing "typing: Support for type hints (see PEP 484).") module is [provisional](../glossary.xhtml#term-provisional-api), all changes introduced in Python 3.6 have also been backported to Python 3.5.x.
The [`typing`](../library/typing.xhtml#module-typing "typing: Support for type hints (see PEP 484).") module has a much improved support for generic type aliases. For example `Dict[str, Tuple[S, T]]` is now a valid type annotation. (Contributed by Guido van Rossum in [Github #195](https://github.com/python/typing/pull/195) \[https://github.com/python/typing/pull/195\].)
The [`typing.ContextManager`](../library/typing.xhtml#typing.ContextManager "typing.ContextManager") class has been added for representing [`contextlib.AbstractContextManager`](../library/contextlib.xhtml#contextlib.AbstractContextManager "contextlib.AbstractContextManager"). (Contributed by Brett Cannon in [bpo-25609](https://bugs.python.org/issue25609) \[https://bugs.python.org/issue25609\].)
The [`typing.Collection`](../library/typing.xhtml#typing.Collection "typing.Collection") class has been added for representing [`collections.abc.Collection`](../library/collections.abc.xhtml#collections.abc.Collection "collections.abc.Collection"). (Contributed by Ivan Levkivskyi in [bpo-27598](https://bugs.python.org/issue27598) \[https://bugs.python.org/issue27598\].)
The [`typing.ClassVar`](../library/typing.xhtml#typing.ClassVar "typing.ClassVar") type construct has been added to mark class variables. As introduced in [**PEP 526**](https://www.python.org/dev/peps/pep-0526) \[https://www.python.org/dev/peps/pep-0526\], a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. (Contributed by Ivan Levkivskyi in [Github #280](https://github.com/python/typing/pull/280) \[https://github.com/python/typing/pull/280\].)
A new [`TYPE_CHECKING`](../library/typing.xhtml#typing.TYPE_CHECKING "typing.TYPE_CHECKING") constant that is assumed to be `True` by the static type checkers, but is `False` at runtime. (Contributed by Guido van Rossum in [Github #230](https://github.com/python/typing/issues/230) \[https://github.com/python/typing/issues/230\].)
A new [`NewType()`](../library/typing.xhtml#typing.NewType "typing.NewType") helper function has been added to create lightweight distinct types for annotations:
```
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
```
The static type checker will treat the new type as if it were a subclass of the original type. (Contributed by Ivan Levkivskyi in [Github #189](https://github.com/python/typing/issues/189) \[https://github.com/python/typing/issues/189\].)
### unicodedata
The [`unicodedata`](../library/unicodedata.xhtml#module-unicodedata "unicodedata: Access the Unicode Database.") module now uses data from [Unicode 9.0.0](http://unicode.org/versions/Unicode9.0.0/) \[http://unicode.org/versions/Unicode9.0.0/\]. (Contributed by Benjamin Peterson.)
### unittest.mock
The [`Mock`](../library/unittest.mock.xhtml#unittest.mock.Mock "unittest.mock.Mock") class has the following improvements:
- Two new methods, [`Mock.assert_called()`](../library/unittest.mock.xhtml#unittest.mock.Mock.assert_called "unittest.mock.Mock.assert_called") and [`Mock.assert_called_once()`](../library/unittest.mock.xhtml#unittest.mock.Mock.assert_called_once "unittest.mock.Mock.assert_called_once") to check if the mock object was called. (Contributed by Amit Saha in [bpo-26323](https://bugs.python.org/issue26323) \[https://bugs.python.org/issue26323\].)
- The [`Mock.reset_mock()`](../library/unittest.mock.xhtml#unittest.mock.Mock.reset_mock "unittest.mock.Mock.reset_mock") method now has two optional keyword only arguments: *return\_value* and *side\_effect*. (Contributed by Kushal Das in [bpo-21271](https://bugs.python.org/issue21271) \[https://bugs.python.org/issue21271\].)
### urllib.request
If a HTTP request has a file or iterable body (other than a bytes object) but no `Content-Length` header, rather than throwing an error, `AbstractHTTPHandler` now falls back to use chunked transfer encoding. (Contributed by Demian Brecht and Rolf Krahl in [bpo-12319](https://bugs.python.org/issue12319) \[https://bugs.python.org/issue12319\].)
### urllib.robotparser
[`RobotFileParser`](../library/urllib.robotparser.xhtml#urllib.robotparser.RobotFileParser "urllib.robotparser.RobotFileParser") now supports the `Crawl-delay` and `Request-rate` extensions. (Contributed by Nikolay Bogoychev in [bpo-16099](https://bugs.python.org/issue16099) \[https://bugs.python.org/issue16099\].)
### venv
[`venv`](../library/venv.xhtml#module-venv "venv: Creation of virtual environments.") accepts a new parameter `--prompt`. This parameter provides an alternative prefix for the virtual environment. (Proposed by ?ukasz Balcerzak and ported to 3.6 by Stéphane Wirtel in [bpo-22829](https://bugs.python.org/issue22829) \[https://bugs.python.org/issue22829\].)
### warnings
A new optional *source* parameter has been added to the [`warnings.warn_explicit()`](../library/warnings.xhtml#warnings.warn_explicit "warnings.warn_explicit") function: the destroyed object which emitted a [`ResourceWarning`](../library/exceptions.xhtml#ResourceWarning "ResourceWarning"). A *source* attribute has also been added to `warnings.WarningMessage` (contributed by Victor Stinner in [bpo-26568](https://bugs.python.org/issue26568) \[https://bugs.python.org/issue26568\] and [bpo-26567](https://bugs.python.org/issue26567) \[https://bugs.python.org/issue26567\]).
When a [`ResourceWarning`](../library/exceptions.xhtml#ResourceWarning "ResourceWarning") warning is logged, the [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") module is now used to try to retrieve the traceback where the destroyed object was allocated.
Example with the script `example.py`:
```
import warnings
def func():
return open(__file__)
f = func()
f = None
```
Output of the command `python3.6 -Wd -X tracemalloc=5 example.py`:
```
example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
f = None
Object allocated at (most recent call first):
File "example.py", lineno 4
return open(__file__)
File "example.py", lineno 6
f = func()
```
The "Object allocated at" traceback is new and is only displayed if [`tracemalloc`](../library/tracemalloc.xhtml#module-tracemalloc "tracemalloc: Trace memory allocations.") is tracing Python memory allocations and if the [`warnings`](../library/warnings.xhtml#module-warnings "warnings: Issue warning messages and control their disposition.") module was already imported.
### winreg
Added the 64-bit integer type [`REG_QWORD`](../library/winreg.xhtml#winreg.REG_QWORD "winreg.REG_QWORD"). (Contributed by Clement Rouault in [bpo-23026](https://bugs.python.org/issue23026) \[https://bugs.python.org/issue23026\].)
### winsound
Allowed keyword arguments to be passed to [`Beep`](../library/winsound.xhtml#winsound.Beep "winsound.Beep"), [`MessageBeep`](../library/winsound.xhtml#winsound.MessageBeep "winsound.MessageBeep"), and [`PlaySound`](../library/winsound.xhtml#winsound.PlaySound "winsound.PlaySound") ([bpo-27982](https://bugs.python.org/issue27982) \[https://bugs.python.org/issue27982\]).
### xmlrpc.client
The [`xmlrpc.client`](../library/xmlrpc.client.xhtml#module-xmlrpc.client "xmlrpc.client: XML-RPC client access.") module now supports unmarshalling additional data types used by the Apache XML-RPC implementation for numerics and `None`. (Contributed by Serhiy Storchaka in [bpo-26885](https://bugs.python.org/issue26885) \[https://bugs.python.org/issue26885\].)
### zipfile
A new [`ZipInfo.from_file()`](../library/zipfile.xhtml#zipfile.ZipInfo.from_file "zipfile.ZipInfo.from_file") class method allows making a [`ZipInfo`](../library/zipfile.xhtml#zipfile.ZipInfo "zipfile.ZipInfo") instance from a filesystem file. A new [`ZipInfo.is_dir()`](../library/zipfile.xhtml#zipfile.ZipInfo.is_dir "zipfile.ZipInfo.is_dir") method can be used to check if the [`ZipInfo`](../library/zipfile.xhtml#zipfile.ZipInfo "zipfile.ZipInfo") instance represents a directory. (Contributed by Thomas Kluyver in [bpo-26039](https://bugs.python.org/issue26039) \[https://bugs.python.org/issue26039\].)
The [`ZipFile.open()`](../library/zipfile.xhtml#zipfile.ZipFile.open "zipfile.ZipFile.open") method can now be used to write data into a ZIP file, as well as for extracting data. (Contributed by Thomas Kluyver in [bpo-26039](https://bugs.python.org/issue26039) \[https://bugs.python.org/issue26039\].)
### zlib
The [`compress()`](../library/zlib.xhtml#zlib.compress "zlib.compress") and [`decompress()`](../library/zlib.xhtml#zlib.decompress "zlib.decompress") functions now accept keyword arguments. (Contributed by Aviv Palivoda in [bpo-26243](https://bugs.python.org/issue26243) \[https://bugs.python.org/issue26243\] and Xiang Zhang in [bpo-16764](https://bugs.python.org/issue16764) \[https://bugs.python.org/issue16764\] respectively.)
## 性能優化
- The Python interpreter now uses a 16-bit wordcode instead of bytecode which made a number of opcode optimizations possible. (Contributed by Demur Rumed with input and reviews from Serhiy Storchaka and Victor Stinner in [bpo-26647](https://bugs.python.org/issue26647) \[https://bugs.python.org/issue26647\] and [bpo-28050](https://bugs.python.org/issue28050) \[https://bugs.python.org/issue28050\].)
- The [`asyncio.Future`](../library/asyncio-future.xhtml#asyncio.Future "asyncio.Future") class now has an optimized C implementation. (Contributed by Yury Selivanov and INADA Naoki in [bpo-26081](https://bugs.python.org/issue26081) \[https://bugs.python.org/issue26081\].)
- The [`asyncio.Task`](../library/asyncio-task.xhtml#asyncio.Task "asyncio.Task") class now has an optimized C implementation. (Contributed by Yury Selivanov in [bpo-28544](https://bugs.python.org/issue28544) \[https://bugs.python.org/issue28544\].)
- Various implementation improvements in the [`typing`](../library/typing.xhtml#module-typing "typing: Support for type hints (see PEP 484).") module (such as caching of generic types) allow up to 30 times performance improvements and reduced memory footprint.
- The ASCII decoder is now up to 60 times as fast for error handlers `surrogateescape`, `ignore` and `replace` (Contributed by Victor Stinner in [bpo-24870](https://bugs.python.org/issue24870) \[https://bugs.python.org/issue24870\]).
- The ASCII and the Latin1 encoders are now up to 3 times as fast for the error handler `surrogateescape`(Contributed by Victor Stinner in [bpo-25227](https://bugs.python.org/issue25227) \[https://bugs.python.org/issue25227\]).
- The UTF-8 encoder is now up to 75 times as fast for error handlers `ignore`, `replace`, `surrogateescape`, `surrogatepass` (Contributed by Victor Stinner in [bpo-25267](https://bugs.python.org/issue25267) \[https://bugs.python.org/issue25267\]).
- The UTF-8 decoder is now up to 15 times as fast for error handlers `ignore`, `replace` and `surrogateescape` (Contributed by Victor Stinner in [bpo-25301](https://bugs.python.org/issue25301) \[https://bugs.python.org/issue25301\]).
- `bytes % args` is now up to 2 times faster. (Contributed by Victor Stinner in [bpo-25349](https://bugs.python.org/issue25349) \[https://bugs.python.org/issue25349\]).
- `bytearray % args` is now between 2.5 and 5 times faster. (Contributed by Victor Stinner in [bpo-25399](https://bugs.python.org/issue25399) \[https://bugs.python.org/issue25399\]).
- Optimize [`bytes.fromhex()`](../library/stdtypes.xhtml#bytes.fromhex "bytes.fromhex") and [`bytearray.fromhex()`](../library/stdtypes.xhtml#bytearray.fromhex "bytearray.fromhex"): they are now between 2x and 3.5x faster. (Contributed by Victor Stinner in [bpo-25401](https://bugs.python.org/issue25401) \[https://bugs.python.org/issue25401\]).
- Optimize `bytes.replace(b'', b'.')` and `bytearray.replace(b'', b'.')`: up to 80% faster. (Contributed by Josh Snider in [bpo-26574](https://bugs.python.org/issue26574) \[https://bugs.python.org/issue26574\]).
- Allocator functions of the [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc") domain ([`PYMEM_DOMAIN_MEM`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM")) now use the [pymalloc memory allocator](../c-api/memory.xhtml#pymalloc) instead of `malloc()` function of the C library. The pymalloc allocator is optimized for objects smaller or equal to 512 bytes with a short lifetime, and use `malloc()` for larger memory blocks. (Contributed by Victor Stinner in [bpo-26249](https://bugs.python.org/issue26249) \[https://bugs.python.org/issue26249\]).
- [`pickle.load()`](../library/pickle.xhtml#pickle.load "pickle.load") and [`pickle.loads()`](../library/pickle.xhtml#pickle.loads "pickle.loads") are now up to 10% faster when deserializing many small objects (Contributed by Victor Stinner in [bpo-27056](https://bugs.python.org/issue27056) \[https://bugs.python.org/issue27056\]).
- Passing [keyword arguments](../glossary.xhtml#term-keyword-argument) to a function has an overhead in comparison with passing [positional arguments](../glossary.xhtml#term-positional-argument). Now in extension functions implemented with using Argument Clinic this overhead is significantly decreased. (Contributed by Serhiy Storchaka in [bpo-27574](https://bugs.python.org/issue27574) \[https://bugs.python.org/issue27574\]).
- Optimized [`glob()`](../library/glob.xhtml#glob.glob "glob.glob") and [`iglob()`](../library/glob.xhtml#glob.iglob "glob.iglob") functions in the [`glob`](../library/glob.xhtml#module-glob "glob: Unix shell style pathname pattern expansion.") module; they are now about 3--6 times faster. (Contributed by Serhiy Storchaka in [bpo-25596](https://bugs.python.org/issue25596) \[https://bugs.python.org/issue25596\]).
- Optimized globbing in [`pathlib`](../library/pathlib.xhtml#module-pathlib "pathlib: Object-oriented filesystem paths") by using [`os.scandir()`](../library/os.xhtml#os.scandir "os.scandir"); it is now about 1.5--4 times faster. (Contributed by Serhiy Storchaka in [bpo-26032](https://bugs.python.org/issue26032) \[https://bugs.python.org/issue26032\]).
- [`xml.etree.ElementTree`](../library/xml.etree.elementtree.xhtml#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API.") parsing, iteration and deepcopy performance has been significantly improved. (Contributed by Serhiy Storchaka in [bpo-25638](https://bugs.python.org/issue25638) \[https://bugs.python.org/issue25638\], [bpo-25873](https://bugs.python.org/issue25873) \[https://bugs.python.org/issue25873\], and [bpo-25869](https://bugs.python.org/issue25869) \[https://bugs.python.org/issue25869\].)
- Creation of [`fractions.Fraction`](../library/fractions.xhtml#fractions.Fraction "fractions.Fraction") instances from floats and decimals is now 2 to 3 times faster. (Contributed by Serhiy Storchaka in [bpo-25971](https://bugs.python.org/issue25971) \[https://bugs.python.org/issue25971\].)
## Build and C API Changes
- Python now requires some C99 support in the toolchain to build. Most notably, Python now uses standard integer types and macros in place of custom macros like `PY_LONG_LONG`. For more information, see [**PEP 7**](https://www.python.org/dev/peps/pep-0007) \[https://www.python.org/dev/peps/pep-0007\] and [bpo-17884](https://bugs.python.org/issue17884) \[https://bugs.python.org/issue17884\].
- Cross-compiling CPython with the Android NDK and the Android API level set to 21 (Android 5.0 Lollipop) or greater runs successfully. While Android is not yet a supported platform, the Python test suite runs on the Android emulator with only about 16 tests failures. See the Android meta-issue [bpo-26865](https://bugs.python.org/issue26865) \[https://bugs.python.org/issue26865\].
- The `--enable-optimizations` configure flag has been added. Turning it on will activate expensive optimizations like PGO. (Original patch by Alecsandru Patrascu of Intel in [bpo-26359](https://bugs.python.org/issue26359) \[https://bugs.python.org/issue26359\].)
- The [GIL](../glossary.xhtml#term-global-interpreter-lock) must now be held when allocator functions of [`PYMEM_DOMAIN_OBJ`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_OBJ "PYMEM_DOMAIN_OBJ") (ex: [`PyObject_Malloc()`](../c-api/memory.xhtml#c.PyObject_Malloc "PyObject_Malloc")) and [`PYMEM_DOMAIN_MEM`](../c-api/memory.xhtml#c.PYMEM_DOMAIN_MEM "PYMEM_DOMAIN_MEM") (ex: [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc")) domains are called.
- New [`Py_FinalizeEx()`](../c-api/init.xhtml#c.Py_FinalizeEx "Py_FinalizeEx") API which indicates if flushing buffered data failed. (Contributed by Martin Panter in [bpo-5319](https://bugs.python.org/issue5319) \[https://bugs.python.org/issue5319\].)
- [`PyArg_ParseTupleAndKeywords()`](../c-api/arg.xhtml#c.PyArg_ParseTupleAndKeywords "PyArg_ParseTupleAndKeywords") now supports [positional-only parameters](../glossary.xhtml#positional-only-parameter). Positional-only parameters are defined by empty names. (Contributed by Serhiy Storchaka in [bpo-26282](https://bugs.python.org/issue26282) \[https://bugs.python.org/issue26282\]).
- `PyTraceback_Print` method now abbreviates long sequences of repeated lines as `"[Previous line repeated {count} more times]"`. (Contributed by Emanuel Barry in [bpo-26823](https://bugs.python.org/issue26823) \[https://bugs.python.org/issue26823\].)
- The new [`PyErr_SetImportErrorSubclass()`](../c-api/exceptions.xhtml#c.PyErr_SetImportErrorSubclass "PyErr_SetImportErrorSubclass") function allows for specifying a subclass of [`ImportError`](../library/exceptions.xhtml#ImportError "ImportError") to raise. (Contributed by Eric Snow in [bpo-15767](https://bugs.python.org/issue15767) \[https://bugs.python.org/issue15767\].)
- The new [`PyErr_ResourceWarning()`](../c-api/exceptions.xhtml#c.PyErr_ResourceWarning "PyErr_ResourceWarning") function can be used to generate a [`ResourceWarning`](../library/exceptions.xhtml#ResourceWarning "ResourceWarning") providing the source of the resource allocation. (Contributed by Victor Stinner in [bpo-26567](https://bugs.python.org/issue26567) \[https://bugs.python.org/issue26567\].)
- The new [`PyOS_FSPath()`](../c-api/sys.xhtml#c.PyOS_FSPath "PyOS_FSPath") function returns the file system representation of a [path-like object](../glossary.xhtml#term-path-like-object). (Contributed by Brett Cannon in [bpo-27186](https://bugs.python.org/issue27186) \[https://bugs.python.org/issue27186\].)
- The [`PyUnicode_FSConverter()`](../c-api/unicode.xhtml#c.PyUnicode_FSConverter "PyUnicode_FSConverter") and [`PyUnicode_FSDecoder()`](../c-api/unicode.xhtml#c.PyUnicode_FSDecoder "PyUnicode_FSDecoder")functions will now accept [path-like objects](../glossary.xhtml#term-path-like-object).
## 其他改進
- When [`--version`](../using/cmdline.xhtml#cmdoption-version) (short form: [`-V`](../using/cmdline.xhtml#cmdoption-v)) is supplied twice, Python prints [`sys.version`](../library/sys.xhtml#sys.version "sys.version") for detailed information.
```
$ ./python -VV
Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
```
## 棄用
### New Keywords
`async` and `await` are not recommended to be used as variable, class, function or module names. Introduced by [**PEP 492**](https://www.python.org/dev/peps/pep-0492) \[https://www.python.org/dev/peps/pep-0492\] in Python 3.5, they will become proper keywords in Python 3.7. Starting in Python 3.6, the use of `async` or `await` as names will generate a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning").
### 已棄用的 Python 行為
Raising the [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") exception inside a generator will now generate a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning"), and will trigger a [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError")in Python 3.7. See [PEP 479: Change StopIteration handling inside generators](3.5.xhtml#whatsnew-pep-479) for details.
The [`__aiter__()`](../reference/datamodel.xhtml#object.__aiter__ "object.__aiter__") method is now expected to return an asynchronous iterator directly instead of returning an awaitable as previously. Doing the former will trigger a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning"). Backward compatibility will be removed in Python 3.7. (Contributed by Yury Selivanov in [bpo-27243](https://bugs.python.org/issue27243) \[https://bugs.python.org/issue27243\].)
A backslash-character pair that is not a valid escape sequence now generates a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning"). Although this will eventually become a [`SyntaxError`](../library/exceptions.xhtml#SyntaxError "SyntaxError"), that will not be for several Python releases. (Contributed by Emanuel Barry in [bpo-27364](https://bugs.python.org/issue27364) \[https://bugs.python.org/issue27364\].)
When performing a relative import, falling back on `__name__` and `__path__` from the calling module when `__spec__` or `__package__` are not defined now raises an [`ImportWarning`](../library/exceptions.xhtml#ImportWarning "ImportWarning"). (Contributed by Rose Ames in [bpo-25791](https://bugs.python.org/issue25791) \[https://bugs.python.org/issue25791\].)
### 已棄用的 Python 模塊、函數和方法
#### asynchat
The [`asynchat`](../library/asynchat.xhtml#module-asynchat "asynchat: Support for asynchronous command/response protocols.") has been deprecated in favor of [`asyncio`](../library/asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O."). (Contributed by Mariatta in [bpo-25002](https://bugs.python.org/issue25002) \[https://bugs.python.org/issue25002\].)
#### asyncore
The [`asyncore`](../library/asyncore.xhtml#module-asyncore "asyncore: A base class for developing asynchronous socket handling services.") has been deprecated in favor of [`asyncio`](../library/asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O."). (Contributed by Mariatta in [bpo-25002](https://bugs.python.org/issue25002) \[https://bugs.python.org/issue25002\].)
#### dbm
Unlike other [`dbm`](../library/dbm.xhtml#module-dbm "dbm: Interfaces to various Unix "database" formats.") implementations, the [`dbm.dumb`](../library/dbm.xhtml#module-dbm.dumb "dbm.dumb: Portable implementation of the simple DBM interface.") module creates databases with the `'rw'` mode and allows modifying the database opened with the `'r'` mode. This behavior is now deprecated and will be removed in 3.8. (Contributed by Serhiy Storchaka in [bpo-21708](https://bugs.python.org/issue21708) \[https://bugs.python.org/issue21708\].)
#### distutils
The undocumented `extra_path` argument to the `Distribution` constructor is now considered deprecated and will raise a warning if set. Support for this parameter will be removed in a future Python release. See [bpo-27919](https://bugs.python.org/issue27919) \[https://bugs.python.org/issue27919\] for details.
#### grp
The support of non-integer arguments in [`getgrgid()`](../library/grp.xhtml#grp.getgrgid "grp.getgrgid") has been deprecated. (Contributed by Serhiy Storchaka in [bpo-26129](https://bugs.python.org/issue26129) \[https://bugs.python.org/issue26129\].)
#### importlib
The [`importlib.machinery.SourceFileLoader.load_module()`](../library/importlib.xhtml#importlib.machinery.SourceFileLoader.load_module "importlib.machinery.SourceFileLoader.load_module") and [`importlib.machinery.SourcelessFileLoader.load_module()`](../library/importlib.xhtml#importlib.machinery.SourcelessFileLoader.load_module "importlib.machinery.SourcelessFileLoader.load_module") methods are now deprecated. They were the only remaining implementations of [`importlib.abc.Loader.load_module()`](../library/importlib.xhtml#importlib.abc.Loader.load_module "importlib.abc.Loader.load_module") in [`importlib`](../library/importlib.xhtml#module-importlib "importlib: The implementation of the import machinery.") that had not been deprecated in previous versions of Python in favour of [`importlib.abc.Loader.exec_module()`](../library/importlib.xhtml#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module").
The [`importlib.machinery.WindowsRegistryFinder`](../library/importlib.xhtml#importlib.machinery.WindowsRegistryFinder "importlib.machinery.WindowsRegistryFinder") class is now deprecated. As of 3.6.0, it is still added to [`sys.meta_path`](../library/sys.xhtml#sys.meta_path "sys.meta_path") by default (on Windows), but this may change in future releases.
#### os
Undocumented support of general [bytes-like objects](../glossary.xhtml#term-bytes-like-object)as paths in [`os`](../library/os.xhtml#module-os "os: Miscellaneous operating system interfaces.") functions, [`compile()`](../library/functions.xhtml#compile "compile") and similar functions is now deprecated. (Contributed by Serhiy Storchaka in [bpo-25791](https://bugs.python.org/issue25791) \[https://bugs.python.org/issue25791\] and [bpo-26754](https://bugs.python.org/issue26754) \[https://bugs.python.org/issue26754\].)
#### re
Support for inline flags `(?letters)` in the middle of the regular expression has been deprecated and will be removed in a future Python version. Flags at the start of a regular expression are still allowed. (Contributed by Serhiy Storchaka in [bpo-22493](https://bugs.python.org/issue22493) \[https://bugs.python.org/issue22493\].)
#### ssl
OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the [`ssl`](../library/ssl.xhtml#module-ssl "ssl: TLS/SSL wrapper for socket objects") module will require at least OpenSSL 1.0.2 or 1.1.0.
SSL-related arguments like `certfile`, `keyfile` and `check_hostname`in [`ftplib`](../library/ftplib.xhtml#module-ftplib "ftplib: FTP protocol client (requires sockets)."), [`http.client`](../library/http.client.xhtml#module-http.client "http.client: HTTP and HTTPS protocol client (requires sockets)."), [`imaplib`](../library/imaplib.xhtml#module-imaplib "imaplib: IMAP4 protocol client (requires sockets)."), [`poplib`](../library/poplib.xhtml#module-poplib "poplib: POP3 protocol client (requires sockets)."), and [`smtplib`](../library/smtplib.xhtml#module-smtplib "smtplib: SMTP protocol client (requires sockets).") have been deprecated in favor of `context`. (Contributed by Christian Heimes in [bpo-28022](https://bugs.python.org/issue28022) \[https://bugs.python.org/issue28022\].)
A couple of protocols and functions of the [`ssl`](../library/ssl.xhtml#module-ssl "ssl: TLS/SSL wrapper for socket objects") module are now deprecated. Some features will no longer be available in future versions of OpenSSL. Other features are deprecated in favor of a different API. (Contributed by Christian Heimes in [bpo-28022](https://bugs.python.org/issue28022) \[https://bugs.python.org/issue28022\] and [bpo-26470](https://bugs.python.org/issue26470) \[https://bugs.python.org/issue26470\].)
#### tkinter
The [`tkinter.tix`](../library/tkinter.tix.xhtml#module-tkinter.tix "tkinter.tix: Tk Extension Widgets for Tkinter") module is now deprecated. [`tkinter`](../library/tkinter.xhtml#module-tkinter "tkinter: Interface to Tcl/Tk for graphical user interfaces") users should use [`tkinter.ttk`](../library/tkinter.ttk.xhtml#module-tkinter.ttk "tkinter.ttk: Tk themed widget set") instead.
#### venv
The `pyvenv` script has been deprecated in favour of `python3 -m venv`. This prevents confusion as to what Python interpreter `pyvenv` is connected to and thus what Python interpreter will be used by the virtual environment. (Contributed by Brett Cannon in [bpo-25154](https://bugs.python.org/issue25154) \[https://bugs.python.org/issue25154\].)
### 已棄用的 C API 函數和類型
Undocumented functions `PyUnicode_AsEncodedObject()`, `PyUnicode_AsDecodedObject()`, `PyUnicode_AsEncodedUnicode()`and `PyUnicode_AsDecodedUnicode()` are deprecated now. Use the [generic codec based API](../c-api/codec.xhtml#codec-registry) instead.
### Deprecated Build Options
The `--with-system-ffi` configure flag is now on by default on non-macOS UNIX platforms. It may be disabled by using `--without-system-ffi`, but using the flag is deprecated and will not be accepted in Python 3.7. macOS is unaffected by this change. Note that many OS distributors already use the `--with-system-ffi` flag when building their system Python.
## 移除
### API 與特性的移除
- Unknown escapes consisting of `'\'` and an ASCII letter in regular expressions will now cause an error. In replacement templates for [`re.sub()`](../library/re.xhtml#re.sub "re.sub") they are still allowed, but deprecated. The [`re.LOCALE`](../library/re.xhtml#re.LOCALE "re.LOCALE") flag can now only be used with binary patterns.
- `inspect.getmoduleinfo()` was removed (was deprecated since CPython 3.3). [`inspect.getmodulename()`](../library/inspect.xhtml#inspect.getmodulename "inspect.getmodulename") should be used for obtaining the module name for a given path. (Contributed by Yury Selivanov in [bpo-13248](https://bugs.python.org/issue13248) \[https://bugs.python.org/issue13248\].)
- `traceback.Ignore` class and `traceback.usage`, `traceback.modname`, `traceback.fullmodname`, `traceback.find_lines_from_code`, `traceback.find_lines`, `traceback.find_strings`, `traceback.find_executable_lines` methods were removed from the [`traceback`](../library/traceback.xhtml#module-traceback "traceback: Print or retrieve a stack traceback.") module. They were undocumented methods deprecated since Python 3.2 and equivalent functionality is available from private methods.
- The `tk_menuBar()` and `tk_bindForTraversal()` dummy methods in [`tkinter`](../library/tkinter.xhtml#module-tkinter "tkinter: Interface to Tcl/Tk for graphical user interfaces") widget classes were removed (corresponding Tk commands were obsolete since Tk 4.0).
- The [`open()`](../library/zipfile.xhtml#zipfile.ZipFile.open "zipfile.ZipFile.open") method of the [`zipfile.ZipFile`](../library/zipfile.xhtml#zipfile.ZipFile "zipfile.ZipFile")class no longer supports the `'U'` mode (was deprecated since Python 3.4). Use [`io.TextIOWrapper`](../library/io.xhtml#io.TextIOWrapper "io.TextIOWrapper") for reading compressed text files in [universal newlines](../glossary.xhtml#term-universal-newlines) mode.
- The undocumented `IN`, `CDROM`, `DLFCN`, `TYPES`, `CDIO`, and `STROPTS` modules have been removed. They had been available in the platform specific `Lib/plat-*/` directories, but were chronically out of date, inconsistently available across platforms, and unmaintained. The script that created these modules is still available in the source distribution at [Tools/scripts/h2py.py](https://github.com/python/cpython/tree/3.7/Tools/scripts/h2py.py) \[https://github.com/python/cpython/tree/3.7/Tools/scripts/h2py.py\].
- The deprecated `asynchat.fifo` class has been removed.
## 移植到Python 3.6
本節列出了先前描述的更改以及可能需要更改代碼的其他錯誤修正.
### 'python' 命令行為的變化
- The output of a special Python build with defined `COUNT_ALLOCS`, `SHOW_ALLOC_COUNT` or `SHOW_TRACK_COUNT` macros is now off by default. It can be re-enabled using the `-X showalloccount` option. It now outputs to `stderr` instead of `stdout`. (Contributed by Serhiy Storchaka in [bpo-23034](https://bugs.python.org/issue23034) \[https://bugs.python.org/issue23034\].)
### 改變了的Python API
- [`open()`](../library/functions.xhtml#open "open") will no longer allow combining the `'U'` mode flag with `'+'`. (Contributed by Jeff Balogh and John O'Connor in [bpo-2091](https://bugs.python.org/issue2091) \[https://bugs.python.org/issue2091\].)
- [`sqlite3`](../library/sqlite3.xhtml#module-sqlite3 "sqlite3: A DB-API 2.0 implementation using SQLite 3.x.") no longer implicitly commits an open transaction before DDL statements.
- On Linux, [`os.urandom()`](../library/os.xhtml#os.urandom "os.urandom") now blocks until the system urandom entropy pool is initialized to increase the security.
- When [`importlib.abc.Loader.exec_module()`](../library/importlib.xhtml#importlib.abc.Loader.exec_module "importlib.abc.Loader.exec_module") is defined, [`importlib.abc.Loader.create_module()`](../library/importlib.xhtml#importlib.abc.Loader.create_module "importlib.abc.Loader.create_module") must also be defined.
- [`PyErr_SetImportError()`](../c-api/exceptions.xhtml#c.PyErr_SetImportError "PyErr_SetImportError") now sets [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") when its **msg**argument is not set. Previously only `NULL` was returned.
- The format of the `co_lnotab` attribute of code objects changed to support a negative line number delta. By default, Python does not emit bytecode with a negative line number delta. Functions using `frame.f_lineno`, `PyFrame_GetLineNumber()` or `PyCode_Addr2Line()` are not affected. Functions directly decoding `co_lnotab` should be updated to use a signed 8-bit integer type for the line number delta, but this is only required to support applications using a negative line number delta. See `Objects/lnotab_notes.txt` for the `co_lnotab` format and how to decode it, and see the [**PEP 511**](https://www.python.org/dev/peps/pep-0511) \[https://www.python.org/dev/peps/pep-0511\] for the rationale.
- The functions in the [`compileall`](../library/compileall.xhtml#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") module now return booleans instead of `1` or `0` to represent success or failure, respectively. Thanks to booleans being a subclass of integers, this should only be an issue if you were doing identity checks for `1` or `0`. See [bpo-25768](https://bugs.python.org/issue25768) \[https://bugs.python.org/issue25768\].
- Reading the `port` attribute of [`urllib.parse.urlsplit()`](../library/urllib.parse.xhtml#urllib.parse.urlsplit "urllib.parse.urlsplit") and [`urlparse()`](../library/urllib.parse.xhtml#urllib.parse.urlparse "urllib.parse.urlparse") results now raises [`ValueError`](../library/exceptions.xhtml#ValueError "ValueError") for out-of-range values, rather than returning [`None`](../library/constants.xhtml#None "None"). See [bpo-20059](https://bugs.python.org/issue20059) \[https://bugs.python.org/issue20059\].
- The [`imp`](../library/imp.xhtml#module-imp "imp: Access the implementation of the import statement. (已移除)") module now raises a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning") instead of [`PendingDeprecationWarning`](../library/exceptions.xhtml#PendingDeprecationWarning "PendingDeprecationWarning").
- The following modules have had missing APIs added to their `__all__`attributes to match the documented APIs: [`calendar`](../library/calendar.xhtml#module-calendar "calendar: Functions for working with calendars, including some emulation of the Unix cal program."), [`cgi`](../library/cgi.xhtml#module-cgi "cgi: Helpers for running Python scripts via the Common Gateway Interface."), [`csv`](../library/csv.xhtml#module-csv "csv: Write and read tabular data to and from delimited files."), [`ElementTree`](../library/xml.etree.elementtree.xhtml#module-xml.etree.ElementTree "xml.etree.ElementTree: Implementation of the ElementTree API."), [`enum`](../library/enum.xhtml#module-enum "enum: Implementation of an enumeration class."), [`fileinput`](../library/fileinput.xhtml#module-fileinput "fileinput: Loop over standard input or a list of files."), [`ftplib`](../library/ftplib.xhtml#module-ftplib "ftplib: FTP protocol client (requires sockets)."), [`logging`](../library/logging.xhtml#module-logging "logging: Flexible event logging system for applications."), [`mailbox`](../library/mailbox.xhtml#module-mailbox "mailbox: Manipulate mailboxes in various formats"), [`mimetypes`](../library/mimetypes.xhtml#module-mimetypes "mimetypes: Mapping of filename extensions to MIME types."), [`optparse`](../library/optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)"), [`plistlib`](../library/plistlib.xhtml#module-plistlib "plistlib: Generate and parse Mac OS X plist files."), [`smtpd`](../library/smtpd.xhtml#module-smtpd "smtpd: A SMTP server implementation in Python."), [`subprocess`](../library/subprocess.xhtml#module-subprocess "subprocess: Subprocess management."), [`tarfile`](../library/tarfile.xhtml#module-tarfile "tarfile: Read and write tar-format archive files."), [`threading`](../library/threading.xhtml#module-threading "threading: Thread-based parallelism.") and [`wave`](../library/wave.xhtml#module-wave "wave: Provide an interface to the WAV sound format."). This means they will export new symbols when `import *`is used. (Contributed by Joel Taddei and Jacek Ko?odziej in [bpo-23883](https://bugs.python.org/issue23883) \[https://bugs.python.org/issue23883\].)
- When performing a relative import, if `__package__` does not compare equal to `__spec__.parent` then [`ImportWarning`](../library/exceptions.xhtml#ImportWarning "ImportWarning") is raised. (Contributed by Brett Cannon in [bpo-25791](https://bugs.python.org/issue25791) \[https://bugs.python.org/issue25791\].)
- When a relative import is performed and no parent package is known, then [`ImportError`](../library/exceptions.xhtml#ImportError "ImportError") will be raised. Previously, [`SystemError`](../library/exceptions.xhtml#SystemError "SystemError") could be raised. (Contributed by Brett Cannon in [bpo-18018](https://bugs.python.org/issue18018) \[https://bugs.python.org/issue18018\].)
- Servers based on the [`socketserver`](../library/socketserver.xhtml#module-socketserver "socketserver: A framework for network servers.") module, including those defined in [`http.server`](../library/http.server.xhtml#module-http.server "http.server: HTTP server and request handlers."), [`xmlrpc.server`](../library/xmlrpc.server.xhtml#module-xmlrpc.server "xmlrpc.server: Basic XML-RPC server implementations.") and [`wsgiref.simple_server`](../library/wsgiref.xhtml#module-wsgiref.simple_server "wsgiref.simple_server: A simple WSGI HTTP server."), now only catch exceptions derived from [`Exception`](../library/exceptions.xhtml#Exception "Exception"). Therefore if a request handler raises an exception like [`SystemExit`](../library/exceptions.xhtml#SystemExit "SystemExit") or [`KeyboardInterrupt`](../library/exceptions.xhtml#KeyboardInterrupt "KeyboardInterrupt"), [`handle_error()`](../library/socketserver.xhtml#socketserver.BaseServer.handle_error "socketserver.BaseServer.handle_error") is no longer called, and the exception will stop a single-threaded server. (Contributed by Martin Panter in [bpo-23430](https://bugs.python.org/issue23430) \[https://bugs.python.org/issue23430\].)
- [`spwd.getspnam()`](../library/spwd.xhtml#spwd.getspnam "spwd.getspnam") now raises a [`PermissionError`](../library/exceptions.xhtml#PermissionError "PermissionError") instead of [`KeyError`](../library/exceptions.xhtml#KeyError "KeyError") if the user doesn't have privileges.
- The [`socket.socket.close()`](../library/socket.xhtml#socket.socket.close "socket.socket.close") method now raises an exception if an error (e.g. `EBADF`) was reported by the underlying system call. (Contributed by Martin Panter in [bpo-26685](https://bugs.python.org/issue26685) \[https://bugs.python.org/issue26685\].)
- The *decode\_data* argument for the [`smtpd.SMTPChannel`](../library/smtpd.xhtml#smtpd.SMTPChannel "smtpd.SMTPChannel") and [`smtpd.SMTPServer`](../library/smtpd.xhtml#smtpd.SMTPServer "smtpd.SMTPServer") constructors is now `False` by default. This means that the argument passed to [`process_message()`](../library/smtpd.xhtml#smtpd.SMTPServer.process_message "smtpd.SMTPServer.process_message") is now a bytes object by default, and `process_message()` will be passed keyword arguments. Code that has already been updated in accordance with the deprecation warning generated by 3.5 will not be affected.
- All optional arguments of the [`dump()`](../library/json.xhtml#json.dump "json.dump"), [`dumps()`](../library/json.xhtml#json.dumps "json.dumps"), [`load()`](../library/json.xhtml#json.load "json.load") and [`loads()`](../library/json.xhtml#json.loads "json.loads") functions and [`JSONEncoder`](../library/json.xhtml#json.JSONEncoder "json.JSONEncoder") and [`JSONDecoder`](../library/json.xhtml#json.JSONDecoder "json.JSONDecoder") class constructors in the [`json`](../library/json.xhtml#module-json "json: Encode and decode the JSON format.") module are now [keyword-only](../glossary.xhtml#keyword-only-parameter). (Contributed by Serhiy Storchaka in [bpo-18726](https://bugs.python.org/issue18726) \[https://bugs.python.org/issue18726\].)
- [`type`](../library/functions.xhtml#type "type") 的子類如果未重載 `type.__new__`,將不再能使用一個參數的形式來獲取對象的類型。
- As part of [**PEP 487**](https://www.python.org/dev/peps/pep-0487) \[https://www.python.org/dev/peps/pep-0487\], the handling of keyword arguments passed to [`type`](../library/functions.xhtml#type "type") (other than the metaclass hint, `metaclass`) is now consistently delegated to [`object.__init_subclass__()`](../reference/datamodel.xhtml#object.__init_subclass__ "object.__init_subclass__"). This means that `type.__new__()` and `type.__init__()` both now accept arbitrary keyword arguments, but [`object.__init_subclass__()`](../reference/datamodel.xhtml#object.__init_subclass__ "object.__init_subclass__") (which is called from `type.__new__()`) will reject them by default. Custom metaclasses accepting additional keyword arguments will need to adjust their calls to `type.__new__()` (whether direct or via [`super`](../library/functions.xhtml#super "super")) accordingly.
- In `distutils.command.sdist.sdist`, the `default_format`attribute has been removed and is no longer honored. Instead, the gzipped tarfile format is the default on all platforms and no platform-specific selection is made. In environments where distributions are built on Windows and zip distributions are required, configure the project with a `setup.cfg` file containing the following:
```
[sdist]
formats=zip
```
This behavior has also been backported to earlier Python versions by Setuptools 26.0.0.
- In the [`urllib.request`](../library/urllib.request.xhtml#module-urllib.request "urllib.request: Extensible library for opening URLs.") module and the [`http.client.HTTPConnection.request()`](../library/http.client.xhtml#http.client.HTTPConnection.request "http.client.HTTPConnection.request") method, if no Content-Length header field has been specified and the request body is a file object, it is now sent with HTTP 1.1 chunked encoding. If a file object has to be sent to a HTTP 1.0 server, the Content-Length value now has to be specified by the caller. (Contributed by Demian Brecht and Rolf Krahl with tweaks from Martin Panter in [bpo-12319](https://bugs.python.org/issue12319) \[https://bugs.python.org/issue12319\].)
- The [`DictReader`](../library/csv.xhtml#csv.DictReader "csv.DictReader") now returns rows of type [`OrderedDict`](../library/collections.xhtml#collections.OrderedDict "collections.OrderedDict"). (Contributed by Steve Holden in [bpo-27842](https://bugs.python.org/issue27842) \[https://bugs.python.org/issue27842\].)
- The [`crypt.METHOD_CRYPT`](../library/crypt.xhtml#crypt.METHOD_CRYPT "crypt.METHOD_CRYPT") will no longer be added to `crypt.methods`if unsupported by the platform. (Contributed by Victor Stinner in [bpo-25287](https://bugs.python.org/issue25287) \[https://bugs.python.org/issue25287\].)
- The *verbose* and *rename* arguments for [`namedtuple()`](../library/collections.xhtml#collections.namedtuple "collections.namedtuple") are now keyword-only. (Contributed by Raymond Hettinger in [bpo-25628](https://bugs.python.org/issue25628) \[https://bugs.python.org/issue25628\].)
- On Linux, [`ctypes.util.find_library()`](../library/ctypes.xhtml#ctypes.util.find_library "ctypes.util.find_library") now looks in `LD_LIBRARY_PATH` for shared libraries. (Contributed by Vinay Sajip in [bpo-9998](https://bugs.python.org/issue9998) \[https://bugs.python.org/issue9998\].)
- The [`imaplib.IMAP4`](../library/imaplib.xhtml#imaplib.IMAP4 "imaplib.IMAP4") class now handles flags containing the `']'` character in messages sent from the server to improve real-world compatibility. (Contributed by Lita Cho in [bpo-21815](https://bugs.python.org/issue21815) \[https://bugs.python.org/issue21815\].)
- The `mmap.write()` function now returns the number of bytes written like other write methods. (Contributed by Jakub Stasiak in [bpo-26335](https://bugs.python.org/issue26335) \[https://bugs.python.org/issue26335\].)
- The [`pkgutil.iter_modules()`](../library/pkgutil.xhtml#pkgutil.iter_modules "pkgutil.iter_modules") and [`pkgutil.walk_packages()`](../library/pkgutil.xhtml#pkgutil.walk_packages "pkgutil.walk_packages")functions now return [`ModuleInfo`](../library/pkgutil.xhtml#pkgutil.ModuleInfo "pkgutil.ModuleInfo") named tuples. (Contributed by Ramchandra Apte in [bpo-17211](https://bugs.python.org/issue17211) \[https://bugs.python.org/issue17211\].)
- [`re.sub()`](../library/re.xhtml#re.sub "re.sub") now raises an error for invalid numerical group references in replacement templates even if the pattern is not found in the string. The error message for invalid group references now includes the group index and the position of the reference. (Contributed by SilentGhost, Serhiy Storchaka in [bpo-25953](https://bugs.python.org/issue25953) \[https://bugs.python.org/issue25953\].)
- [`zipfile.ZipFile`](../library/zipfile.xhtml#zipfile.ZipFile "zipfile.ZipFile") will now raise [`NotImplementedError`](../library/exceptions.xhtml#NotImplementedError "NotImplementedError") for unrecognized compression values. Previously a plain [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError")was raised. Additionally, calling [`ZipFile`](../library/zipfile.xhtml#zipfile.ZipFile "zipfile.ZipFile") methods on a closed ZipFile or calling the [`write()`](../library/zipfile.xhtml#zipfile.ZipFile.write "zipfile.ZipFile.write") method on a ZipFile created with mode `'r'` will raise a [`ValueError`](../library/exceptions.xhtml#ValueError "ValueError"). Previously, a [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError") was raised in those scenarios.
- when custom metaclasses are combined with zero-argument [`super()`](../library/functions.xhtml#super "super") or direct references from methods to the implicit `__class__` closure variable, the implicit `__classcell__` namespace entry must now be passed up to `type.__new__` for initialisation. Failing to do so will result in a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning") in Python 3.6 and a [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError") in Python 3.8.
- With the introduction of [`ModuleNotFoundError`](../library/exceptions.xhtml#ModuleNotFoundError "ModuleNotFoundError"), import system consumers may start expecting import system replacements to raise that more specific exception when appropriate, rather than the less-specific [`ImportError`](../library/exceptions.xhtml#ImportError "ImportError"). To provide future compatibility with such consumers, implementors of alternative import systems that completely replace [`__import__()`](../library/functions.xhtml#__import__ "__import__") will need to update their implementations to raise the new subclass when a module can't be found at all. Implementors of compliant plugins to the default import system shouldn't need to make any changes, as the default import system will raise the new subclass when appropriate.
### C API 中的改變
- The [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc") allocator family now uses the [pymalloc allocator](../c-api/memory.xhtml#pymalloc) rather than the system `malloc()`. Applications calling [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc") without holding the GIL can now crash. Set the [`PYTHONMALLOC`](../using/cmdline.xhtml#envvar-PYTHONMALLOC) environment variable to `debug` to validate the usage of memory allocators in your application. See [bpo-26249](https://bugs.python.org/issue26249) \[https://bugs.python.org/issue26249\].
- [`Py_Exit()`](../c-api/sys.xhtml#c.Py_Exit "Py_Exit") (and the main interpreter) now override the exit status with 120 if flushing buffered data failed. See [bpo-5319](https://bugs.python.org/issue5319) \[https://bugs.python.org/issue5319\].
### CPython 字節碼的改變
There have been several major changes to the [bytecode](../glossary.xhtml#term-bytecode) in Python 3.6.
- The Python interpreter now uses a 16-bit wordcode instead of bytecode. (Contributed by Demur Rumed with input and reviews from Serhiy Storchaka and Victor Stinner in [bpo-26647](https://bugs.python.org/issue26647) \[https://bugs.python.org/issue26647\] and [bpo-28050](https://bugs.python.org/issue28050) \[https://bugs.python.org/issue28050\].)
- The new [`FORMAT_VALUE`](../library/dis.xhtml#opcode-FORMAT_VALUE) and [`BUILD_STRING`](../library/dis.xhtml#opcode-BUILD_STRING) opcodes as part of the [formatted string literal](#whatsnew36-pep498) implementation. (Contributed by Eric Smith in [bpo-25483](https://bugs.python.org/issue25483) \[https://bugs.python.org/issue25483\] and Serhiy Storchaka in [bpo-27078](https://bugs.python.org/issue27078) \[https://bugs.python.org/issue27078\].)
- The new [`BUILD_CONST_KEY_MAP`](../library/dis.xhtml#opcode-BUILD_CONST_KEY_MAP) opcode to optimize the creation of dictionaries with constant keys. (Contributed by Serhiy Storchaka in [bpo-27140](https://bugs.python.org/issue27140) \[https://bugs.python.org/issue27140\].)
- The function call opcodes have been heavily reworked for better performance and simpler implementation. The [`MAKE_FUNCTION`](../library/dis.xhtml#opcode-MAKE_FUNCTION), [`CALL_FUNCTION`](../library/dis.xhtml#opcode-CALL_FUNCTION), [`CALL_FUNCTION_KW`](../library/dis.xhtml#opcode-CALL_FUNCTION_KW) and [`BUILD_MAP_UNPACK_WITH_CALL`](../library/dis.xhtml#opcode-BUILD_MAP_UNPACK_WITH_CALL) opcodes have been modified, the new [`CALL_FUNCTION_EX`](../library/dis.xhtml#opcode-CALL_FUNCTION_EX) and [`BUILD_TUPLE_UNPACK_WITH_CALL`](../library/dis.xhtml#opcode-BUILD_TUPLE_UNPACK_WITH_CALL) have been added, and `CALL_FUNCTION_VAR`, `CALL_FUNCTION_VAR_KW` and `MAKE_CLOSURE` opcodes have been removed. (Contributed by Demur Rumed in [bpo-27095](https://bugs.python.org/issue27095) \[https://bugs.python.org/issue27095\], and Serhiy Storchaka in [bpo-27213](https://bugs.python.org/issue27213) \[https://bugs.python.org/issue27213\], [bpo-28257](https://bugs.python.org/issue28257) \[https://bugs.python.org/issue28257\].)
- The new [`SETUP_ANNOTATIONS`](../library/dis.xhtml#opcode-SETUP_ANNOTATIONS) and `STORE_ANNOTATION` opcodes have been added to support the new [variable annotation](../glossary.xhtml#term-variable-annotation) syntax. (Contributed by Ivan Levkivskyi in [bpo-27985](https://bugs.python.org/issue27985) \[https://bugs.python.org/issue27985\].)
## Python 3.6.2 中的重要變化
### New `make regen-all` build target
To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.
Instead, a new `make regen-all` command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).
More selective regeneration targets are also defined - see [Makefile.pre.in](https://github.com/python/cpython/tree/3.7/Makefile.pre.in) \[https://github.com/python/cpython/tree/3.7/Makefile.pre.in\] for details.
(Contributed by Victor Stinner in [bpo-23404](https://bugs.python.org/issue23404) \[https://bugs.python.org/issue23404\].)
3\.6.2 新版功能.
### Removal of `make touch` build target
The `make touch` build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.
It has been replaced by the new `make regen-all` target.
(Contributed by Victor Stinner in [bpo-23404](https://bugs.python.org/issue23404) \[https://bugs.python.org/issue23404\].)
在 3.6.2 版更改.
## Python 3.6.4 中的重要變化
The `PyExc_RecursionErrorInst` singleton that was part of the public API has been removed as its members being never cleared may cause a segfault during finalization of the interpreter. (Contributed by Xavier de Gaye in [bpo-22898](https://bugs.python.org/issue22898) \[https://bugs.python.org/issue22898\] and [bpo-30697](https://bugs.python.org/issue30697) \[https://bugs.python.org/issue30697\].)
## Python 3.6.5 中的重要變化
The [`locale.localeconv()`](../library/locale.xhtml#locale.localeconv "locale.localeconv") function now sets temporarily the `LC_CTYPE`locale to the `LC_NUMERIC` locale in some cases. (Contributed by Victor Stinner in [bpo-31900](https://bugs.python.org/issue31900) \[https://bugs.python.org/issue31900\].)
## Python 3.6.7 中的重要變化
In 3.6.7 the [`tokenize`](../library/tokenize.xhtml#module-tokenize "tokenize: Lexical scanner for Python source code.") module now implicitly emits a `NEWLINE` token when provided with input that does not have a trailing new line. This behavior now matches what the C tokenizer does internally. (Contributed by Ammar Askar in [bpo-33899](https://bugs.python.org/issue33899) \[https://bugs.python.org/issue33899\].)
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](3.5.xhtml "Python 3.5 有什么新變化") |
- [上一頁](3.7.xhtml "Python 3.7 有什么新變化") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 有什么新變化?](index.xhtml) ?
- $('.inline-search').show(0); |
? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec