What's New In Python 3.7¶
Elvis Pranskevichus <email@example.com>
この記事では Python 3.6 と比較した Python 3.7 の新機能を解説します。Python 3.7 は2018年6月27日にリリースされました。全詳細については 変更履歴 をご覧ください。
概要 -- リリースハイライト¶
PEP 563 、型アノテーションの評価の遅延。
PEP 562 、モジュール属性へのアクセスのカスタマイズ。
PEP 560 、typing モジュールとジェネリック型に対する言語コアによるサポート。
デフォルトのテキストエンコーディングとして ASCII を使わなくなりました:
PEP 552 、決定論的な .pyc
C API の改善:
PEP 539 、スレッドローカルなストレージのための新しい C API
このリリースの特色は、多くの領域での特筆すべきパフォーマンスの改善です。 最適化 節に詳細な一覧があります。
1つ前にリリースされた Python との互換性に影響を持つ変更の一覧については、 Python 3.7 への移植 節を参照してください。
PEP 563: アノテーションの遅延評価¶
ソースコードに注釈を付けるのは Python プログラムの起動時間に好ましくない影響がある。
アノテーションの定義時に、アノテーションに含まれる式を評価するコードをコンパイルする代わりに、コンパイラは当該の式の AST と同等な文字列形式でアノテーションを保存します。
class C: @classmethod def from_string(cls, source: str) -> C: ... def validate_b(self, obj: B) -> bool: ... class B: ...
この変更は後方互換性を壊してしまうので、新しい振る舞いは Python 3.7 では
from __future__ import annotations
この振る舞いは Python 3.10 でデフォルトになります。
- PEP 563 -- アノテーションの遅延評価
PEP written and implemented by Łukasz Langa.
PEP 538: レガシーな C ロケールの抑圧¶
Python 3 シリーズにおける継続中の課題の一つは、非 Windows プラットフォームではデフォルトの C ロケールつまり POSIX ロケールの使用から現在のところ必然的に導かれてしまう "7-bit ASCII" テキストエンコーディングの仮定を取り扱う賢明なデフォルトの方針を決定することです。
PEP 538 はインタープリタのデフォルトのコマンドラインインターフェースを更新し、新しく加わった
PYTHONCOERCECLOCALE 環境変数のドキュメントにある通り、自動的にロケールを UTF-8 に基づいた利用可能なロケールへ強制します。
LC_CTYPE を自動的に設定すると、コアのインタープリタと (
readline などの) ロケールを考慮する C 拡張はデフォルトのテキストエンコーディングとして ASCII ではなく UTF-8 を使うことになります。
PEP 11 にあるプラットフォームのサポート定義も、適切に設定された非 ASCII に基づくロケールだけにテキスト処理の完全なサポートを制限するよう更新されました。
PYTHONCOERCECLOCALE=warn を設定することで (
stderr に直接出力される) 明示的な警告を要求できます。
この設定を有効にしていると、コアのインタプリタの初期化時にレガシーな C ロケールが有効なままの場合、 Python 実行器が警告を出力します。
PEP 538 のロケール強制には、(非 Python アプリケーションや古いバージョンの Python で動くのも含めた) 子プロセスに加え (GNU
readline などの) 影響を受ける拡張モジュールにも利益がある一方、適切な対象ロケールが実行するシステムに存在することを要求するという負の面もあります。
(例えば、RHEL/CentOS 7 で起きているように) 適切な対象ロケールで利用可能なものが無いケースにきちんと対処するために、 Python 3.7 には PEP 540: 強制 UTF-8 実行モード も実装されています。
- PEP 538 -- レガシーな C ロケールから UTF-8 ベースのロケールへの強制
PEP written and implemented by Nick Coghlan.
PEP 540: 強制 UTF-8 実行モード¶
The forced UTF-8 mode can be used to change the text handling behavior in an embedded Python interpreter without changing the locale settings of an embedding application.
While PEP 540's UTF-8 mode has the benefit of working regardless of which
locales are available on the running system, it has the downside of having no
effect on extension modules (such as GNU
readline), child processes running
non-Python applications, and child processes running older versions of Python.
To reduce the risk of corrupting text data when communicating with such
components, Python 3.7 also implements PEP 540: 強制 UTF-8 実行モード).
The UTF-8 mode is enabled by default when the locale is
the PEP 538 locale coercion feature fails to change it to a UTF-8 based
alternative (whether that failure is due to
PYTHONCOERCECLOCALE=0 being set,
LC_ALL being set, or the lack of a suitable target locale).
- PEP 540 -- 新しい UTF-8 モードの追加
PEP written and implemented by Victor Stinner
PEP 553: 組み込みの
Python 3.7 には、 Python デバッガへ入って行くための簡単で一貫した手段である、新しい組み込みの
sys.breakpointhook(). By default, the
pdb and then calls
pdb.set_trace(), but by binding
sys.breakpointhook() to the function of your choosing,
enter any debugger. Additionally, the environment variable
PYTHONBREAKPOINT can be set to the callable of your debugger of
PYTHONBREAKPOINT=0 to completely disable built-in
- PEP 553 -- 組み込みの breakpoint()
PEP written and implemented by Barry Warsaw
PEP 539: スレッドローカルストレージのための新しい C API¶
While Python provides a C API for thread-local storage support; the existing Thread Local Storage (TLS) API has used int to represent TLS keys across all platforms. This has not generally been a problem for officially support platforms, but that is neither POSIX-compliant, nor portable in any practical sense.
PEP 539 changes this by providing a new Thread Specific Storage (TSS)
API to CPython which supersedes use of the
existing TLS API within the CPython interpreter, while deprecating the existing
API. The TSS API uses a new type
Py_tss_t instead of int
to represent TSS keys--an opaque type the definition of which may depend on
the underlying TLS implementation. Therefore, this will allow to build CPython
on platforms where the native TLS key is defined in a way that cannot be safely
cast to int.
Note that on platforms where the native TLS key is defined in a way that cannot be safely cast to int, all functions of the existing TLS API will be no-op and immediately return failure. This indicates clearly that the old API is not supported on platforms where it cannot be used reliably, and that no effort will be made to add such support.
- PEP 539 -- A New C-API for Thread-Local Storage in CPython
PEP written by Erik M. Bray; implementation by Masayuki Yamamoto.
PEP 562: モジュール属性へのアクセスのカスタマイズ¶
Python 3.7 ではモジュールに
- PEP 562 -- モジュールの
PEP written and implemented by Ivan Levkivskyi
PEP 564: ナノ秒単位の分解能を持つ新しい時間関数¶
- PEP 564 -- ナノ秒単位の分解能を持つ新しい時間関数の追加
PEP written and implemented by Victor Stinner
PEP 565: Show DeprecationWarning in
The default handling of
DeprecationWarning has been changed such that
these warnings are once more shown by default, but only when the code
triggering them is running directly in the
__main__ module. As a result,
developers of single file scripts and those using Python interactively should
once again start seeing deprecation warnings for the APIs they use, but
deprecation warnings triggered by imported application, library and framework
modules will continue to be hidden by default.
As a result of this change, the standard library now allows developers to choose between three different deprecation warning behaviours:
FutureWarning: always displayed by default, recommended for warnings intended to be seen by application end users (e.g. for deprecated application configuration settings).
DeprecationWarning: displayed by default only in
__main__and when running tests, recommended for warnings intended to be seen by other Python developers where a version upgrade may result in changed behaviour or an error.
were only visible when running tests, which meant that developers primarily
writing single file scripts or using Python interactively could be surprised
by breaking changes in the APIs they used.
- PEP 565 -- Show DeprecationWarning in
PEP written and implemented by Nick Coghlan
当初 PEP 484 は、 CPython のインタプリタのコア部分に どんな 変更も施さないような方法で設計されていました。
この PEP では、2 つの特殊メソッド
その結果、型に関する様々な操作の速度が最大で 7 倍にまでなり、ジェネリック型はメタクラスの衝突を起こさずに使えるようになり、
- PEP 560 -- typing モジュールとジェネリック型に対する言語コアによるサポート
PEP written and implemented by Ivan Levkivskyi
PEP 552: Hash-based .pyc Files¶
Python has traditionally checked the up-to-dateness of bytecode cache files
.pyc files) by comparing the source metadata (last-modified timestamp
and size) with source metadata saved in the cache file header when it was
generated. While effective, this invalidation method has its drawbacks. When
filesystem timestamps are too coarse, Python can miss source updates, leading to
user confusion. Additionally, having a timestamp in the cache file is
problematic for build reproducibility and
content-based build systems.
PEP 552 extends the pyc format to allow the hash of the source file to be
used for invalidation instead of the source timestamp. Such
.pyc files are
called "hash-based". By default, Python still uses timestamp-based invalidation
and does not generate hash-based
.pyc files at runtime. Hash-based
files may be generated with
.pyc files come in two variants: checked and unchecked. Python
validates checked hash-based
.pyc files against the corresponding source
files at runtime but doesn't do so for unchecked hash-based pycs. Unchecked
.pyc files are a useful performance optimization for environments
where a system external to Python (e.g., the build system) is responsible for
.pyc files up-to-date.
See キャッシュされたバイトコードの無効化 for more information.
- PEP 552 -- Deterministic pycs
PEP written and implemented by Benjamin Peterson
PEP 545: Python Documentation Translations¶
PEP 545 describes the process of creating and maintaining Python documentation translations.
Three new translations have been added:
- PEP 545 -- Python ドキュメント翻訳
PEP written and implemented by Julien Palard, Inada Naoki, and Victor Stinner.
Python Development Mode (-X dev)¶
dev command line option or the new
PYTHONDEVMODE environment variable can be used to enable
Python Development Mode. When in development mode, Python performs
additional runtime checks that are too expensive to be enabled by default.
See Python Development Mode documentation for the full
awaitexpression and comprehensions containing an
async forclause were illegal in the expressions in formatted string literals due to a problem with the implementation. In Python 3.7 this restriction was lifted.
Circular imports involving absolute imports with binding a submodule to a name are now supported. (Contributed by Serhiy Storchaka in bpo-30024.)
object.__format__(x, '')is now equivalent to
format(str(self), ''). (Contributed by Serhiy Storchaka in bpo-28974.)
In order to better support dynamic creation of stack traces,
types.TracebackTypecan now be instantiated from Python code, and the
tb_nextattribute on tracebacks is now writable. (Contributed by Nathaniel J. Smith in bpo-30579.)
When using the
sys.pathis now eagerly expanded to the full starting directory path, rather than being left as the empty directory (which allows imports from the current working directory at the time when an import occurs) (Contributed by Nick Coghlan in bpo-33053.)
contextvars module and a set of
new C APIs introduce
support for context variables. Context variables are conceptually
similar to thread-local variables. Unlike TLS, context variables
support asynchronous code correctly.
decimal modules have been updated to use
and support context variables out of the box. Particularly the active
decimal context is now stored in a context variable, which allows
decimal operations to work with the correct context in asynchronous code.
- PEP 567 -- コンテキスト変数
PEP written and implemented by Yury Selivanov
@dataclass class Point: x: float y: float z: float = 0.0 p = Point(1.5, 2.5) print(p) # produces "Point(x=1.5, y=2.5, z=0.0)"
- PEP 557 -- データクラス
PEP written and implemented by Eric V. Smith
importlib.resources module provides several new APIs and one
new ABC for access to, opening, and reading resources inside packages.
Resources are roughly similar to files inside packages, but they needn't
be actual files on the physical file system. Module loaders can provide a
get_resource_reader() function which returns
importlib.abc.ResourceReader instance to support this
new API. Built-in file path loaders and zip file loaders both support this.
Contributed by Barry Warsaw and Brett Cannon in bpo-32248.
importlib_resources -- a PyPI backport for earlier Python versions.
asyncio gained support for
Future.add_done_callback()have a new optional keyword-only context parameter.
Tasksnow track their context automatically. See PEP 567 for more details. (Contributed by Yury Selivanov in bpo-32436.)
asyncio.current_task()function returns the currently running
Taskinstance, and the new
asyncio.all_tasks()function returns a set of all existing
Taskinstances in a given loop. The
Task.all_tasks()methods have been deprecated. (Contributed by Andrew Svetlov in bpo-32250.)
asyncio.get_running_loop()function returns the currently running loop, and raises a
RuntimeErrorif no loop is running. This is in contrast with
asyncio.get_event_loop(), which will create a new event loop if none is running. (Contributed by Yury Selivanov in bpo-32269.)
StreamWriter.wait_closed()coroutine method allows waiting until the stream writer is closed. The new
StreamWriter.is_closing()method can be used to determine if the writer is closing. (Contributed by Andrew Svetlov in bpo-32391.)
Task.get_loop()methods return the instance of the loop on which a task or a future were created.
Server.get_loop()allows doing the same for
asyncio.Serverobjects. (Contributed by Yury Selivanov in bpo-32415 and Srinivas Reddy Thatiparthy in bpo-32418.)
It is now possible to control how instances of
asyncio.Serverbegin serving. Previously, the server would start serving immediately when created. The new start_serving keyword argument to
loop.create_unix_server(), as well as
Server.serve_forever()can be used to decouple server instantiation and serving. The new
Trueif the server is serving.
Serverobjects are now asynchronous context managers:
srv = await loop.create_server(...) async with srv: # some code # At this point, srv is closed and no longer accepts new connections.
(Contributed by Yury Selivanov in bpo-32662.)
loop.create_accepted_socket()methods and their corresponding UNIX socket variants now accept the ssl_handshake_timeout keyword argument. (Contributed by Neil Aspinall in bpo-29970.)
ReadTransport.is_reading()method can be used to determine the reading state of the transport. Additionally, calls to
ReadTransport.pause_reading()are now idempotent. (Contributed by Yury Selivanov in bpo-32356.)
Exceptions occurring in cancelled tasks are no longer logged. (Contributed by Yury Selivanov in bpo-30508.)
WindowsProactorEventLoopPolicyclasses. (Contributed by Yury Selivanov in bpo-33792.)
asyncio APIs have been
(Contributed by Raymond Hettinger in bpo-32320.)
compileall.compile_dir() learned the new invalidation_mode parameter,
which can be used to enable
hash-based .pyc invalidation. The invalidation
mode can also be specified on the command line using the new
(Contributed by Benjamin Peterson in bpo-31650.)
AsyncExitStack have been added to
complement their synchronous counterparts. (Contributed
by Jelle Zijlstra in bpo-29679 and bpo-30241,
and by Alexander Mohr and Ilya Kulakov in bpo-29302.)
dbm.dumb now supports reading read-only files and no longer writes the
index file when it is not changed.
dis() function is now able to
disassemble nested code objects (the code of comprehensions, generator
expressions and nested functions, and the code used for building nested
classes). The maximum depth of disassembly recursion is controlled by
the new depth parameter.
(Contributed by Serhiy Storchaka in bpo-11822.)
README.rst is now included in the list of distutils standard READMEs and
therefore included in source distributions.
(Contributed by Ryan Gonzalez in bpo-11913.)
In Python 3.8, attempting to check for non-Enum objects in
classes will raise a
1 in Color); similarly,
attempting to check for non-Flag objects in a
Flag member will
1 in Perm.RW); currently, both operations
False instead and are deprecated.
(Contributed by Ethan Furman in bpo-33217.)
gc.freeze() function allows freezing all objects tracked
by the garbage collector and excluding them from future collections.
This can be used before a POSIX
fork() call to make the GC copy-on-write
friendly or to speed up collection. The new
reverses this operation. Additionally,
be used to obtain the number of frozen objects.
(Contributed by Li Zekun in bpo-31558.)
SimpleHTTPRequestHandler now supports the HTTP
If-Modified-Since header. The server returns the 304 response status if
the target file was not modified after the time specified in the header.
(Contributed by Pierre Quentel in bpo-29654.)
SimpleHTTPRequestHandler accepts the new directory
argument, in addition to the new
--directory command line argument.
With this parameter, the server serves the specified directory, by default it
uses the current working directory.
(Contributed by Stéphane Wirtel and Julien Palard in bpo-28707.)
idlelib と IDLE¶
自動補完におけるいくつもの修正。 (Contributed by Louie Lu in bpo-15786.)
Module Browser (on the File menu, formerly called Class Browser), now displays nested functions and classes in addition to top-level functions and classes. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy in bpo-1612262.)
The Settings dialog (Options, Configure IDLE) has been partly rewritten to improve both appearance and function. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)
The font sample now includes a selection of non-Latin characters so that users can better see the effect of selecting a particular font. (Contributed by Terry Jan Reedy in bpo-13802.) The sample can be edited to include other characters. (Contributed by Serhiy Storchaka in bpo-31860.)
The IDLE features formerly implemented as extensions have been reimplemented as normal features. Their settings have been moved from the Extensions tab to other dialog tabs. (Contributed by Charles Wohlganger and Terry Jan Reedy in bpo-27099.)
Editor code context option revised. Box displays all context lines up to maxlines. Clicking on a context line jumps the editor to that line. Context colors for custom themes is added to Highlights tab of Settings dialog. (Contributed by Cheryl Sabella and Terry Jan Reedy in bpo-33642, bpo-33768, and bpo-33679.)
On Windows, a new API call tells Windows that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect. (Contributed by Terry Jan Reedy in bpo-33656.)
New in 3.7.1:
Output over N lines (50 by default) is squeezed down to a button. N can be changed in the PyShell section of the General page of the Settings dialog. Fewer, but possibly extra long, lines can be squeezed by right clicking on the output. Squeezed output can be expanded in place by double-clicking the button or into the clipboard or a separate window by right-clicking the button. (Contributed by Tal Einat in bpo-1529353.)
上で挙げた変更は 3.6 のメンテナンスリリースにバックポートされました。
NEW in 3.7.4:
Add "Run Customized" to the Run menu to run a module with customized settings. Any command line arguments entered are added to sys.argv. They re-appear in the box for the next customized run. One can also suppress the normal Shell main module restart. (Contributed by Cheryl Sabella, Terry Jan Reedy, and others in bpo-5680 and bpo-37627.)
New in 3.7.5:
Add optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog. Line numbers for an existing window are shown and hidden in the Options menu. (Contributed by Tal Einat and Saimadhav Heblikar in bpo-17535.)
importlib.find_spec() now raises
ModuleNotFoundError instead of
AttributeError if the specified parent module is not a package (i.e.
(Contributed by Milan Oberkirch in bpo-30436.)
importlib.source_hash() can be used to compute the hash of
the passed source. A hash-based .pyc file
embeds the value returned by this function.
supernet_of() methods of
be used for network containment tests.
(Contributed by Michel Albert and Cheryl Sabella in bpo-20825.)
The MIME type of .bmp has been changed from
(Contributed by Nitish Chandra in bpo-22589.)
explicitly closes the process object and releases all resources associated
ValueError is raised if the underlying process is still
(Contributed by Antoine Pitrou in bpo-30596.)
os.preadv() (combine the functionality of
os.pwritev() functions (combine the functionality
os.pwrite()). (Contributed by Pablo Galindo in
py_compile.compile() -- and by extension,
compileall -- now
SOURCE_DATE_EPOCH environment variable by
.pyc files for hash-based validation.
This allows for guaranteeing
reproducible builds of
files when they are created eagerly. (Contributed by Bernhard M. Wiedemann
The pydoc server can now bind to an arbitrary hostname specified by the
-n command-line argument.
(Contributed by Feanil Patel in bpo-31128.)
Regular expressions compiled with the
re.LOCALE flag no longer
depend on the locale at compile time. Locale settings are applied only
when the compiled regular expression is used.
(Contributed by Serhiy Storchaka in bpo-30215.)
FutureWarning is now emitted if a regular expression contains
character set constructs that will change semantically in the future,
such as nested sets and set operations.
(Contributed by Serhiy Storchaka in bpo-30349.)
The new warn_on_full_buffer argument to the
function makes it possible to specify whether Python prints a warning on
stderr when the wakeup buffer overflows.
(Contributed by Nathaniel J. Smith in bpo-30050.)
socket.close() function closes the passed socket file descriptor.
This function should be used instead of
os.close() for better
compatibility across platforms.
(Contributed by Christian Heimes in bpo-32454.)
socket module now exposes the
socket.TCP_USER_TIMEOUT (Linux 2.6.37), and
socket.TCP_NOTSENT_LOWAT (Linux 3.12) constants.
(Contributed by Omar Sandoval in bpo-26273 and
Nathaniel J. Smith in bpo-29728.)
Sockets now auto-detect family, type and protocol from file descriptor by default. (Contributed by Christian Heimes in bpo-28134.)
socketserver.ThreadingMixIn.server_close() now waits until all non-daemon
socketserver.ForkingMixIn.server_close() now waits
until all child processes complete.
ssl module now uses OpenSSL's builtin API instead of
match_hostname() to check a host name or an IP address. Values
are validated during TLS handshake. Any certificate validation error
including failing the host name check now raises
SSLCertVerificationError and aborts the handshake with a proper
TLS Alert message. The new exception contains additional information.
Host name validation can be customized with
(Contributed by Christian Heimes in bpo-31399.)
The improved host name check requires a libssl implementation compatible with OpenSSL 1.0.2 or 1.1. Consequently, OpenSSL 0.9.8 and 1.0.1 are no longer supported (see サポート対象プラットフォームからの除外 for more details). The ssl module is mostly compatible with LibreSSL 2.7.2 and newer.
ssl module no longer sends IP addresses in SNI TLS extension.
(Contributed by Christian Heimes in bpo-32185.)
The default cipher suite selection of the
ssl module now uses a blacklist
approach rather than a hard-coded whitelist. Python no longer re-enables
ciphers that have been blocked by OpenSSL security updates. Default cipher
suite selection can be configured at compile time.
(Contributed by Christian Heimes in bpo-31429.)
Validation of server certificates containing internationalized domain names
(IDNs) is now supported. As part of this change, the
now stores the expected hostname in A-label form (
rather than the U-label form (
"pythön.org"). (Contributed by
Nathaniel J. Smith and Christian Heimes in bpo-28414.)
ssl module has preliminary and experimental support for TLS 1.3 and
OpenSSL 1.1.1. At the time of Python 3.7.0 release, OpenSSL 1.1.1 is still
under development and TLS 1.3 hasn't been finalized yet. The TLS 1.3
handshake and protocol behaves slightly differently than TLS 1.2 and earlier,
see TLS 1.3.
(Contributed by Christian Heimes in bpo-32947, bpo-20995,
bpo-29136, bpo-30622 and bpo-33618)
SSLObject no longer have a public
constructor. Direct instantiation was never a documented and supported
feature. Instances must be created with
(Contributed by Christian Heimes in bpo-32951)
OpenSSL 1.1 APIs for setting the minimum and maximum TLS protocol version are
Supported protocols are indicated by several new flags, such as
(Contributed by Christian Heimes in bpo-32609.)
subprocess.run() function accepts the new capture_output
keyword argument. When true, stdout and stderr will be captured.
This is equivalent to passing
subprocess.PIPE as stdout and
(Contributed by Bo Bayles in bpo-32102.)
On Windows the default for close_fds was changed from
True when redirecting the standard handles. It's now possible to set
close_fds to true when redirecting the standard handles. See
subprocess.Popen. This means that close_fds now defaults to
True on all supported platforms.
(Contributed by Segev Finer in bpo-19764.)
The subprocess module is now more graceful when handling
subprocess.run(), or in a
context manager. It now waits a short amount of time for the child
to exit, before continuing the handling of the
(Contributed by Gregory P. Smith in bpo-25942.)
sys.get_coroutine_origin_tracking_depth() function returns
the current coroutine origin tracking depth, as set by
has been converted to use this new API instead of
(Contributed by Nathaniel J. Smith in bpo-32591.)
New clock identifiers have been added:
time.CLOCK_PROF(FreeBSD, NetBSD and OpenBSD): High-resolution per-process CPU timer.
time.CLOCK_UPTIME(FreeBSD, OpenBSD): Time whose absolute value is the time the system has been running and not suspended, providing accurate uptime measurement.
time.pthread_getcpuclockid() function returns the clock ID
of the thread-specific CPU-time clock.
tracemalloc.Traceback behaves more like regular tracebacks,
sorting the frames from oldest to most recent.
now accepts negative limit, truncating the result to the
abs(limit) oldest frames. To get the old behaviour, use
the new most_recent_first argument to
(Contributed by Jesse Bakker in bpo-32121.)
ClassMethodDescriptorType classes are now available.
(Contributed by Manuel Krebber and Guido van Rossum in bpo-29377,
and Serhiy Storchaka in bpo-32265.)
-k command-line option allows filtering tests by a name
substring or a Unix shell-like pattern.
python -m unittest -k foo runs
(Contributed by Jonas Haag in bpo-32071.)
seal() function allows sealing
Mock instances, which will disallow further creation
of attribute mocks. The seal is applied recursively to all attributes that
are themselves mocks.
(Contributed by Mario Corchero in bpo-30541.)
urllib.parse.quote() has been updated from RFC 2396 to RFC 3986,
~ to the set of characters that are never quoted by default.
(Contributed by Christian Theune and Ratnadeep Debnath in bpo-16285.)
uuid.getnode() now prefers universally administered
MAC addresses over locally administered MAC addresses.
This makes a better guarantee for global uniqueness of UUIDs returned
uuid.uuid1(). If only locally administered MAC addresses are
available, the first such one found is returned.
(Contributed by Barry Warsaw in bpo-32107.)
The initialization of the default warnings filters has changed as follows:
warnings filters enabled via the command line or the environment now have the following order of precedence:
any filters specified with the
any filters specified with the
any other CPython specific filters (e.g. the
defaultfilter added for the new
any implicit filters defined directly by the warnings machinery
in CPython debug builds, all warnings are now displayed by default (the implicit filter list is empty)
Deprecation warnings are once again shown by default in single-file scripts and at the interactive prompt. See PEP 565: Show DeprecationWarning in __main__ for details. (Contributed by Nick Coghlan in bpo-31975.)
ElementPath predicates in the
methods can now compare text of the current node with
[. = "text"],
not only text in children. Predicates also allow adding spaces for
better readability. (Contributed by Stefan Behnel in bpo-31648.)
can now be used as a decorator. (Contributed by Xiang Zhang in
create_archive() now accepts an optional compressed
argument to generate a compressed archive. A command line option
--compress has also been added to support compression.
(Contributed by Zhiming Wang in bpo-31638.)
Subdirectories in archives created by
ZipFile are now stored in
(Contributed by Bernhard M. Wiedemann in bpo-30693.)
C API の変更¶
A new API for thread-local storage has been implemented. See PEP 539: スレッドローカルストレージのための新しい C API for an overview and スレッド固有ストレージ (Thread Specific Storage, TSS) API for a complete reference. (Contributed by Masayuki Yamamoto in bpo-25658.)
import__find__load__done() static markers can be used to trace
(Contributed by Christian Heimes in bpo-31574.)
doc of structures
wrapperbase are now of type
const char * rather of
char *. (Contributed by Serhiy Storchaka in bpo-28761.)
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 and bpo-30697.
Added C API support for timezones with timezone constructors
and access to the UTC singleton with
Contributed by Paul Ganssle in bpo-10381.
The type of results of
PyThread_get_thread_ident(), and the id parameter of
PyThreadState_SetAsyncExc() changed from long to
(Contributed by Serhiy Storchaka in bpo-6532.)
Changes to the startup sequence and the management of dynamic memory
allocators mean that the long documented requirement to call
Py_Initialize() before calling most C API functions is now
relied on more heavily, and failing to abide by it may lead to segfaults in
embedding applications. See the Python 3.7 への移植 section in this
document and the Python 初期化以前 section in the C API documentation
for more details.
A full copy of libffi is no longer bundled for use when building the
_ctypes module on non-OSX UNIX platforms. An installed copy
of libffi is now required when building
_ctypes on such platforms.
(Contributed by Zachary Ware in bpo-27979.)
The Windows build process no longer depends on Subversion to pull in external
sources, a Python script is used to download zipfiles from GitHub instead.
If Python 3.6 is not found on the system (via
py -3.6), NuGet is used to
download a copy of 32-bit Python for this purpose. (Contributed by Zachary
Ware in bpo-30450.)
ssl module requires OpenSSL 1.0.2 or 1.1 compatible libssl.
OpenSSL 1.0.1 has reached end of lifetime on 2016-12-31 and is no longer
supported. LibreSSL is temporarily not supported as well. LibreSSL releases
up to version 2.6.4 are missing required OpenSSL 1.0.2 APIs.
The overhead of calling many methods of various standard library classes
implemented in C has been significantly reduced by porting more code
to use the
(Contributed by Victor Stinner in bpo-29300, bpo-29507,
bpo-29452, and bpo-29286.)
Method calls are now up to 20% faster due to the bytecode changes which avoid creating bound method instances. (Contributed by Yury Selivanov and INADA Naoki in bpo-26110.)
asyncio module received a number of notable optimizations for
commonly used functions:
The performance overhead of asyncio debug mode has been reduced. (Contributed by Antoine Pitrou in bpo-31970.)
Searching for certain Unicode characters (like Ukrainian capital "Є") in a string was up to 25 times slower than searching for other characters. It is now only 3 times slower in the worst case. (Contributed by Serhiy Storchaka in bpo-24821.)
collections.namedtuple() factory has been reimplemented to
make the creation of named tuples 4 to 6 times faster.
(Contributed by Jelle Zijlstra with further improvements by INADA Naoki,
Serhiy Storchaka, and Raymond Hettinger in bpo-28638.)
date.fromtimestamp() are now up to
30% faster in the common case.
(Contributed by Paul Ganssle in bpo-32403.)
re.compile() now converts
flags parameter to int object if
RegexFlag. It is now as fast as Python 3.5, and faster than
Python 3.6 by about 10% depending on the pattern.
(Contributed by INADA Naoki in bpo-31671.)
modify() methods of classes
selectors.DevpollSelector may be around 10% faster under
heavy loads. (Contributed by Giampaolo Rodola' in bpo-30014)
Constant folding has been moved from the peephole optimizer to the new AST optimizer, which is able perform optimizations more consistently. (Contributed by Eugene Toder and INADA Naoki in bpo-29469 and bpo-11549.)
Most functions and methods in
abc have been rewritten in C.
This makes creation of abstract base classes, and calling
issubclass() on them 1.5x faster. This also reduces Python
start-up time by up to 10%. (Contributed by Ivan Levkivskyi and INADA Naoki
Significant speed improvements to alternate constructors for
datetime.datetime by using fast-path
constructors when not constructing subclasses. (Contributed by Paul Ganssle
The speed of comparison of
array.array instances has been
improved considerably in certain cases. It is now from 10x to 70x faster
when comparing arrays holding values of the same integer type.
(Contributed by Adrian Wielgosik in bpo-24700.)
その他の CPython の実装の変更¶
Trace hooks may now opt out of receiving the
lineand opt into receiving the
opcodeevents from the interpreter by setting the corresponding new
f_trace_opcodesattributes on the frame being traced. (Contributed by Nick Coghlan in bpo-31344.)
Fixed some consistency problems with namespace package module attributes. Namespace module objects now have an
__file__that is set to
None(previously unset), and their
__spec__.originis also set to
None(previously the string
"namespace"). See bpo-32305. Also, the namespace module object's
__spec__.loaderis set to the same value as
__loader__(previously, the former was set to
None). See bpo-32303.
uploadcommand no longer tries to change CR end-of-line characters to CRLF. This fixes a corruption issue with sdists that ended with a byte equivalent to CR. (Contributed by Bo Bayles in bpo-32304.)
非推奨の Python の挙動¶
Yield expressions (both
yield from clauses) are now deprecated
in comprehensions and generator expressions (aside from the iterable expression
in the leftmost
for clause). This ensures that comprehensions
always immediately return a container of the appropriate type (rather than
potentially returning a generator iterator object), while generator
expressions won't attempt to interleave their implicit output with the output
from any explicit yield expressions. In Python 3.7, such expressions emit
DeprecationWarning when compiled, in Python 3.8 this will be a
(Contributed by Serhiy Storchaka in bpo-10544.)
Returning a subclass of
deprecated and will be an error in future Python versions. This makes
__complex__() consistent with
(Contributed by Serhiy Storchaka in bpo-28894.)
非推奨の Python モジュール、関数、メソッド¶
Support for directly
await-ing instances of
other asyncio synchronization primitives has been deprecated. An
asynchronous context manager must be used in order to acquire and release
the synchronization resource.
(Contributed by Andrew Svetlov in bpo-32253.)
methods have been deprecated.
(Contributed by Andrew Svetlov in bpo-32250.)
In Python 3.8, the abstract base classes in
collections.abc will no
longer be exposed in the regular
collections module. This will help
create a clearer distinction between the concrete classes and the abstract
(Contributed by Serhiy Storchaka in bpo-25988.)
dbm.dumb now supports reading read-only files and no longer writes the
index file when it is not changed. A deprecation warning is now emitted
if the index file is missing and recreated in the
modes (this will be an error in future Python releases).
(Contributed by Serhiy Storchaka in bpo-28847.)
In Python 3.8, attempting to check for non-Enum objects in
classes will raise a
1 in Color); similarly,
attempting to check for non-Flag objects in a
Flag member will
1 in Perm.RW); currently, both operations
(Contributed by Ethan Furman in bpo-33217.)
both deprecated in Python 3.4 now emit
(Contributed by Matthias Bussonnier in bpo-29576)
importlib.abc.ResourceLoader ABC has been deprecated in
macpath is now deprecated and will be removed in Python 3.8.
(Contributed by Chi Hsuan Yen in bpo-9850.)
The silent argument value truncation in
socket.ntohs() has been deprecated. In future versions of Python,
if the passed argument is larger than 16 bits, an exception will be raised.
(Contributed by Oren Milman in bpo-28332.)
sys.callstats() function has been deprecated and
will be removed in a future Python version.
(Contributed by Victor Stinner in bpo-28799.)
C API の非推奨の関数ならびに型¶
PySlice_GetIndicesEx() is deprecated and replaced with
a macro if
Py_LIMITED_API is not set or set to a value in the range
0x03060000 (not inclusive), or is
or higher. (Contributed by Serhiy Storchaka in bpo-27867.)
FreeBSD 9 とそれ以前のバージョンは公式にはサポートされなくなりました。
For full Unicode support, including within extension modules, *nix platforms are now expected to provide at least one of
C.utf8(full locale) or
LC_CTYPE-only locale) as an alternative to the legacy
OpenSSL 0.9.8 and 1.0.1 are no longer supported, which means building CPython 3.7 with SSL/TLS support on older platforms still using these versions requires custom build options that link to a more recent version of OpenSSL.
Notably, this issue affects the Debian 8 (aka "jessie") and Ubuntu 14.04 (aka "Trusty") LTS Linux distributions, as they still use OpenSSL 1.0.1 by default.
Debian 9 ("stretch") and Ubuntu 16.04 ("xenial"), as well as recent releases of other LTS Linux releases (e.g. RHEL/CentOS 7.5, SLES 12-SP3), use OpenSSL 1.0.2 or later, and remain supported in the default build configuration.
CPython's own CI configuration file provides an example of using the SSL compatibility testing infrastructure in CPython's test suite to build and link against OpenSSL 1.1.0 rather than an outdated system provided OpenSSL.
The following features and APIs have been removed from Python 3.7:
os.stat_float_times()function has been removed. It was introduced in Python 2.3 for backward compatibility with Python 2.2, and was deprecated since Python 3.1.
Unknown escapes consisting of
'\'and an ASCII letter in replacement templates for
re.sub()were deprecated in Python 3.5, and will now cause an error.
Removed support of the exclude argument in
tarfile.TarFile.add(). It was deprecated in Python 2.7 and 3.2. Use the filter argument instead.
splitunc()function in the
ntpathmodule was deprecated in Python 3.1, and has now been removed. Use the
collections.namedtuple()no longer supports the verbose parameter or
_sourceattribute which showed the generated source code for the named tuple class. This was part of an optimization designed to speed-up class creation. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger in bpo-28638.)
Removed previously deprecated in Python 2.4 classes
plistlibmodule. Dict values in the result of functions
readPlistFromBytes()are now normal dicts. You no longer can use attribute access to access items of these dictionaries.
asyncio.windows_utils.socketpair()function has been removed. Use the
socket.socketpair()function instead, it is available on all platforms since Python 3.5.
asyncio.windows_utils.socketpairwas just an alias to
socket.socketpairon Python 3.5 and newer.
Direct instantiation of
ssl.SSLObjectobjects is now prohibited. The constructors were never documented, tested, or designed as public constructors. Users were supposed to use
ssl.SSLContext. (Contributed by Christian Heimes in bpo-32951.)
fpectl module has been removed. It was never enabled by
default, never worked correctly on x86-64, and it changed the Python
ABI in ways that caused unexpected breakage of C extensions.
(Contributed by Nathaniel J. Smith in bpo-29137.)
The python launcher, (py.exe), can accept 32 & 64 bit specifiers without
having to specify a minor version as well. So
py -3-32 and
become valid as well as
py -3.7-32, also the -m-64 and -m.n-64 forms
are now accepted to force 64 bit python even if 32 bit would have otherwise
been used. If the specified version is not available py.exe will error exit.
(Contributed by Steve Barnes in bpo-30291.)
The launcher can be run as
py -0 to produce a list of the installed pythons,
with default marked with an asterisk. Running
py -0p will include the paths.
If py is run with a version specifier that cannot be matched it will also print
the short form list of available specifiers.
(Contributed by Steve Barnes in bpo-30362.)
Python 3.7 への移植¶
PEP 479 is enabled for all code in Python 3.7, meaning that
StopIterationexceptions raised directly or indirectly in coroutines and generators are transformed into
RuntimeErrorexceptions. (Contributed by Yury Selivanov in bpo-32670.)
以前のバージョンの Python で、誤って以下の構文を許容してしまっていました:
f(1 for x in ,) class C(1 for x in ): pass
Python 3.7 now correctly raises a
SyntaxError, as a generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side, and the duplication of the parentheses can be omitted only on calls. (Contributed by Serhiy Storchaka in bpo-32012 and bpo-32023.)
When using the
-mswitch, the initial working directory is now added to
sys.path, rather than an empty string (which dynamically denoted the current working directory at the time of each import). Any programs that are checking for the empty string, or otherwise relying on the previous behaviour, will need to be updated accordingly (e.g. by also checking for
os.path.dirname(__main__.__file__), depending on why the code was checking for the empty string in the first place).
Python API の変更¶
socketserver.ThreadingMixIn.server_close()now waits until all non-daemon threads complete. Set the new
socketserver.ThreadingMixIn.block_on_closeclass attribute to
Falseto get the pre-3.7 behaviour. (Contributed by Victor Stinner in bpo-31233 and bpo-33540.)
socketserver.ForkingMixIn.server_close()now waits until all child processes complete. Set the new
socketserver.ForkingMixIn.block_on_closeclass attribute to
Falseto get the pre-3.7 behaviour. (Contributed by Victor Stinner in bpo-31151 and bpo-33540.)
http.cookies.Morselare now read-only. Assigning to them was deprecated in Python 3.5. Use the
set()method for setting them. (Contributed by Serhiy Storchaka in bpo-29192.)
The mode argument of
os.makedirs()no longer affects the file permission bits of newly created intermediate-level directories. To set their file permission bits you can set the umask before invoking
makedirs(). (Contributed by Serhiy Storchaka in bpo-19930.)
parse_multipart()now accepts the encoding and errors arguments and returns the same results as
FieldStorage: for non-file fields, the value associated to a key is a list of strings, not bytes. (Contributed by Pierre Quentel in bpo-29979.)
shutil.rmtree()is now implemented using the
os.scandir()function, the user specified handler onerror is now called with the first argument
os.listdirwhen listing the directory is failed.
Support for nested sets and set operations in regular expressions as in Unicode Technical Standard #18 might be added in the future. This would change the syntax. To facilitate this future change a
FutureWarningwill be raised in ambiguous cases for the time being. That include sets starting with a literal
'['or containing literal character sequences
'||'. To avoid a warning, escape them with a backslash. (Contributed by Serhiy Storchaka in bpo-30349.)
The result of splitting a string on a
regular expressionthat could match an empty string has been changed. For example splitting on
r'\s*'will now split not only on whitespaces as it did previously, but also on empty strings before all non-whitespace characters and just before the end of the string. The previous behavior can be restored by changing the pattern to
FutureWarningwas emitted for such patterns since Python 3.5.
For patterns that match both empty and non-empty strings, the result of searching for all matches may also be changed in other cases. For example in the string
'a\n\n', the pattern
r'(?m)^\s*?$'will not only match empty strings at positions 2 and 3, but also the string
'\n'at positions 2--3. To match only blank lines, the pattern should be rewritten as
re.sub()now replaces empty matches adjacent to a previous non-empty match. For example
re.sub('x*', '-', 'abxd')returns now
'-a-b-d-'(the first minus between 'b' and 'd' replaces 'x', and the second minus replaces an empty string between 'x' and 'd').
On OSes that support
socket.SOCK_CLOEXECbit flags, the
socket.typeno longer has them applied. Therefore, checks like
if sock.type == socket.SOCK_STREAMwork as expected on all platforms. (Contributed by Yury Selivanov in bpo-32331.)
On Windows the default for the close_fds argument of
subprocess.Popenwas changed from
Truewhen redirecting the standard handles. If you previously depended on handles being inherited when using
subprocess.Popenwith standard io redirection, you will have to pass
close_fds=Falseto preserve the previous behaviour, or use
importlib.machinery.PathFinder.invalidate_caches()-- which implicitly affects
importlib.invalidate_caches()-- now deletes entries in
sys.path_importer_cachewhich are set to
None. (Contributed by Brett Cannon in bpo-33169.)
loop.getnameinfo()have been changed to be proper coroutine methods to match their documentation. Previously, these methods returned
asyncio.Futureinstances. (Contributed by Yury Selivanov in bpo-32327.)
Calendar.itermonthdateswill now consistently raise an exception when a date falls outside of the
9999-12-31range. To support applications that cannot tolerate such exceptions, the new
Calendar.itermonthdays4can be used. The new methods return tuples and are not restricted by the range supported by
datetime.date. (Contributed by Alexander Belopolsky in bpo-28292.)
concurrent.futures.ProcessPoolExecutornow raises a
RuntimeErrorif called during interpreter shutdown. (Contributed by Mark Nemec in bpo-33097.)
configparser.ConfigParserconstructor now uses
read_dict()to process the default values, making its behavior consistent with the rest of the parser. Non-string keys and values in the defaults dictionary are now being implicitly converted to strings. (Contributed by James Tocknell in bpo-23835.)
Several undocumented internal imports were removed. One example is that
os.errnois no longer available; use
import errnodirectly instead. Note that such undocumented internal imports may be removed any time without notice, even in micro version releases.
C API の変更¶
PySlice_GetIndicesEx() is considered unsafe for
resizable sequences. If the slice indices are not instances of
but objects that implement the
__index__() method, the sequence can be
resized after passing its length to
can lead to returning indices out of the length of the sequence. For
avoiding possible problems use new functions
(Contributed by Serhiy Storchaka in bpo-27867.)
STORE_ANNOTATION opcode has been removed.
(Contributed by Mark Shannon in bpo-32550.)
その他の CPython の実装の変更¶
In preparation for potential future changes to the public CPython runtime initialization API (see PEP 432 for an initial, but somewhat outdated, draft), CPython's internal startup and configuration management logic has been significantly refactored. While these updates are intended to be entirely transparent to both embedding applications and users of the regular CPython CLI, they're being mentioned here as the refactoring changes the internal order of various operations during interpreter startup, and hence may uncover previously latent defects, either in embedding applications, or in CPython itself. (Initially contributed by Nick Coghlan and Eric Snow as part of bpo-22257, and further updated by Nick, Eric, and Victor Stinner in a number of other issues). Some known details affected:
warnings filters added by an embedding application with
PySys_AddWarnOption()should now more consistently take precedence over the default filters set by the interpreter
Due to changes in the way the default warnings filters are configured,
Py_BytesWarningFlag to a value greater than one is no longer
sufficient to both emit
BytesWarning messages and have them converted
to exceptions. Instead, the flag must be set (to cause the warnings to be
emitted in the first place), and an explicit
warnings filter added to convert them to exceptions.
Due to a change in the way docstrings are handled by the compiler, the
return None in a function body consisting solely of a docstring
is now marked as occurring on the same line as the docstring, not on the
function's header line.
The current exception state has been moved from the frame object to the co-routine. This simplified the interpreter and fixed a couple of obscure bugs caused by having swap exception state when entering or exiting a generator. (Contributed by Mark Shannon in bpo-25612.)
Python 3.7.1 での重要な変更点¶
Starting in 3.7.1,
Py_Initialize() now consistently reads and respects
all of the same environment settings as
Py_Main() (in earlier Python
versions, it respected an ill-defined subset of those environment variables,
while in Python 3.7.0 it didn't read any of them due to bpo-34247). If
this behavior is unwanted, set
Py_IgnoreEnvironmentFlag to 1 before
In 3.7.1 the
tokenize module now implicitly emits a
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.)
Python 3.7.2 での重要な変更点¶
venv on Windows no longer copies the original binaries, but
creates redirector scripts named
This resolves a long standing issue where all virtual environments would have
to be upgraded or recreated with each Python update. However, note that this
release will still require recreation of virtual environments in order to get
the new scripts.
Python 3.7.6 での重要な変更点¶
asyncio.loop.create_datagram_endpoint() での reuse_address 引数は無効になりました。これはソケットオプション SO_REUSEADDR` のUDP における挙動が原因です。詳しくは、
loop.create_datagram_endpoint() のドキュメントを参照してください。(Kyle Stanley, Antoine Pitrou, Yury Selivanov による貢献 bpo-37228)
Python 3.7.10 での重要な変更点¶
Earlier Python versions allowed using both
query parameter separators in
urllib.parse.parse_qsl(). Due to security concerns, and to conform with
newer W3C recommendations, this has been changed to allow only a single
separator key, with
& as the default. This change also affects
cgi.parse_multipart() as they use the affected
functions internally. For more details, please see their respective
(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967.)