注意
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.
The
ssl
module no longer sends IP addresses in SNI TLS extension. (Contributed by Christian Heimes in
bpo-32185
)。
match_hostname()
no longer supports partial wildcards like
www*.example.org
. (Contributed by Mandeep Singh in
bpo-23033
and Christian Heimes in
bpo-31399
)。
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
SSLSocket.server_hostname
attribute now stores the expected hostname in A-label form (
"xn--pythn-mua.org"
), rather than the U-label form (
"pythön.org"
). (Contributed by Nathaniel J. Smith and Christian Heimes in
bpo-28414
)。
The
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
)
SSLSocket
and
SSLObject
no longer have a public constructor. Direct instantiation was never a documented and supported feature. Instances must be created with
SSLContext
方法
wrap_socket()
and
wrap_bio()
. (Contributed by Christian Heimes in
bpo-32951
)
OpenSSL 1.1 APIs for setting the minimum and maximum TLS protocol version are available as
SSLContext.minimum_version
and
SSLContext.maximum_version
. Supported protocols are indicated by several new flags, such as
HAS_TLSv1_1
. (Contributed by Christian Heimes in
bpo-32609
)。
添加
ssl.SSLContext.post_handshake_auth
to enable and
ssl.SSLSocket.verify_client_post_handshake()
to initiate TLS 1.3 post-handshake authentication. (Contributed by Christian Heimes in
gh-78851
)。
string
¶
string.Template
now lets you to optionally modify the regular expression pattern for braced placeholders and non-braced placeholders separately. (Contributed by Barry Warsaw in
bpo-1198569
)。
subprocess
¶
The
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
stderr
arguments. (Contributed by Bo Bayles in
bpo-32102
)。
The
subprocess.run
函数和
subprocess.Popen
constructor now accept the
text
keyword argument as an alias to
universal_newlines
. (Contributed by Andrew Clegg in
bpo-31756
)。
On Windows the default for
close_fds
was changed from
False
to
True
when redirecting the standard handles. It’s now possible to set
close_fds
to true when redirecting the standard handles. See
subprocess.Popen
。这意味着
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
KeyboardInterrupt
during
subprocess.call()
,
subprocess.run()
, or in a
Popen
context manager. It now waits a short amount of time for the child to exit, before continuing the handling of the
KeyboardInterrupt
exception. (Contributed by Gregory P. Smith in
bpo-25942
)。
tracemalloc
¶
tracemalloc.Traceback
behaves more like regular tracebacks, sorting the frames from oldest to most recent.
Traceback.format()
now accepts negative
limit
, truncating the result to the
abs(limit)
oldest frames. To get the old behaviour, use the new
most_recent_first
自变量对于
Traceback.format()
. (Contributed by Jesse Bakker in
bpo-32121
)。
unicodedata
¶
The internal
unicodedata
database has been upgraded to use
Unicode 11
. (Contributed by Benjamin Peterson.)
unittest
¶
新的
-k
command-line option allows filtering tests by a name substring or a Unix shell-like pattern. For example,
python -m unittest -k foo
runs
foo_tests.SomeTest.test_something
,
bar_tests.SomeTest.test_foo
, but not
bar_tests.FooTest.test_something
. (Contributed by Jonas Haag in
bpo-32071
)。
unittest.mock
¶
The
sentinel
attributes now preserve their identity when they are
copied
or
pickled
. (Contributed by Serhiy Storchaka in
bpo-20804
)。
新的
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
)。
uu
¶
The
uu.encode()
function now accepts an optional
backtick
keyword argument. When it’s true, zeros are represented by
'`'
instead of spaces. (Contributed by Xiang Zhang in
bpo-30103
)。
uuid
¶
新的
UUID.is_safe
attribute relays information from the platform about whether generated UUIDs are generated with a multiprocessing-safe method. (Contributed by Barry Warsaw in
bpo-22807
)。
uuid.getnode()
now prefers universally administered MAC addresses over locally administered MAC addresses. This makes a better guarantee for global uniqueness of UUIDs returned from
uuid.uuid1()
. If only locally administered MAC addresses are available, the first such one found is returned. (Contributed by Barry Warsaw in
bpo-32107
)。
warnings
¶
The initialization of the default warnings filters has changed as follows:
-
warnings enabled via command line options (including those for
-b
and the new CPython-specific
-X
dev
option) are always passed to the warnings machinery via the
sys.warnoptions
属性。
-
warnings filters enabled via the command line or the environment now have the following order of precedence:
-
the
BytesWarning
filter for
-b
(或
-bb
)
-
any filters specified with the
-W
option
-
any filters specified with the
PYTHONWARNINGS
环境变量
-
any other CPython specific filters (e.g. the
default
filter added for the new
-X dev
mode)
-
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)
(Contributed by Nick Coghlan and Victor Stinner in
bpo-20361
,
bpo-32043
,和
bpo-32230
)。
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
)。
xml
¶
As mitigation against DTD and external entity retrieval, the
xml.dom.minidom
and
xml.sax
modules no longer process external entities by default. (Contributed by Christian Heimes in
gh-61441
)。
xml.etree
¶
ElementPath
predicates in the
find()
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
)。
xmlrpc.server
¶
SimpleXMLRPCDispatcher.register_function
can now be used as a decorator. (Contributed by Xiang Zhang in
bpo-7769
)。
zipapp
¶
函数
create_archive()
now accepts an optional
filter
argument to allow the user to select which files should be included in the archive. (Contributed by Irmen de Jong in
bpo-31072
)。
函数
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
)。
zipfile
¶
ZipFile
now accepts the new
compresslevel
parameter to control the compression level. (Contributed by Bo Bayles in
bpo-21417
)。
Subdirectories in archives created by
ZipFile
are now stored in alphabetical order. (Contributed by Bernhard M. Wiedemann in
bpo-30693
)。
构建变化
¶
Support for building
--without-threads
has been removed. The
threading
module is now always available. (Contributed by Antoine Pitrou in
bpo-31370
.).
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
)。
The
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
METH_FASTCALL
convention. (Contributed by Victor Stinner in
bpo-29300
,
bpo-29507
,
bpo-29452
,和
bpo-29286
)。
Various optimizations have reduced Python startup time by 10% on Linux and up to 30% on macOS. (Contributed by Victor Stinner, INADA Naoki in
bpo-29585
, and Ivan Levkivskyi in
bpo-31333
)。
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
)。
The
asyncio
module received a number of notable optimizations for commonly used functions:
-
The
asyncio.get_event_loop()
function has been reimplemented in C to make it up to 15 times faster. (Contributed by Yury Selivanov in
bpo-32296
)。
-
asyncio.Future
callback management has been optimized. (Contributed by Yury Selivanov in
bpo-32348
)。
-
asyncio.gather()
is now up to 15% faster. (Contributed by Yury Selivanov in
bpo-32355
)。
-
asyncio.sleep()
is now up to 2 times faster when the
delay
argument is zero or negative. (Contributed by Andrew Svetlov in
bpo-32351
)。
-
The performance overhead of asyncio debug mode has been reduced. (Contributed by Antoine Pitrou in
bpo-31970
)。
As a result of
PEP 560 work
, the import time of
typing
has been reduced by a factor of 7, and many typing operations are now faster. (Contributed by Ivan Levkivskyi in
bpo-32226
)。
sorted()
and
list.sort()
have been optimized for common cases to be up to 40-75% faster. (Contributed by Elliot Gorokhovsky in
bpo-28685
)。
dict.copy()
is now up to 5.5 times faster. (Contributed by Yury Selivanov in
bpo-31179
)。
hasattr()
and
getattr()
are now about 4 times faster when
name
is not found and
obj
does not override
object.__getattr__()
or
object.__getattribute__()
. (Contributed by INADA Naoki in
bpo-32544
)。
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
)。
The
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.fromordinal()
and
date.fromtimestamp()
are now up to 30% faster in the common case. (Contributed by Paul Ganssle in
bpo-32403
)。
The
os.fwalk()
function is now up to 2 times faster thanks to the use of
os.scandir()
. (Contributed by Serhiy Storchaka in
bpo-25996
)。
The speed of the
shutil.rmtree()
function has been improved by 20–40% thanks to the use of the
os.scandir()
function. (Contributed by Serhiy Storchaka in
bpo-28564
)。
Optimized case-insensitive matching and searching of
regular
expressions
. Searching some patterns can now be up to 20 times faster. (Contributed by Serhiy Storchaka in
bpo-30285
)。
re.compile()
now converts
flags
parameter to int object if it is
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
)。
The
modify()
methods of classes
selectors.EpollSelector
,
selectors.PollSelector
and
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
isinstance()
and
issubclass()
on them 1.5x faster. This also reduces Python start-up time by up to 10%. (Contributed by Ivan Levkivskyi and INADA Naoki in
bpo-31333
)
Significant speed improvements to alternate constructors for
datetime.date
and
datetime.datetime
by using fast-path constructors when not constructing subclasses. (Contributed by Paul Ganssle in
bpo-32403
)
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
)。
The
math.erf()
and
math.erfc()
functions now use the (faster) C library implementation on most platforms. (Contributed by Serhiy Storchaka in
bpo-26121
)。
其它 CPython 实现变化
¶
-
Trace hooks may now opt out of receiving the
line
and opt into receiving the
opcode
events from the interpreter by setting the corresponding new
f_trace_lines
and
f_trace_opcodes
attributes 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__.origin
is also set to
None
(previously the string
"namespace"
)。见
bpo-32305
. Also, the namespace module object’s
__spec__.loader
is set to the same value as
__loader__
(previously, the former was set to
None
)。见
bpo-32303
.
-
The
locals()
dictionary now displays in the lexical order that variables were defined. Previously, the order was undefined. (Contributed by Raymond Hettinger in
bpo-32690
)。
-
The
distutils
upload
command 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
and
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
生成器迭代器
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
SyntaxError
. (Contributed by Serhiy Storchaka in
bpo-10544
)。
Returning a subclass of
complex
from
object.__complex__()
is deprecated and will be an error in future Python versions. This makes
__complex__()
consistent with
object.__int__()
and
object.__float__()
. (Contributed by Serhiy Storchaka in
bpo-28894
)。
弃用 Python 模块、函数和方法
¶
aifc
¶
aifc.openfp()
has been deprecated and will be removed in Python 3.9. Use
aifc.open()
instead. (Contributed by Brian Curtin in
bpo-31985
)。
asyncio
¶
Support for directly
await
-ing instances of
asyncio.Lock
and 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
)。
The
asyncio.Task.current_task()
and
asyncio.Task.all_tasks()
methods have been deprecated. (Contributed by Andrew Svetlov in
bpo-32250
)。
collections
¶
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 base classes. (Contributed by Serhiy Storchaka in
bpo-25988
)。
dbm
¶
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
'r'
and
'w'
modes (this will be an error in future Python releases). (Contributed by Serhiy Storchaka in
bpo-28847
)。
enum
¶
In Python 3.8, attempting to check for non-Enum objects in
Enum
classes will raise a
TypeError
(如
1 in Color
); similarly, attempting to check for non-Flag objects in a
Flag
member will raise
TypeError
(如
1 in Perm.RW
); currently, both operations return
False
instead. (Contributed by Ethan Furman in
bpo-33217
)。
gettext
¶
Using non-integer value for selecting a plural form in
gettext
is now deprecated. It never correctly worked. (Contributed by Serhiy Storchaka in
bpo-28692
)。
macpath
¶
The
macpath
is now deprecated and will be removed in Python 3.8. (Contributed by Chi Hsuan Yen in
bpo-9850
)。
threading
¶
dummy_threading
and
_dummy_thread
have been deprecated. It is no longer possible to build Python with threading disabled. Use
threading
instead. (Contributed by Antoine Pitrou in
bpo-31370
)。
socket
¶
The silent argument value truncation in
socket.htons()
and
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
)。
sunau
¶
sunau.openfp()
has been deprecated and will be removed in Python 3.9. Use
sunau.open()
instead. (Contributed by Brian Curtin in
bpo-31985
)。
sys
¶
弃用
sys.set_coroutine_wrapper()
and
sys.get_coroutine_wrapper()
.
The undocumented
sys.callstats()
function has been deprecated and will be removed in a future Python version. (Contributed by Victor Stinner in
bpo-28799
)。
wave
¶
wave.openfp()
has been deprecated and will be removed in Python 3.9. Use
wave.open()
instead. (Contributed by Brian Curtin in
bpo-31985
)。
API 和特征移除
¶
The following features and APIs have been removed from Python 3.7:
-
The
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.
-
未知转义组成通过
'\'
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
自变量代替。
-
The
ntpath.splitunc()
function was deprecated in Python 3.1, and has now been removed. Use
splitdrive()
代替。
-
collections.namedtuple()
no longer supports the
verbose
parameter or
_source
attribute 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
)。
-
函数
bool()
,
float()
,
list()
and
tuple()
no longer take keyword arguments. The first argument of
int()
can now be passed only as positional argument.
-
Removed previously deprecated in Python 2.4 classes
Plist
,
Dict
and
_InternalDict
在
plistlib
module. Dict values in the result of functions
readPlist()
and
readPlistFromBytes()
are now normal dicts. You no longer can use attribute access to access items of these dictionaries.
-
The
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.socketpair
was just an alias to
socket.socketpair
on Python 3.5 and newer.
-
asyncio
no longer exports the
selectors
and
_overlapped
modules as
asyncio.selectors
and
asyncio._overlapped
. Replace
from asyncio import selectors
with
import selectors
.
-
Direct instantiation of
ssl.SSLSocket
and
ssl.SSLObject
objects is now prohibited. The constructors were never documented, tested, or designed as public constructors. Users were supposed to use
ssl.wrap_socket()
or
ssl.SSLContext
. (Contributed by Christian Heimes in
bpo-32951
)。
-
The unused
distutils
install_misc
command has been removed. (Contributed by Eric N. Vander Weele in
bpo-29218
)。
模块移除
¶
The
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
)。
仅 Windows 变化
¶
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
py -3-64
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
¶
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in Python Behavior
¶
-
async
and
await
names are now reserved keywords. Code using these names as identifiers will now raise a
SyntaxError
. (Contributed by Jelle Zijlstra in
bpo-30406
)。
-
PEP 479
is enabled for all code in Python 3.7, meaning that
StopIteration
exceptions raised directly or indirectly in coroutines and generators are transformed into
RuntimeError
exceptions. (Contributed by Yury Selivanov in
bpo-32670
)。
-
object.__aiter__()
methods can no longer be declared as asynchronous. (Contributed by Yury Selivanov in
bpo-31709
)。
-
Due to an oversight, earlier Python versions erroneously accepted the following syntax:
f(1 for x in [1],)
class C(1 for x in [1]):
pass