Python 3.9 有什麼新功能¶
- 編輯者:
Łukasz Langa
本文介紹了 Python 3.9 與 3.8 相比多了哪些新功能。Python 3.9 已於 2020 年 10 月 5 日發布。有關完整詳細資訊,請參閱changelog。
也參考
PEP 596 - Python 3.9 發佈時程
發布重點摘要¶
新增語法特性:
PEP 584, union operators added to
dict
;PEP 585, type hinting generics in standard collections;
PEP 614, relaxed grammar restrictions on decorators.
新的內建功能:
PEP 616, string methods to remove prefixes and suffixes.
New features in the standard library:
PEP 593, flexible function and variable annotations;
os.pidfd_open()
added that allows process management without racesand signals.
直譯器的改進:
PEP 573, fast access to module state from methods of C extensiontypes;
PEP 617, CPython now uses a new parser based on PEG;
a number of Python builtins (range, tuple, set, frozenset, list, dict) arenow sped up usingPEP 590 vectorcall;
garbage collection does not block on resurrected objects;
a number of Python modules (
_abc
,audioop
,_bz2
,_codecs
,_contextvars
,_crypt
,_functools
,_json
,_locale
,math
,operator
,resource
,time
,_weakref
) now use multiphase initialization as definedby PEP 489;a number of standard library modules (
audioop
,ast
,grp
,_hashlib
,pwd
,_posixsubprocess
,random
,select
,struct
,termios
,zlib
) are now usingthe stable ABI defined by PEP 384.
新的函式庫模組:
PEP 615, the IANA Time Zone Database is now present in the standardlibrary in the
zoneinfo
module;an implementation of a topological sort of a graph is now provided inthe new
graphlib
module.
Release process changes:
PEP 602, CPython adopts an annual release cycle.
You should check for DeprecationWarning in your code¶
When Python 2.7 was still supported, a lot of functionality in Python 3was kept for backward compatibility with Python 2.7. With the end of Python2 support, these backward compatibility layers have been removed, or willbe removed soon. Most of them emitted aDeprecationWarning
warning forseveral years. For example, usingcollections.Mapping
instead ofcollections.abc.Mapping
emits aDeprecationWarning
since Python3.3, released in 2012.
Test your application with the-W
default
command-line option to seeDeprecationWarning
andPendingDeprecationWarning
, or even with-W
error
to treat them as errors.Warnings Filter can be used to ignore warnings from third-party code.
Python 3.9 is the last version providing those Python 2 backward compatibilitylayers, to give more time to Python projects maintainers to organize theremoval of the Python 2 support and add support for Python 3.9.
Aliases toAbstract Base Classes inthecollections
module, likecollections.Mapping
alias tocollections.abc.Mapping
, are kept for one last release for backwardcompatibility. They will be removed from Python 3.10.
More generally, try to run your tests in thePython Development Mode which helps to prepare your code to make it compatible with thenext Python version.
Note: a number of pre-existing deprecations were removed in this version ofPython as well. Consult the已移除 section.
新增功能¶
Dictionary Merge & Update Operators¶
Merge (|
) and update (|=
) operators have been added to the built-indict
class. Those complement the existingdict.update
and{**d1,**d2}
methods of merging dictionaries.
範例:
>>>x={"key1":"value1 from x","key2":"value2 from x"}>>>y={"key2":"value2 from y","key3":"value3 from y"}>>>x|y{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}>>>y|x{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}
SeePEP 584 for a full description.(Contributed by Brandt Bucher inbpo-36144.)
New String Methods to Remove Prefixes and Suffixes¶
str.removeprefix(prefix)
andstr.removesuffix(suffix)
have been addedto easily remove an unneeded prefix or a suffix from a string. Correspondingbytes
,bytearray
, andcollections.UserString
methods have also beenadded. SeePEP 616 for a full description. (Contributed by Dennis Sweeney inbpo-39939.)
Type Hinting Generics in Standard Collections¶
In type annotations you can now use built-in collection types such aslist
anddict
as generic types instead of importing thecorresponding capitalized types (e.g.List
orDict
) fromtyping
. Some other types in the standard library are also now generic,for examplequeue.Queue
.
範例:
defgreet_all(names:list[str])->None:fornameinnames:print("Hello",name)
SeePEP 585 for more details. (Contributed by Guido van Rossum,Ethan Smith, and Batuhan Taşkaya inbpo-39481.)
New Parser¶
Python 3.9 uses a new parser, based onPEG insteadofLL(1). The newparser's performance is roughly comparable to that of the old parser,but the PEG formalism is more flexible than LL(1) when it comes todesigning new language features. We'll start using this flexibilityin Python 3.10 and later.
Theast
module uses the new parser and produces the same AST asthe old parser.
In Python 3.10, the old parser will be deleted and so will allfunctionality that depends on it (primarily theparser
module,which has long been deprecated). In Python 3.9only, you can switchback to the LL(1) parser using a command line switch (-Xoldparser
) or an environment variable (PYTHONOLDPARSER=1
).
SeePEP 617 for more details. (Contributed by Guido van Rossum,Pablo Galindo and Lysandros Nikolaou inbpo-40334.)
其他語言更動¶
__import__()
now raisesImportError
instead ofValueError
, which used to occur when a relative import went pastits top-level package.(Contributed by Ngalim Siregar inbpo-37444.)Python now gets the absolute path of the script filename specified onthe command line (ex:
python3script.py
): the__file__
attribute ofthe__main__
module became an absolute path, rather than a relativepath. These paths now remain valid after the current directory is changedbyos.chdir()
. As a side effect, the traceback also displays theabsolute path for__main__
module frames in this case.(Contributed by Victor Stinner inbpo-20443.)In thePython Development Mode and indebug build, theencoding anderrors arguments are now checked for string encoding anddecoding operations. Examples:
open()
,str.encode()
andbytes.decode()
.By default, for best performance, theerrors argument is only checked atthe first encoding/decoding error and theencoding argument is sometimesignored for empty strings.(Contributed by Victor Stinner inbpo-37388.)
"".replace("",s,n)
now returnss
instead of an empty string forall non-zeron
. It is now consistent with"".replace("",s)
.There are similar changes forbytes
andbytearray
objects.(Contributed by Serhiy Storchaka inbpo-28029.)Any valid expression can now be used as adecorator. Previously, thegrammar was much more restrictive. SeePEP 614 for details.(Contributed by Brandt Bucher inbpo-39702.)
Improved help for the
typing
module. Docstrings are now shown forall special forms and special generic aliases (likeUnion
andList
).Usinghelp()
with generic alias likeList[int]
will show the helpfor the correspondent concrete type (list
in this case).(Contributed by Serhiy Storchaka inbpo-40257.)Parallel running of
aclose()
/asend()
/athrow()
is now prohibited, andag_running
now reflectsthe actual running status of the async generator.(Contributed by Yury Selivanov inbpo-30773.)Unexpected errors in calling the
__iter__
method are no longer masked byTypeError
in thein
operator and functionscontains()
,indexOf()
andcountOf()
of theoperator
module.(Contributed by Serhiy Storchaka inbpo-40824.)Unparenthesized lambda expressions can no longer be the expression part in an
if
clause in comprehensions and generator expressions. Seebpo-41848andbpo-43755 for details.
新模組¶
zoneinfo¶
Thezoneinfo
module brings support for the IANA time zone database tothe standard library. It addszoneinfo.ZoneInfo
, a concretedatetime.tzinfo
implementation backed by the system's time zone data.
範例:
>>>fromzoneinfoimportZoneInfo>>>fromdatetimeimportdatetime,timedelta>>># Daylight saving time>>>dt=datetime(2020,10,31,12,tzinfo=ZoneInfo("America/Los_Angeles"))>>>print(dt)2020-10-31 12:00:00-07:00>>>dt.tzname()'PDT'>>># Standard time>>>dt+=timedelta(days=7)>>>print(dt)2020-11-07 12:00:00-08:00>>>print(dt.tzname())PST
As a fall-back source of data for platforms that don't ship the IANA database,thetzdata module was released as a first-party package -- distributed viaPyPI and maintained by the CPython core team.
也參考
- PEP 615 -- Support for the IANA Time Zone Database in the Standard Library
由 Paul Ganssle 撰寫 PEP 與實作
graphlib¶
A new module,graphlib
, was added that contains thegraphlib.TopologicalSorter
class to offer functionality to performtopological sorting of graphs. (Contributed by Pablo Galindo, Tim Peters andLarry Hastings inbpo-17005.)
改進的模組¶
ast¶
Added theindent option todump()
which allows it to produce amultiline indented output.(Contributed by Serhiy Storchaka inbpo-37995.)
Addedast.unparse()
as a function in theast
module that canbe used to unparse anast.AST
object and produce a string with codethat would produce an equivalentast.AST
object when parsed.(Contributed by Pablo Galindo and Batuhan Taskaya inbpo-38870.)
Added docstrings to AST nodes that contains the ASDL signature used toconstruct that node. (Contributed by Batuhan Taskaya inbpo-39638.)
asyncio¶
Due to significant security concerns, thereuse_address parameter ofasyncio.loop.create_datagram_endpoint()
is no longer supported. This isbecause of the behavior of the socket optionSO_REUSEADDR
in UDP. For moredetails, see the documentation forloop.create_datagram_endpoint()
.(Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov inbpo-37228.)
Added a newcoroutineshutdown_default_executor()
that schedules a shutdown for the default executor that waits on theThreadPoolExecutor
to finish closing. Also,asyncio.run()
has been updated to use the newcoroutine.(Contributed by Kyle Stanley inbpo-34037.)
Addedasyncio.PidfdChildWatcher
, a Linux-specific child watcherimplementation that polls process file descriptors. (bpo-38692)
Added a newcoroutineasyncio.to_thread()
. It is mainly used forrunning IO-bound functions in a separate thread to avoid blocking the eventloop, and essentially works as a high-level version ofrun_in_executor()
that can directly take keyword arguments.(Contributed by Kyle Stanley and Yury Selivanov inbpo-32309.)
When cancelling the task due to a timeout,asyncio.wait_for()
will nowwait until the cancellation is complete also in the case whentimeout is<= 0, like it does with positive timeouts.(Contributed by Elvis Pranskevichus inbpo-32751.)
asyncio
now raisesTypeError
when calling incompatiblemethods with anssl.SSLSocket
socket.(Contributed by Ido Michael inbpo-37404.)
compileall¶
Added new possibility to use hardlinks for duplicated.pyc
files:hardlink_dupes parameter and --hardlink-dupes command line option.(Contributed by Lumír 'Frenzy' Balhar inbpo-40495.)
Added new options for path manipulation in resulting.pyc
files:stripdir,prependdir,limit_sl_dest parameters and -s, -p, -e command line options.Added the possibility to specify the option for an optimization level multiple times.(Contributed by Lumír 'Frenzy' Balhar inbpo-38112.)
concurrent.futures¶
Added a newcancel_futures parameter toconcurrent.futures.Executor.shutdown()
that cancels all pending futureswhich have not started running, instead of waiting for them to complete beforeshutting down the executor.(Contributed by Kyle Stanley inbpo-39349.)
Removed daemon threads fromThreadPoolExecutor
andProcessPoolExecutor
. This improvescompatibility with subinterpreters and predictability in their shutdownprocesses. (Contributed by Kyle Stanley inbpo-39812.)
Workers inProcessPoolExecutor
are now spawned ondemand, only when there are no available idle workers to reuse. This optimizesstartup overhead and reduces the amount of lost CPU time to idle workers.(Contributed by Kyle Stanley inbpo-39207.)
curses¶
Addedcurses.get_escdelay()
,curses.set_escdelay()
,curses.get_tabsize()
, andcurses.set_tabsize()
functions.(Contributed by Anthony Sottile inbpo-38312.)
datetime¶
Theisocalendar()
ofdatetime.date
andisocalendar()
ofdatetime.datetime
methods now returns anamedtuple()
instead of atuple
.(Contributed by Donghee Na inbpo-24416.)
distutils¶
Theupload command now creates SHA2-256 and Blake2b-256 hashdigests. It skips MD5 on platforms that block MD5 digest.(Contributed by Christian Heimes inbpo-40698.)
fcntl¶
Added constantsF_OFD_GETLK
,F_OFD_SETLK
andF_OFD_SETLKW
.(Contributed by Donghee Na inbpo-38602.)
ftplib¶
FTP
andFTP_TLS
now raise aValueError
if the given timeout for their constructor is zero to prevent the creation ofa non-blocking socket. (Contributed by Donghee Na inbpo-39259.)
gc¶
When the garbage collector makes a collection in which some objects resurrect(they are reachable from outside the isolated cycles after the finalizers havebeen executed), do not block the collection of all objects that are stillunreachable. (Contributed by Pablo Galindo and Tim Peters inbpo-38379.)
Added a new functiongc.is_finalized()
to check if an object has beenfinalized by the garbage collector. (Contributed by Pablo Galindo inbpo-39322.)
hashlib¶
Thehashlib
module can now use SHA3 hashes and SHAKE XOF from OpenSSLwhen available.(Contributed by Christian Heimes inbpo-37630.)
Builtin hash modules can now be disabled with./configure--without-builtin-hashlib-hashes
or selectively enabled withe.g../configure--with-builtin-hashlib-hashes=sha3,blake2
to force useof OpenSSL based implementation.(Contributed by Christian Heimes inbpo-40479)
http¶
HTTP status codes103EARLY_HINTS
,418IM_A_TEAPOT
and425TOO_EARLY
are added tohttp.HTTPStatus
. (Contributed by Donghee Na inbpo-39509 and Ross Rhodes inbpo-39507.)
IDLE and idlelib¶
Added option to toggle cursor blink off. (Contributed by Zackery Spytzinbpo-4603.)
Escape key now closes IDLE completion windows. (Contributed by JohnnyNajera inbpo-38944.)
Added keywords to module name completion list. (Contributed by Terry J.Reedy inbpo-37765.)
New in 3.9 maintenance releases
Make IDLE invokesys.excepthook()
(when started without '-n').User hooks were previously ignored. (Contributed by Ken Hilton inbpo-43008.)
The changes above have been backported to 3.8 maintenance releases.
Rearrange the settings dialog. Split the General tab into Windowsand Shell/Ed tabs. Move help sources, which extend the Help menu, to theExtensions tab. Make space for new options and shorten the dialog. Thelatter makes the dialog better fit small screens. (Contributed by Terry JanReedy inbpo-40468.) Move the indent space setting from the Font tab tothe new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy inbpo-33962.)
Apply syntax highlighting to.pyi
files. (Contributed by AlexWaygood and Terry Jan Reedy inbpo-45447.)
imaplib¶
IMAP4
andIMAP4_SSL
now havean optionaltimeout parameter for their constructors.Also, theopen()
method now has an optionaltimeout parameterwith this change. The overridden methods ofIMAP4_SSL
andIMAP4_stream
were applied to this change.(Contributed by Donghee Na inbpo-38615.)
imaplib.IMAP4.unselect()
is added.imaplib.IMAP4.unselect()
frees server's resources associated with theselected mailbox and returns the server to the authenticatedstate. This command performs the same actions asimaplib.IMAP4.close()
, exceptthat no messages are permanently removed from the currentlyselected mailbox. (Contributed by Donghee Na inbpo-40375.)
importlib¶
To improve consistency with import statements,importlib.util.resolve_name()
now raisesImportError
instead ofValueError
for invalid relativeimport attempts.(Contributed by Ngalim Siregar inbpo-37444.)
Import loaders which publish immutable module objects can now publishimmutable packages in addition to individual modules.(Contributed by Dino Viehland inbpo-39336.)
Addedimportlib.resources.files()
function with support forsubdirectories in package data, matching backport inimportlib_resources
version 1.5.(Contributed by Jason R. Coombs inbpo-39791.)
Refreshedimportlib.metadata
fromimportlib_metadata
version 1.6.1.
inspect¶
inspect.BoundArguments.arguments
is changed fromOrderedDict
to regulardict. (Contributed by Inada Naoki inbpo-36350 andbpo-39775.)
ipaddress¶
ipaddress
now supports IPv6 Scoped Addresses (IPv6 address with suffix%<scope_id>
).
Scoped IPv6 addresses can be parsed usingipaddress.IPv6Address
.If present, scope zone ID is available through thescope_id
attribute.(Contributed by Oleksandr Pavliuk inbpo-34788.)
Starting with Python 3.9.5 theipaddress
module no longeraccepts any leading zeros in IPv4 address strings.(Contributed by Christian Heimes inbpo-36384).
math¶
Expanded themath.gcd()
function to handle multiple arguments.Formerly, it only supported two arguments.(Contributed by Serhiy Storchaka inbpo-39648.)
Addedmath.lcm()
: return the least common multiple of specified arguments.(Contributed by Mark Dickinson, Ananthakrishnan and Serhiy Storchaka inbpo-39479 andbpo-39648.)
Addedmath.nextafter()
: return the next floating-point value afterxtowardsy.(Contributed by Victor Stinner inbpo-39288.)
Addedmath.ulp()
: return the value of the least significant bitof a float.(Contributed by Victor Stinner inbpo-39310.)
multiprocessing¶
Themultiprocessing.SimpleQueue
class has a newclose()
method to explicitly close thequeue.(Contributed by Victor Stinner inbpo-30966.)
nntplib¶
NNTP
andNNTP_SSL
now raise aValueError
if the given timeout for their constructor is zero to prevent the creation ofa non-blocking socket. (Contributed by Donghee Na inbpo-39259.)
os¶
AddedCLD_KILLED
andCLD_STOPPED
forsi_code
.(Contributed by Donghee Na inbpo-38493.)
Exposed the Linux-specificos.pidfd_open()
(bpo-38692) andos.P_PIDFD
(bpo-38713) for process management with filedescriptors.
Theos.unsetenv()
function is now also available on Windows.(Contributed by Victor Stinner inbpo-39413.)
Theos.putenv()
andos.unsetenv()
functions are now alwaysavailable.(Contributed by Victor Stinner inbpo-39395.)
Addedos.waitstatus_to_exitcode()
function:convert a wait status to an exit code.(Contributed by Victor Stinner inbpo-40094.)
pathlib¶
Addedpathlib.Path.readlink()
which acts similarly toos.readlink()
.(Contributed by Girts Folkmanis inbpo-30618)
pdb¶
On Windows nowPdb
supports~/.pdbrc
.(Contributed by Tim Hopper and Dan Lidral-Porter inbpo-20523.)
poplib¶
POP3
andPOP3_SSL
now raise aValueError
if the given timeout for their constructor is zero to prevent the creation ofa non-blocking socket. (Contributed by Donghee Na inbpo-39259.)
pprint¶
pprint
can now pretty-printtypes.SimpleNamespace
.(Contributed by Carl Bordum Hansen inbpo-37376.)
pydoc¶
The documentation string is now shown not only for class, function,method etc, but for any object that has its own__doc__
attribute.(Contributed by Serhiy Storchaka inbpo-40257.)
random¶
Added a newrandom.Random.randbytes
method: generate random bytes.(Contributed by Victor Stinner inbpo-40286.)
signal¶
Exposed the Linux-specificsignal.pidfd_send_signal()
for sending tosignals to a process using a file descriptor instead of a pid. (bpo-38712)
smtplib¶
SMTP
andSMTP_SSL
now raise aValueError
if the given timeout for their constructor is zero to prevent the creation ofa non-blocking socket. (Contributed by Donghee Na inbpo-39259.)
LMTP
constructor now has an optionaltimeout parameter.(Contributed by Donghee Na inbpo-39329.)
socket¶
Thesocket
module now exports theCAN_RAW_JOIN_FILTERS
constant on Linux 4.1 and greater.(Contributed by Stefan Tatschner and Zackery Spytz inbpo-25780.)
The socket module now supports theCAN_J1939
protocol onplatforms that support it. (Contributed by Karl Ding inbpo-40291.)
The socket module now has thesocket.send_fds()
andsocket.recv_fds()
functions. (Contributed by Joannah Nanjekye, ShinyaOkano and Victor Stinner inbpo-28724.)
time¶
On AIX,thread_time()
is now implemented withthread_cputime()
which has nanosecond resolution, rather thanclock_gettime(CLOCK_THREAD_CPUTIME_ID)
which has a resolution of 10 milliseconds.(Contributed by Batuhan Taskaya inbpo-40192)
sys¶
Added a newsys.platlibdir
attribute: name of the platform-specificlibrary directory. It is used to build the path of standard library and thepaths of installed extension modules. It is equal to"lib"
on mostplatforms. On Fedora and SuSE, it is equal to"lib64"
on 64-bit platforms.(Contributed by Jan Matějek, Matěj Cepl, Charalampos Stratakis and Victor Stinner inbpo-1294959.)
Previously,sys.stderr
was block-buffered when non-interactive. Nowstderr
defaults to always being line-buffered.(Contributed by Jendrik Seipp inbpo-13601.)
tracemalloc¶
Addedtracemalloc.reset_peak()
to set the peak size of traced memoryblocks to the current size, to measure the peak of specific pieces of code.(Contributed by Huon Wilson inbpo-40630.)
typing¶
PEP 593 introduced antyping.Annotated
type to decorate existingtypes with context-specific metadata and newinclude_extras
parameter totyping.get_type_hints()
to access the metadata at runtime. (Contributedby Till Varoquaux and Konstantin Kashin.)
unicodedata¶
The Unicode database has been updated to version 13.0.0. (bpo-39926).
venv¶
The activation scripts provided byvenv
now all specify their promptcustomization consistently by always using the value specified by__VENV_PROMPT__
. Previously some scripts unconditionally used__VENV_PROMPT__
, others only if it happened to be set (which was the defaultcase), and one used__VENV_NAME__
instead.(Contributed by Brett Cannon inbpo-37663.)
xml¶
White space characters within attributes are now preserved when serializingxml.etree.ElementTree
to XML file. EOLNs are no longer normalizedto "n". This is the result of discussion about how to interpretsection 2.11 of XML spec.(Contributed by Mefistotelis inbpo-39011.)
最佳化¶
Optimized the idiom for assignment a temporary variable in comprehensions.Now
foryin[expr]
in comprehensions is as fast as a simple assignmenty=expr
. For example:sums = [s for s in [0] for x in data for s in [s + x]]
Unlike the
:=
operator this idiom does not leak a variable to theouter scope.(由 Serhiy Storchaka 在bpo-32856 中貢獻。)
Optimized signal handling in multithreaded applications. If a thread differentthan the main thread gets a signal, the bytecode evaluation loop is no longerinterrupted at each bytecode instruction to check for pending signals whichcannot be handled. Only the main thread of the main interpreter can handlesignals.
Previously, the bytecode evaluation loop was interrupted at each instructionuntil the main thread handles signals.(Contributed by Victor Stinner inbpo-40010.)
Optimized the
subprocess
module on FreeBSD usingclosefrom()
.(Contributed by Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak and VictorStinner inbpo-38061.)PyLong_FromDouble()
is now up to 1.87x faster for values thatfit intolong.(Contributed by Sergey Fedoseev inbpo-37986.)A number of Python builtins (
range
,tuple
,set
,frozenset
,list
,dict
) are now sped up by usingPEP 590 vectorcall protocol.(Contributed by Donghee Na, Mark Shannon, Jeroen Demeyer and Petr Viktorin inbpo-37207.)Optimized
difference_update()
for the case when the other setis much larger than the base set.(Suggested by Evgeny Kapun with code contributed by Michele Orrù inbpo-8425.)Python's small object allocator (
obmalloc.c
) now allows (no more than)one empty arena to remain available for immediate reuse, without returningit to the OS. This prevents thrashing in simple loops where an arena couldbe created and destroyed anew on each iteration.(Contributed by Tim Peters inbpo-37257.)floor division of float operation now has a better performance. Alsothe message of
ZeroDivisionError
for this operation is updated.(Contributed by Donghee Na inbpo-39434.)Decoding short ASCII strings with UTF-8 and ascii codecs is now about15% faster. (Contributed by Inada Naoki inbpo-37348.)
Here's a summary of performance improvements from Python 3.4 through Python 3.9:
Python version 3.4 3.5 3.6 3.7 3.8 3.9-------------- --- --- --- --- --- ---Variable and attribute read access: read_local 7.1 7.1 5.4 5.1 3.9 3.9 read_nonlocal 7.1 8.1 5.8 5.4 4.4 4.5 read_global 15.5 19.0 14.3 13.6 7.6 7.8 read_builtin 21.1 21.6 18.5 19.0 7.5 7.8 read_classvar_from_class 25.6 26.5 20.7 19.5 18.4 17.9 read_classvar_from_instance 22.8 23.5 18.8 17.1 16.4 16.9 read_instancevar 32.4 33.1 28.0 26.3 25.4 25.3 read_instancevar_slots 27.8 31.3 20.8 20.8 20.2 20.5 read_namedtuple 73.8 57.5 45.0 46.8 18.4 18.7 read_boundmethod 37.6 37.9 29.6 26.9 27.7 41.1Variable and attribute write access: write_local 8.7 9.3 5.5 5.3 4.3 4.3 write_nonlocal 10.5 11.1 5.6 5.5 4.7 4.8 write_global 19.7 21.2 18.0 18.0 15.8 16.7 write_classvar 92.9 96.0 104.6 102.1 39.2 39.8 write_instancevar 44.6 45.8 40.0 38.9 35.5 37.4 write_instancevar_slots 35.6 36.1 27.3 26.6 25.7 25.8Data structure read access: read_list 24.2 24.5 20.8 20.8 19.0 19.5 read_deque 24.7 25.5 20.2 20.6 19.8 20.2 read_dict 24.3 25.7 22.3 23.0 21.0 22.4 read_strdict 22.6 24.3 19.5 21.2 18.9 21.5Data structure write access: write_list 27.1 28.5 22.5 21.6 20.0 20.0 write_deque 28.7 30.1 22.7 21.8 23.5 21.7 write_dict 31.4 33.3 29.3 29.2 24.7 25.4 write_strdict 28.4 29.9 27.5 25.2 23.1 24.5Stack (or queue) operations: list_append_pop 93.4 112.7 75.4 74.2 50.8 50.6 deque_append_pop 43.5 57.0 49.4 49.2 42.5 44.2 deque_append_popleft 43.7 57.3 49.7 49.7 42.8 46.4Timing loop: loop_overhead 0.5 0.6 0.4 0.3 0.3 0.3
These results were generated from the variable access benchmark script at:Tools/scripts/var_access_benchmark.py
. The benchmark script displays timingsin nanoseconds. The benchmarks were measured on anIntel® Core™ i7-4960HQ processorrunning the macOS 64-bit builds found atpython.org.
已棄用¶
The distutils
bdist_msi
command is now deprecated, usebdist_wheel
(wheel packages) instead.(Contributed by Hugo van Kemenade inbpo-39586.)Currently
math.factorial()
acceptsfloat
instances withnon-negative integer values (like5.0
). It raises aValueError
for non-integral and negative floats. It is now deprecated. In futurePython versions it will raise aTypeError
for all floats.(Contributed by Serhiy Storchaka inbpo-37315.)The
parser
andsymbol
modules are deprecated and will beremoved in future versions of Python. For the majority of use cases,users can leverage the Abstract Syntax Tree (AST) generation and compilationstage, using theast
module.The Public C API functions
PyParser_SimpleParseStringFlags()
,PyParser_SimpleParseStringFlagsFilename()
,PyParser_SimpleParseFileFlags()
andPyNode_Compile()
are deprecated and will be removed in Python 3.10 together with the old parser.Using
NotImplemented
in a boolean context has been deprecated,as it is almost exclusively the result of incorrect rich comparatorimplementations. It will be made aTypeError
in a future versionof Python.(Contributed by Josh Rosenberg inbpo-35712.)The
random
module currently accepts any hashable type as apossible seed value. Unfortunately, some of those types are notguaranteed to have a deterministic hash value. After Python 3.9,the module will restrict its seeds toNone
,int
,float
,str
,bytes
, andbytearray
.Opening the
GzipFile
file for writing without specifyingthemode argument is deprecated. In future Python versions it will alwaysbe opened for reading by default. Specify themode argument for openingit for writing and silencing a warning.(Contributed by Serhiy Storchaka inbpo-28286.)Deprecated the
split()
method of_tkinter.TkappType
infavour of thesplitlist()
method which has more consistent andpredictable behavior.(Contributed by Serhiy Storchaka inbpo-38371.)The explicit passing of coroutine objects to
asyncio.wait()
has beendeprecated and will be removed in version 3.11.(Contributed by Yury Selivanov and Kyle Stanley inbpo-34790.)binhex4 and hexbin4 standards are now deprecated. The
binhex
moduleand the followingbinascii
functions are now deprecated:b2a_hqx()
、a2b_hqx()
rlecode_hqx()
、rledecode_hqx()
(由 Victor Stinner 在bpo-39353 中貢獻。)
ast
classesslice
,Index
andExtSlice
are considered deprecatedand will be removed in future Python versions.value
itself should beused instead ofIndex(value)
.Tuple(slices,Load())
should beused instead ofExtSlice(slices)
.(Contributed by Serhiy Storchaka inbpo-34822.)ast
classesSuite
,Param
,AugLoad
andAugStore
are considered deprecated and will be removed in future Python versions.They were not generated by the parser and not accepted by the codegenerator in Python 3.(Contributed by Batuhan Taskaya inbpo-39639 andbpo-39969and Serhiy Storchaka inbpo-39988.)The
PyEval_InitThreads()
andPyEval_ThreadsInitialized()
functions are now deprecated and will be removed in Python 3.11. CallingPyEval_InitThreads()
now does nothing. TheGIL is initializedbyPy_Initialize()
since Python 3.7.(Contributed by Victor Stinner inbpo-39877.)Passing
None
as the first argument to theshlex.split()
functionhas been deprecated. (Contributed by Zackery Spytz inbpo-33262.)smtpd.MailmanProxy()
is now deprecated as it is unusable withoutan external module,mailman
. (Contributed by Samuel Colvin inbpo-35800.)The
lib2to3
module now emits aPendingDeprecationWarning
.Python 3.9 switched to a PEG parser (seePEP 617), and Python 3.10 mayinclude new language syntax that is not parsable by lib2to3's LL(1) parser.Thelib2to3
module may be removed from the standard library in a futurePython version. Consider third-party alternatives such asLibCST orparso.(Contributed by Carl Meyer inbpo-40360.)Therandom parameter of
random.shuffle()
has been deprecated.(Contributed by Raymond Hettinger inbpo-40465)
已移除¶
The erroneous version at
unittest.mock.__version__
has been removed.nntplib.NNTP
:xpath()
andxgtitle()
methods have been removed.These methods are deprecated since Python 3.3. Generally, these extensionsare not supported or not enabled by NNTP server administrators.Forxgtitle()
, please usenntplib.NNTP.descriptions()
ornntplib.NNTP.description()
instead.(Contributed by Donghee Na inbpo-39366.)array.array
:tostring()
andfromstring()
methods have beenremoved. They were aliases totobytes()
andfrombytes()
, deprecatedsince Python 3.2.(Contributed by Victor Stinner inbpo-38916.)The undocumented
sys.callstats()
function has been removed. Since Python3.7, it was deprecated and always returnedNone
. It required a specialbuild optionCALL_PROFILE
which was already removed in Python 3.7.(Contributed by Victor Stinner inbpo-37414.)The
sys.getcheckinterval()
andsys.setcheckinterval()
functions havebeen removed. They were deprecated since Python 3.2. Usesys.getswitchinterval()
andsys.setswitchinterval()
instead.(Contributed by Victor Stinner inbpo-37392.)The C function
PyImport_Cleanup()
has been removed. It was documented as:"Empty the module table. For internal use only."(Contributed by Victor Stinner inbpo-36710.)_dummy_thread
anddummy_threading
modules have been removed. Thesemodules were deprecated since Python 3.7 which requires threading support.(Contributed by Victor Stinner inbpo-37312.)aifc.openfp()
alias toaifc.open()
,sunau.openfp()
alias tosunau.open()
, andwave.openfp()
alias towave.open()
have beenremoved. They were deprecated since Python 3.7.(Contributed by Victor Stinner inbpo-37320.)The
isAlive()
method ofthreading.Thread
has been removed. It was deprecated since Python 3.8.Useis_alive()
instead.(Contributed by Donghee Na inbpo-37804.)Methods
getchildren()
andgetiterator()
of classesElementTree
andElement
in theElementTree
module have been removed. They were deprecated in Python 3.2.Useiter(x)
orlist(x)
instead ofx.getchildren()
andx.iter()
orlist(x.iter())
instead ofx.getiterator()
.(Contributed by Serhiy Storchaka inbpo-36543.)The old
plistlib
API has been removed, it was deprecated since Python3.4. Use theload()
,loads()
,dump()
, anddumps()
functions. Additionally, theuse_builtin_types parameter wasremoved, standardbytes
objects are always used instead.(Contributed by Jon Janzen inbpo-36409.)The C function
PyGen_NeedsFinalizing
has been removed. It was notdocumented, tested, or used anywhere within CPython after the implementationofPEP 442. Patch by Joannah Nanjekye.(Contributed by Joannah Nanjekye inbpo-15088)base64.encodestring()
andbase64.decodestring()
, aliases deprecatedsince Python 3.1, have been removed: usebase64.encodebytes()
andbase64.decodebytes()
instead.(Contributed by Victor Stinner inbpo-39351.)fractions.gcd()
function has been removed, it was deprecated since Python3.5 (bpo-22486): usemath.gcd()
instead.(Contributed by Victor Stinner inbpo-39350.)Thebuffering parameter of
bz2.BZ2File
has been removed. SincePython 3.0, it was ignored and using it emitted aDeprecationWarning
.Pass an open file object to control how the file is opened.(Contributed by Victor Stinner inbpo-39357.)Theencoding parameter of
json.loads()
has been removed.As of Python 3.1, it was deprecated and ignored; using it has emitted aDeprecationWarning
since Python 3.8.(Contributed by Inada Naoki inbpo-39377)with(awaitasyncio.lock):
andwith(yieldfromasyncio.lock):
statements arenot longer supported, useasyncwithlock
instead. The same is correct forasyncio.Condition
andasyncio.Semaphore
.(Contributed by Andrew Svetlov inbpo-34793.)The
sys.getcounts()
function, the-Xshowalloccount
command lineoption and theshow_alloc_count
field of the C structurePyConfig
have been removed. They required a special Python build bydefiningCOUNT_ALLOCS
macro.(Contributed by Victor Stinner inbpo-39489.)The
_field_types
attribute of thetyping.NamedTuple
classhas been removed. It was deprecated since Python 3.8. Usethe__annotations__
attribute instead.(Contributed by Serhiy Storchaka inbpo-40182.)The
symtable.SymbolTable.has_exec()
method has been removed. It wasdeprecated since 2006, and only returningFalse
when it's called.(Contributed by Batuhan Taskaya inbpo-40208)The
asyncio.Task.current_task()
andasyncio.Task.all_tasks()
have been removed. They were deprecated since Python 3.7 and you can useasyncio.current_task()
andasyncio.all_tasks()
instead.(Contributed by Rémi Lapeyre inbpo-40967)The
unescape()
method in thehtml.parser.HTMLParser
classhas been removed (it was deprecated since Python 3.4).html.unescape()
should be used for converting character references to the correspondingunicode characters.
移植至 Python 3.9¶
This section lists previously described changes and other bugfixesthat may require changes to your code.
Python API 的變更¶
__import__()
andimportlib.util.resolve_name()
now raiseImportError
where it previously raisedValueError
. Callerscatching the specific exception type and supporting both Python 3.9 andearlier versions will need to catch both usingexcept(ImportError,ValueError):
.The
venv
activation scripts no longer special-case when__VENV_PROMPT__
is set to""
.The
select.epoll.unregister()
method no longer ignores theEBADF
error.(Contributed by Victor Stinner inbpo-39239.)Thecompresslevel parameter of
bz2.BZ2File
became keyword-only,since thebuffering parameter has been removed.(Contributed by Victor Stinner inbpo-39357.)Simplified AST for subscription. Simple indices will be represented bytheir value, extended slices will be represented as tuples.
Index(value)
will return avalue
itself,ExtSlice(slices)
will returnTuple(slices,Load())
.(Contributed by Serhiy Storchaka inbpo-34822.)The
importlib
module now ignores thePYTHONCASEOK
environment variable when the-E
or-I
command lineoptions are being used.Theencoding parameter has been added to the classes
ftplib.FTP
andftplib.FTP_TLS
as a keyword-only parameter, and the default encodingis changed from Latin-1 to UTF-8 to followRFC 2640.asyncio.loop.shutdown_default_executor()
has been added toAbstractEventLoop
, meaning alternative event loops thatinherit from it should have this method defined.(Contributed by Kyle Stanley inbpo-34037.)The constant values of future flags in the
__future__
moduleis updated in order to prevent collision with compiler flags. PreviouslyPyCF_ALLOW_TOP_LEVEL_AWAIT
was clashing withCO_FUTURE_DIVISION
.(Contributed by Batuhan Taskaya inbpo-39562)array('u')
now useswchar_t
as C type instead ofPy_UNICODE
.This change doesn't affect to its behavior becausePy_UNICODE
is aliasofwchar_t
since Python 3.3.(Contributed by Inada Naoki inbpo-34538.)The
logging.getLogger()
API now returns the root logger when passedthe name'root'
, whereas previously it returned a non-root logger named'root'
. This could affect cases where user code explicitly wants anon-root logger named'root'
, or instantiates a logger usinglogging.getLogger(__name__)
in some top-level module called'root.py'
.(Contributed by Vinay Sajip inbpo-37742.)Division handling of
PurePath
now returnsNotImplemented
instead of raising aTypeError
when passed something other than aninstance ofstr
orPurePath
. This allows creatingcompatible classes that don't inherit from those mentioned types.(Contributed by Roger Aiudi inbpo-34775).Starting with Python 3.9.5 the
ipaddress
module no longeraccepts any leading zeros in IPv4 address strings. Leading zeros areambiguous and interpreted as octal notation by some libraries. For examplethe legacy functionsocket.inet_aton()
treats leading zeros as octalnotatation. glibc implementation of moderninet_pton()
doesnot accept any leading zeros.(Contributed by Christian Heimes inbpo-36384).codecs.lookup()
now normalizes the encoding name the same way asencodings.normalize_encoding()
, except thatcodecs.lookup()
alsoconverts the name to lower case. For example,"latex+latin1"
encodingname is now normalized to"latex_latin1"
.(Contributed by Jordon Xu inbpo-37751.)
C API 中的改動¶
Instances ofheap-allocated types (such as those created with
PyType_FromSpec()
and similar APIs) hold a reference to their typeobject since Python 3.8. As indicated in the "Changes in the C API" of Python3.8, for the vast majority of cases, there should be no side effect but fortypes that have a customtp_traverse
function,ensure that all customtp_traverse
functions of heap-allocated typesvisit the object's type.範例:
intfoo_traverse(foo_struct*self,visitprocvisit,void*arg){// Rest of the traverse function#if PY_VERSION_HEX >= 0x03090000// This was not needed before Python 3.9 (Python issue 35810 and 40217)Py_VISIT(Py_TYPE(self));#endif}
If your traverse function delegates to
tp_traverse
of its base class(or another type), ensure thatPy_TYPE(self)
is visited only once.Note that onlyheap type are expected to visit the typeintp_traverse
.For example, if your
tp_traverse
function includes:base->tp_traverse(self,visit,arg)
then add:
#if PY_VERSION_HEX >= 0x03090000// This was not needed before Python 3.9 (bpo-35810 and bpo-40217)if(base->tp_flags&Py_TPFLAGS_HEAPTYPE){// a heap type's tp_traverse already visited Py_TYPE(self)}else{Py_VISIT(Py_TYPE(self));}#else
The functions
PyEval_CallObject
,PyEval_CallFunction
,PyEval_CallMethod
andPyEval_CallObjectWithKeywords
are deprecated.UsePyObject_Call()
and its variants instead.(See more details inbpo-29548.)
CPython 位元組碼變更¶
The
LOAD_ASSERTION_ERROR
opcode was added for handling theassert
statement. Previously, the assert statement would not workcorrectly if theAssertionError
exception was being shadowed.(Contributed by Zackery Spytz inbpo-34880.)The
COMPARE_OP
opcode was split into four distinct instructions:COMPARE_OP
for rich comparisonsIS_OP
for 'is' and 'is not' testsCONTAINS_OP
for 'in' and 'not in' testsJUMP_IF_NOT_EXC_MATCH
for checking exceptions in 'try-except'statements.
(由 Mark Shannon 在bpo-39156 中貢獻。)
建置變更¶
Added
--with-platlibdir
option to theconfigure
script: name of theplatform-specific library directory, stored in the newsys.platlibdir
attribute. Seesys.platlibdir
attribute for more information.(Contributed by Jan Matějek, Matěj Cepl, Charalampos Stratakisand Victor Stinner inbpo-1294959.)The
COUNT_ALLOCS
special build macro has been removed.(Contributed by Victor Stinner inbpo-39489.)On non-Windows platforms, the
setenv()
andunsetenv()
functions are now required to build Python.(Contributed by Victor Stinner inbpo-39395.)On non-Windows platforms, creating
bdist_wininst
installers is nowofficially unsupported. (Seebpo-10945 for more details.)When building Python on macOS from source,
_tkinter
now links withnon-system Tcl and Tk frameworks if they are installed in/Library/Frameworks
, as had been the case on older releasesof macOS. If a macOS SDK is explicitly configured, by using--enable-universalsdk
or-isysroot
, only the SDK itself issearched. The default behavior can still be overridden with--with-tcltk-includes
and--with-tcltk-libs
.(Contributed by Ned Deily inbpo-34956.)Python can now be built for Windows 10 ARM64.(Contributed by Steve Dower inbpo-33125.)
Some individual tests are now skipped when
--pgo
is used. The testsin question increased the PGO task time significantly and likelydidn't help improve optimization of the final executable. Thisspeeds up the task by a factor of about 15x. Running the full unit testsuite is slow. This change may result in a slightly less optimized buildsince not as many code branches will be executed. If you are willing towait for the much slower build, the old behavior can be restored using./configure[..]PROFILE_TASK="-mtest--pgo-extended"
. We make noguarantees as to which PGO task set produces a faster build. Users who careshould run their own relevant benchmarks as results can depend on theenvironment, workload, and compiler tool chain.(Seebpo-36044 andbpo-37707 for more details.)
C API 變更¶
新增功能¶
PEP 573: Added
PyType_FromModuleAndSpec()
to associatea module with a class;PyType_GetModule()
andPyType_GetModuleState()
to retrieve the module and its state; andPyCMethod
andMETH_METHOD
to allow a method toaccess the class it was defined in.(Contributed by Marcel Plch and Petr Viktorin inbpo-38787.)Added
PyFrame_GetCode()
function: get a frame code.AddedPyFrame_GetBack()
function: get the frame next outer frame.(Contributed by Victor Stinner inbpo-40421.)Added
PyFrame_GetLineNumber()
to the limited C API.(Contributed by Victor Stinner inbpo-40421.)Added
PyThreadState_GetInterpreter()
andPyInterpreterState_Get()
functions to get the interpreter.AddedPyThreadState_GetFrame()
function to get the current frame of aPython thread state.AddedPyThreadState_GetID()
function: get the unique identifier of aPython thread state.(Contributed by Victor Stinner inbpo-39947.)Added a new public
PyObject_CallNoArgs()
function to the C API, whichcalls a callable Python object without any arguments. It is the most efficientway to call a callable Python object without any argument.(Contributed by Victor Stinner inbpo-37194.)Changes in the limited C API (if
Py_LIMITED_API
macro is defined):Provide
Py_EnterRecursiveCall()
andPy_LeaveRecursiveCall()
as regular functions for the limited API. Previously, there were defined asmacros, but these macros didn't compile with the limited C API which cannotaccessPyThreadState.recursion_depth
field (the structure is opaque inthe limited C API).PyObject_INIT()
andPyObject_INIT_VAR()
become regular "opaque"function to hide implementation details.
(由 Victor Stinner 在 38644 和 39542 中貢獻。)
The
PyModule_AddType()
function is added to help adding a typeto a module.(Contributed by Donghee Na inbpo-40024.)Added the functions
PyObject_GC_IsTracked()
andPyObject_GC_IsFinalized()
to the public API to allow to query ifPython objects are being currently tracked or have been already finalized bythe garbage collector respectively.(Contributed by Pablo Galindo Salgado inbpo-40241.)Added
_PyObject_FunctionStr()
to get a user-friendly stringrepresentation of a function-like object.(Patch by Jeroen Demeyer inbpo-37645.)Added
PyObject_CallOneArg()
for calling an object with onepositional argument(Patch by Jeroen Demeyer inbpo-37483.)
移植至 Python 3.9¶
PyInterpreterState.eval_frame
(PEP 523) now requires a new mandatorytstate parameter (PyThreadState*
).(Contributed by Victor Stinner inbpo-38500.)Extension modules:
m_traverse
,m_clear
andm_free
functions ofPyModuleDef
are no longer called if the module statewas requested but is not allocated yet. This is the case immediately afterthe module is created and before the module is executed(Py_mod_exec
function). More precisely, these functions are not calledifm_size
is greater than 0 and the module state (asreturned byPyModule_GetState()
) isNULL
.Extension modules without module state (
m_size<=0
) are not affected.If
Py_AddPendingCall()
is called in a subinterpreter, the function isnow scheduled to be called from the subinterpreter, rather than being calledfrom the main interpreter. Each subinterpreter now has its own list ofscheduled calls.(Contributed by Victor Stinner inbpo-39984.)The Windows registry is no longer used to initialize
sys.path
whenthe-E
option is used (ifPyConfig.use_environment
is set to0
). This is significant when embedding Python on Windows.(Contributed by Zackery Spytz inbpo-8901.)The global variable
PyStructSequence_UnnamedField
is now a constantand refers to a constant string.(Contributed by Serhiy Storchaka inbpo-38650.)The
PyGC_Head
structure is now opaque. It is only defined in theinternal C API (pycore_gc.h
).(Contributed by Victor Stinner inbpo-40241.)The
Py_UNICODE_COPY
,Py_UNICODE_FILL
,PyUnicode_WSTR_LENGTH
,PyUnicode_FromUnicode()
,PyUnicode_AsUnicode()
,_PyUnicode_AsUnicode
, andPyUnicode_AsUnicodeAndSize()
aremarked as deprecated in C. They have been deprecated byPEP 393 sincePython 3.3.(Contributed by Inada Naoki inbpo-36346.)The
Py_FatalError()
function is replaced with a macro which logsautomatically the name of the current function, unless thePy_LIMITED_API
macro is defined.(Contributed by Victor Stinner inbpo-39882.)The vectorcall protocol now requires that the caller passes only strings askeyword names. (Seebpo-37540 for more information.)
Implementation details of a number of macros and functions are now hidden:
PyObject_IS_GC()
macro was converted to a function.The
PyObject_NEW()
macro becomes an alias to thePyObject_New
macro, and thePyObject_NEW_VAR()
macrobecomes an alias to thePyObject_NewVar
macro. They no longeraccess directly thePyTypeObject.tp_basicsize
member.PyObject_GET_WEAKREFS_LISTPTR()
macro was converted to a function:the macro accessed directly thePyTypeObject.tp_weaklistoffset
member.PyObject_CheckBuffer()
macro was converted to a function: the macroaccessed directly thePyTypeObject.tp_as_buffer
member.PyIndex_Check()
is now always declared as an opaque function to hideimplementation details: removed thePyIndex_Check()
macro. The macro accesseddirectly thePyTypeObject.tp_as_number
member.
(更多資訊請見bpo-40170。)
已移除¶
Excluded
PyFPE_START_PROTECT()
andPyFPE_END_PROTECT()
macros ofpyfpe.h
from the limited C API.(Contributed by Victor Stinner inbpo-38835.)The
tp_print
slot ofPyTypeObject has been removed.It was used for printing objects to files in Python 2.7 and before. SincePython 3.0, it has been ignored and unused.(Contributed by Jeroen Demeyer inbpo-36974.)Changes in the limited C API (if
Py_LIMITED_API
macro is defined):Excluded the following functions from the limited C API:
PyThreadState_DeleteCurrent()
(Contributed by Joannah Nanjekye inbpo-37878.)_Py_CheckRecursionLimit
_Py_NewReference()
_Py_ForgetReference()
_PyTraceMalloc_NewReference()
_Py_GetRefTotal()
The trashcan mechanism which never worked in the limited C API.
PyTrash_UNWIND_LEVEL
Py_TRASHCAN_BEGIN_CONDITION
Py_TRASHCAN_BEGIN
Py_TRASHCAN_END
Py_TRASHCAN_SAFE_BEGIN
Py_TRASHCAN_SAFE_END
Moved following functions and definitions to the internal C API:
_PyDebug_PrintTotalRefs()
_Py_PrintReferences()
_Py_PrintReferenceAddresses()
_Py_tracemalloc_config
_Py_AddToAllObjects()
(specific toPy_TRACE_REFS
build)
(由 Victor Stinner 在 38644 和 39542 中貢獻。)
Removed
_PyRuntime.getframe
hook and removed_PyThreadState_GetFrame
macro which was an alias to_PyRuntime.getframe
. They were only exposedby the internal C API. Removed alsoPyThreadFrameGetter
type.(Contributed by Victor Stinner inbpo-39946.)Removed the following functions from the C API. Call
PyGC_Collect()
explicitly to clear all free lists.(Contributed by Inada Naoki and Victor Stinner inbpo-37340,bpo-38896 andbpo-40428.)PyAsyncGen_ClearFreeLists()
PyContext_ClearFreeList()
PyDict_ClearFreeList()
PyFloat_ClearFreeList()
PyFrame_ClearFreeList()
PyList_ClearFreeList()
PyMethod_ClearFreeList()
andPyCFunction_ClearFreeList()
:the free lists of bound method objects have been removed.PySet_ClearFreeList()
: the set free list has been removedin Python 3.4.PyTuple_ClearFreeList()
PyUnicode_ClearFreeList()
: the Unicode free list has been removed inPython 3.3.
Removed
_PyUnicode_ClearStaticStrings()
function.(Contributed by Victor Stinner inbpo-39465.)Removed
Py_UNICODE_MATCH
. It has been deprecated byPEP 393, andbroken since Python 3.3. ThePyUnicode_Tailmatch()
function can beused instead.(Contributed by Inada Naoki inbpo-36346.)Cleaned header files of interfaces defined but with no implementation.The public API symbols being removed are:
_PyBytes_InsertThousandsGroupingLocale
,_PyBytes_InsertThousandsGrouping
,_Py_InitializeFromArgs
,_Py_InitializeFromWideArgs
,_PyFloat_Repr
,_PyFloat_Digits
,_PyFloat_DigitsInit
,PyFrame_ExtendStack
,_PyAIterWrapper_Type
,PyNullImporter_Type
,PyCmpWrapper_Type
,PySortWrapper_Type
,PyNoArgsFunction
.(Contributed by Pablo Galindo Salgado inbpo-39372.)
Python 3.9.1 中顯著的變更¶
typing¶
The behavior oftyping.Literal
was changed to conform withPEP 586and to match the behavior of static type checkers specified in the PEP.
Literal
now de-duplicates parameters.Equality comparisons between
Literal
objects are now order independent.Literal
comparisons now respect types. For example,Literal[0]==Literal[False]
previously evaluated toTrue
. It isnowFalse
. To support this change, the internally used type cache nowsupports differentiating types.Literal
objects will now raise aTypeError
exception duringequality comparisons if any of their parameters are nothashable.Note that declaringLiteral
with mutable parameters will not throwan error:>>>fromtypingimportLiteral>>>Literal[{0}]>>>Literal[{0}]==Literal[{False}]Traceback (most recent call last): File"<stdin>", line1, in<module>TypeError:unhashable type: 'set'
(由 Yurii Karabas 在bpo-42345 中貢獻。)
macOS 11.0 (Big Sur) and Apple Silicon Mac support¶
As of 3.9.1, Python now fully supports building and running on macOS 11.0(Big Sur) and on Apple Silicon Macs (based on theARM64
architecture).A new universal build variant,universal2
, is now available to nativelysupport bothARM64
andIntel64
in one set of executables. Binariescan also now be built on current versions of macOS to be deployed on a rangeof older macOS versions (tested to 10.9) while making some newer OSfunctions and options conditionally available based on the operating systemversion in use at runtime ("weaklinking").
(由 Ronald Oussoren 和 Lawrence D'Anna 在bpo-41100 中貢獻。)
Python 3.9.2 中顯著的變更¶
collections.abc¶
collections.abc.Callable
generic now flattens type parameters, similarto whattyping.Callable
currently does. This means thatcollections.abc.Callable[[int,str],str]
will have__args__
of(int,str,str)
; previously this was([int,str],str)
. To allow thischange,types.GenericAlias
can now be subclassed, and a subclass willbe returned when subscripting thecollections.abc.Callable
type.Code which accesses the arguments viatyping.get_args()
or__args__
need to account for this change. ADeprecationWarning
may be emitted forinvalid forms of parameterizingcollections.abc.Callable
which may havepassed silently in Python 3.9.1. ThisDeprecationWarning
willbecome aTypeError
in Python 3.10.(Contributed by Ken Jin inbpo-42195.)
urllib.parse¶
Earlier Python versions allowed using both;
and&
asquery parameter separators inurllib.parse.parse_qs()
andurllib.parse.parse_qsl()
. Due to security concerns, and to conform withnewer W3C recommendations, this has been changed to allow only a singleseparator key, with&
as the default. This change also affectscgi.parse()
andcgi.parse_multipart()
as they use the affectedfunctions internally. For more details, please see their respectivedocumentation.(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin inbpo-42967.)
Python 3.9.3 中顯著的變更¶
A security fix alters theftplib.FTP
behavior to not trust theIPv4 address sent from the remote server when setting up a passive datachannel. We reuse the ftp server IP address instead. For unusual coderequiring the old behavior, set atrust_server_pasv_ipv4_address
attribute on your FTP instance toTrue
. (Seegh-87451)
Python 3.9.5 中顯著的變更¶
urllib.parse¶
The presence of newline or tab characters in parts of a URL allows for someforms of attacks. Following the WHATWG specification that updatesRFC 3986,ASCII newline\n
,\r
and tab\t
characters are stripped from theURL by the parser inurllib.parse
preventing such attacks. The removalcharacters are controlled by a new module level variableurllib.parse._UNSAFE_URL_BYTES_TO_REMOVE
. (Seegh-88048)
Notable security feature in 3.9.14¶
Converting betweenint
andstr
in bases other than 2(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)now raises aValueError
if the number of digits in string form isabove a limit to avoid potential denial of service attacks due to thealgorithmic complexity. This is a mitigation forCVE 2020-10735.This limit can be configured or disabled by environment variable, commandline flag, orsys
APIs. See theinteger string conversionlength limitation documentation. The default limitis 4300 digits in string form.
Notable changes in 3.9.17¶
tarfile¶
The extraction methods in
tarfile
, andshutil.unpack_archive()
,have a new afilter argument that allows limiting tar features than may besurprising or dangerous, such as creating files outside the destinationdirectory.SeeExtraction filters for details.In Python 3.12, use without thefilter argument will show aDeprecationWarning
.In Python 3.14, the default will switch to'data'
.(Contributed by Petr Viktorin inPEP 706.)