The operator is also useful with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop:
Another motivating use case arises in list comprehensions where a value computed in a filtering condition is also needed in the expression body:
Try to limit use of the walrus operator to clean cases that reduce complexity and improve readability.
仅位置参数
¶
There is a new function parameter syntax
/
to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments. This is the same notation shown by
help()
for C functions annotated with Larry Hastings’
Argument Clinic
工具。
In the following example, parameters
a
and
b
are positional-only, while
c
or
d
can be positional or keyword, and
e
or
f
are required to be keywords:
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
The following is a valid call:
f(10, 20, 30, d=40, e=50, f=60)
However, these are invalid calls:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument
One use case for this notation is that it allows pure Python functions to fully emulate behaviors of existing C coded functions. For example, the built-in
divmod()
function does not accept keyword arguments:
def divmod(a, b, /):
"Emulate the built in divmod() function"
return (a // b, a % b)
Another use case is to preclude keyword arguments when the parameter name is not helpful. For example, the builtin
len()
function has the signature
len(obj, /)
. This precludes awkward calls such as:
len(obj='hello') # The "obj" keyword argument impairs readability
A further benefit of marking a parameter as positional-only is that it allows the parameter name to be changed in the future without risk of breaking client code. For example, in the
statistics
module, the parameter name
dist
may be changed in the future. This was made possible with the following function specification:
def quantiles(dist, /, *, n=4, method='exclusive')
...
Since the parameters to the left of
/
are not exposed as possible keywords, the parameters names remain available for use in
**kwargs
:
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
This greatly simplifies the implementation of functions and methods that need to accept arbitrary keyword arguments. For example, here is an excerpt from code in the
collections
模块:
class Counter(dict):
def __init__(self, iterable=None, /, **kwds):
# Note "iterable" is a possible keyword argument
见
PEP 570
了解完整描述。
(Contributed by Pablo Galindo in
bpo-36540
)。
改进模块
¶
ast
¶
AST nodes now have
end_lineno
and
end_col_offset
attributes, which give the precise location of the end of the node. (This only applies to nodes that have
lineno
and
col_offset
attributes.)
New function
ast.get_source_segment()
returns the source code for a specific AST node.
(Contributed by Ivan Levkivskyi in
bpo-33416
)。
The
ast.parse()
function has some new flags:
-
type_comments=True
causes it to return the text of
PEP 484
and
PEP 526
type comments associated with certain AST nodes;
-
mode='func_type'
can be used to parse
PEP 484
“signature type comments” (returned for function definition AST nodes);
-
feature_version=(3, N)
allows specifying an earlier Python 3 version. For example,
feature_version=(3, 4)
will treat
async
and
await
as non-reserved words.
(Contributed by Guido van Rossum in
bpo-35766
)。
asyncio
¶
asyncio.run()
has graduated from the provisional to stable API. This function can be used to execute a
协程
and return the result while automatically managing the event loop. For example:
import asyncio
async def main():
await asyncio.sleep(0)
return 42
asyncio.run(main())
这为
roughly
equivalent to:
import asyncio
async def main():
await asyncio.sleep(0)
return 42
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
asyncio.set_event_loop(None)
loop.close()
The actual implementation is significantly more complex. Thus,
asyncio.run()
should be the preferred way of running asyncio programs.
(Contributed by Yury Selivanov in
bpo-32314
)。
运行
python -m asyncio
launches a natively async REPL. This allows rapid experimentation with code that has a top-level
await
. There is no longer a need to directly call
asyncio.run()
which would spawn a new event loop on every invocation:
$ python -m asyncio
asyncio REPL 3.8.0
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
hello
(Contributed by Yury Selivanov in
bpo-37028
)。
The exception
asyncio.CancelledError
now inherits from
BaseException
而不是
Exception
and no longer inherits from
concurrent.futures.CancelledError
. (Contributed by Yury Selivanov in
bpo-32528
)。
On Windows, the default event loop is now
ProactorEventLoop
. (Contributed by Victor Stinner in
bpo-34687
)。
ProactorEventLoop
now also supports UDP. (Contributed by Adam Meily and Andrew Svetlov in
bpo-29883
)。
ProactorEventLoop
can now be interrupted by
KeyboardInterrupt
(“CTRL+C”). (Contributed by Vladimir Matveev in
bpo-23057
)。
添加
asyncio.Task.get_coro()
for getting the wrapped coroutine within an
asyncio.Task
. (Contributed by Alex Grönholm in
bpo-36999
)。
Asyncio tasks can now be named, either by passing the
name
keyword argument to
asyncio.create_task()
或
create_task()
event loop method, or by calling the
set_name()
method on the task object. The task name is visible in the
repr()
output of
asyncio.Task
and can also be retrieved using the
get_name()
method. (Contributed by Alex Grönholm in
bpo-34270
)。
添加支持
Happy Eyeballs
to
asyncio.loop.create_connection()
. To specify the behavior, two new parameters have been added:
happy_eyeballs_delay
and
interleave
. The Happy Eyeballs algorithm improves responsiveness in applications that support IPv4 and IPv6 by attempting to simultaneously connect using both. (Contributed by twisteroid ambassador in
bpo-33530
)。
builtins
¶
The
compile()
built-in has been improved to accept the
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
flag. With this new flag passed,
compile()
will allow top-level
await
,
async for
and
async with
constructs that are usually considered invalid syntax. Asynchronous code object marked with the
CO_COROUTINE
flag may then be returned. (Contributed by Matthias Bussonnier in
bpo-34616
)
cProfile
¶
The
cProfile.Profile
class can now be used as a context manager. Profile a block of code by running:
import cProfile
with cProfile.Profile() as profiler:
# code to be profiled
...
(Contributed by Scott Sanderson in
bpo-29235
)。
curses
¶
Added a new variable holding structured version information for the underlying ncurses library:
ncurses_version
. (Contributed by Serhiy Storchaka in
bpo-31680
)。
ctypes
¶
在 Windows,
CDLL
和子类现在接受
winmode
参数以指定标志为底层
LoadLibraryEx
调用。默认标志被设为仅从受信任位置加载 DLL 依赖,包括 DLL 存储路径 (若使用完整或部分路径来加载初始 DLL) 和添加路径通过
add_dll_directory()
。(由 Steve Dower 史蒂夫·道尔提供在
bpo-36085
)。
gc
¶
get_objects()
can now receive an optional
generation
parameter indicating a generation to get objects from. (Contributed by Pablo Galindo in
bpo-36016
)。
gettext
¶
添加
pgettext()
and its variants. (Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in
bpo-2504
)。
gzip
¶
添加
mtime
参数用于
gzip.compress()
for reproducible output. (Contributed by Guo Ci Teo in
bpo-34898
)。
A
BadGzipFile
exception is now raised instead of
OSError
for certain types of invalid or corrupt gzip files. (Contributed by Filip Gruszczyński, Michele Orrù, and Zackery Spytz in
bpo-6584
)。
IDLE and idlelib
¶
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
)。
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 also 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
)。
Added 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
)。
OS native encoding is now used for converting between Python strings and Tcl objects. This allows IDLE to work with emoji and other non-BMP characters. These characters can be displayed or copied and pasted to or from the clipboard. Converting strings from Tcl to Python and back now never fails. (Many people worked on this for eight years but the problem was finally solved by Serhiy Storchaka in
bpo-13153
)。
New in 3.8.1:
Add option to toggle cursor blink off. (Contributed by Zackery Spytz in
bpo-4603
)。
Escape key now closes IDLE completion windows. (Contributed by Johnny Najera in
bpo-38944
)。
The changes above have been backported to 3.7 maintenance releases.
Add keywords to module name completion list. (Contributed by Terry J. Reedy in
bpo-37765
)。
inspect
¶
The
inspect.getdoc()
function can now find docstrings for
__slots__
if that attribute is a
dict
where the values are docstrings. This provides documentation options similar to what we already have for
property()
,
classmethod()
,和
staticmethod()
:
class AudioClip:
__slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
'duration': 'in seconds, rounded up to an integer'}
def __init__(self, bit_rate, duration):
self.bit_rate = round(bit_rate / 1000.0, 1)
self.duration = ceil(duration)
(Contributed by Raymond Hettinger in
bpo-36326
)。
io
¶
In development mode (
-X
env
) and in
调试构建
,
io.IOBase
finalizer now logs the exception if the
close()
method fails. The exception is ignored silently by default in release build. (Contributed by Victor Stinner in
bpo-18748
)。
logging
¶
添加
force
keyword argument to
logging.basicConfig()
. When set to true, any existing handlers attached to the root logger are removed and closed before carrying out the configuration specified by the other arguments.
This solves a long-standing problem. Once a logger or
basicConfig()
had been called, subsequent calls to
basicConfig()
were silently ignored. This made it difficult to update, experiment with, or teach the various logging configuration options using the interactive prompt or a Jupyter notebook.
(Suggested by Raymond Hettinger, implemented by Donghee Na, and reviewed by Vinay Sajip in
bpo-33897
)。
math
¶
添加新的函数
math.dist()
for computing Euclidean distance between two points. (Contributed by Raymond Hettinger in
bpo-33089
)。
Expanded the
math.hypot()
function to handle multiple dimensions. Formerly, it only supported the 2-D case. (Contributed by Raymond Hettinger in
bpo-33089
)。
Added new function,
math.prod()
, as analogous function to
sum()
that returns the product of a ‘start’ value (default: 1) times an iterable of numbers:
>>> prior = 0.8
>>> likelihoods = [0.625, 0.84, 0.30]
>>> math.prod(likelihoods, start=prior)
0.126
(Contributed by Pablo Galindo in
bpo-35606
)。
Added two new combinatoric functions
math.perm()
and
math.comb()
:
>>> math.perm(10, 3) # Permutations of 10 things taken 3 at a time
720
>>> math.comb(10, 3) # Combinations of 10 things taken 3 at a time
120
(Contributed by Yash Aggarwal, Keller Fuchs, Serhiy Storchaka, and Raymond Hettinger in
bpo-37128
,
bpo-37178
,和
bpo-35431
)。
添加新函数
math.isqrt()
for computing accurate integer square roots without conversion to floating point. The new function supports arbitrarily large integers. It is faster than
floor(sqrt(n))
but slower than
math.sqrt()
:
>>> r = 650320427
>>> s = r ** 2
>>> isqrt(s - 1) # correct
650320426
>>> floor(sqrt(s - 1)) # incorrect
650320427
(Contributed by Mark Dickinson in
bpo-36887
)。
函数
math.factorial()
no longer accepts arguments that are not int-like. (Contributed by Pablo Galindo in
bpo-33083
)。
os
¶
添加新的函数
add_dll_directory()
在 Windows 用于为本机依赖提供额外搜索路径,当导入扩展模块时或加载 DLL 使用
ctypes
。(由 Steve Dower 史蒂夫·道尔提供在
bpo-36085
)。
新的
os.memfd_create()
function was added to wrap the
memfd_create()
syscall. (Contributed by Zackery Spytz and Christian Heimes in
bpo-26836
)。
On Windows, much of the manual logic for handling reparse points (including symlinks and directory junctions) has been delegated to the operating system. Specifically,
os.stat()
will now traverse anything supported by the operating system, while
os.lstat()
will only open reparse points that identify as “name surrogates” while others are opened as for
os.stat()
. In all cases,
stat_result.st_mode
will only have
S_IFLNK
set for symbolic links and not other kinds of reparse points. To identify other kinds of reparse point, check the new
stat_result.st_reparse_tag
属性。
在 Windows,
os.readlink()
is now able to read directory junctions. Note that
islink()
将返回
False
for directory junctions, and so code that checks
islink
first will continue to treat junctions as directories, while code that handles errors from
os.readlink()
may now treat junctions as links.
(Contributed by Steve Dower in
bpo-37834
)。
pickle
¶
pickle
extensions subclassing the C-optimized
Pickler
can now override the pickling logic of functions and classes by defining the special
reducer_override()
method. (Contributed by Pierre Glaser and Olivier Grisel in
bpo-35900
)。
plistlib
¶
添加新
plistlib.UID
and enabled support for reading and writing NSKeyedArchiver-encoded binary plists. (Contributed by Jon Janzen in
bpo-26707
)。
pprint
¶
The
pprint
module added a
sort_dicts
parameter to several functions. By default, those functions continue to sort dictionaries before rendering or printing. However, if
sort_dicts
is set to false, the dictionaries retain the order that keys were inserted. This can be useful for comparison to JSON inputs during debugging.
In addition, there is a convenience new function,
pprint.pp()
that is like
pprint.pprint()
but with
sort_dicts
defaulting to
False
:
>>> from pprint import pprint, pp
>>> d = dict(source='input.txt', operation='filter', destination='output.txt')
>>> pp(d, width=40) # Original order
{'source': 'input.txt',
'operation': 'filter',
'destination': 'output.txt'}
>>> pprint(d, width=40) # Keys sorted alphabetically
{'destination': 'output.txt',
'operation': 'filter',
'source': 'input.txt'}
(Contributed by Rémi Lapeyre in
bpo-30670
)。
shutil
¶
shutil.copytree()
now accepts a new
dirs_exist_ok
keyword argument. (Contributed by Josh Bronson in
bpo-20849
)。
shutil.make_archive()
now defaults to the modern pax (POSIX.1-2001) format for new archives to improve portability and standards conformance, inherited from the corresponding change to the
tarfile
module. (Contributed by C.A.M. Gerlach in
bpo-30661
)。
shutil.rmtree()
on Windows now removes directory junctions without recursively removing their contents first. (Contributed by Steve Dower in
bpo-37834
)。
statistics
¶
添加
statistics.fmean()
as a faster, floating-point variant of
statistics.mean()
. (Contributed by Raymond Hettinger and Steven D’Aprano in
bpo-35904
)。
添加
statistics.geometric_mean()
(Contributed by Raymond Hettinger in
bpo-27181
)。
添加
statistics.multimode()
that returns a list of the most common values. (Contributed by Raymond Hettinger in
bpo-35892
)。
添加
statistics.quantiles()
that divides data or a distribution in to equiprobable intervals (e.g. quartiles, deciles, or percentiles). (Contributed by Raymond Hettinger in
bpo-36546
)。
添加
statistics.NormalDist
, a tool for creating and manipulating normal distributions of a random variable. (Contributed by Raymond Hettinger in
bpo-36018
)。
>>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
>>> temperature_feb.mean
6.0
>>> temperature_feb.stdev
6.356099432828281
>>> temperature_feb.cdf(3) # Chance of being under 3 degrees
0.3184678262814532
>>> # Relative chance of being 7 degrees versus 10 degrees
>>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
1.2039930378537762
>>> el_niño = NormalDist(4, 2.5)
>>> temperature_feb += el_niño # Add in a climate effect
>>> temperature_feb
NormalDist(mu=10.0, sigma=6.830080526611674)
>>> temperature_feb * (9/5) + 32 # Convert to Fahrenheit
NormalDist(mu=50.0, sigma=12.294144947901014)
>>> temperature_feb.samples(3) # Generate random samples
[7.672102882379219, 12.000027119750287, 4.647488369766392]
sys
¶
Add new
sys.unraisablehook()
function which can be overridden to control how “unraisable exceptions” are handled. It is called when an exception has occurred but there is no way for Python to handle it. For example, when a destructor raises an exception or during garbage collection (
gc.collect()
). (Contributed by Victor Stinner in
bpo-36829
)。
tarfile
¶
The
tarfile
module now defaults to the modern pax (POSIX.1-2001) format for new archives, instead of the previous GNU-specific one. This improves cross-platform portability with a consistent encoding (UTF-8) in a standardized and extensible format, and offers several other benefits. (Contributed by C.A.M. Gerlach in
bpo-36268
)。
tokenize
¶
The
tokenize
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
)。
tkinter
¶
Added methods
selection_from()
,
selection_present()
,
selection_range()
and
selection_to()
在
tkinter.Spinbox
class. (Contributed by Juliette Monsel in
bpo-34829
)。
Added method
moveto()
在
tkinter.Canvas
class. (Contributed by Juliette Monsel in
bpo-23831
)。
The
tkinter.PhotoImage
class now has
transparency_get()
and
transparency_set()
methods. (Contributed by Zackery Spytz in
bpo-25451
)。
typing
¶
The
typing
module incorporates several new features:
-
A dictionary type with per-key types. See
PEP 589
and
typing.TypedDict
. TypedDict uses only string keys. By default, every key is required to be present. Specify “total=False” to allow keys to be optional:
class Location(TypedDict, total=False):
lat_long: tuple
grid_square: str
xy_coordinate: tuple
-
Literal types. See
PEP 586
and
typing.Literal
. Literal types indicate that a parameter or return value is constrained to one or more specific literal values:
def get_status(port: int) -> Literal['connected', 'disconnected']:
...
-
“Final” variables, functions, methods and classes. See
PEP 591
,
typing.Final
and
typing.final()
. The final qualifier instructs a static type checker to restrict subclassing, overriding, or reassignment:
pi: Final[float] = 3.1415926536
-
Protocol definitions. See
PEP 544
,
typing.Protocol
and
typing.runtime_checkable()
. Simple ABCs like
typing.SupportsInt
are now
Protocol
子类。
-
New protocol class
typing.SupportsIndex
.
-
New functions
typing.get_origin()
and
typing.get_args()
.
unicodedata
¶
The
unicodedata
module has been upgraded to use the
Unicode 12.1.0
release.
New function
is_normalized()
can be used to verify a string is in a specific normal form, often much faster than by actually normalizing the string. (Contributed by Max Belanger, David Euresti, and Greg Price in
bpo-32285
and
bpo-37966
).
unittest
¶
添加
AsyncMock
to support an asynchronous version of
Mock
. Appropriate new assert functions for testing have been added as well. (Contributed by Lisa Roach in
bpo-26467
).
添加
addModuleCleanup()
and
addClassCleanup()
to unittest to support cleanups for
setUpModule()
and
setUpClass()
. (Contributed by Lisa Roach in
bpo-24412
)。
Several mock assert functions now also print a list of actual calls upon failure. (Contributed by Petter Strandmark in
bpo-35047
)。
unittest
module gained support for coroutines to be used as test cases with
unittest.IsolatedAsyncioTestCase
. (Contributed by Andrew Svetlov in
bpo-32972
)。
范例:
import unittest
class TestRequest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.connection = await AsyncConnection()
async def test_get(self):
response = await self.connection.get("https://example.com")
self.assertEqual(response.status_code, 200)
async def asyncTearDown(self):
await self.connection.close()
if __name__ == "__main__":
unittest.main()
venv
¶
venv
now includes an
Activate.ps1
script on all platforms for activating virtual environments under PowerShell Core 6.1. (Contributed by Brett Cannon in
bpo-32718
)。
weakref
¶
The proxy objects returned by
weakref.proxy()
now support the matrix multiplication operators
@
and
@=
in addition to the other numeric operators. (Contributed by Mark Dickinson in
bpo-36669
)。
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
bpo-17239
)。
The
.find*()
methods in the
xml.etree.ElementTree
module support wildcard searches like
{*}tag
which ignores the namespace and
{namespace}*
which returns all tags in the given namespace. (Contributed by Stefan Behnel in
bpo-28238
)。
The
xml.etree.ElementTree
module provides a new function
–xml.etree.ElementTree.canonicalize()
that implements C14N 2.0. (Contributed by Stefan Behnel in
bpo-13611
)。
The target object of
xml.etree.ElementTree.XMLParser
can receive namespace declaration events through the new callback methods
start_ns()
and
end_ns()
。此外,
xml.etree.ElementTree.TreeBuilder
target can be configured to process events about comments and processing instructions to include them in the generated tree. (Contributed by Stefan Behnel in
bpo-36676
and
bpo-36673
)。
xmlrpc
¶
xmlrpc.client.ServerProxy
now supports an optional
headers
keyword argument for a sequence of HTTP headers to be sent with each request. Among other things, this makes it possible to upgrade from default basic authentication to faster session authentication. (Contributed by Cédric Krier in
bpo-35153
)。