Whatsnew
- What's New in Python 2.0
- What's New in Python 2.1
- What's New in Python 2.2
- What's New in Python 2.3
- What's New in Python 2.4
- What's New in Python 2.5
- What's New in Python 2.6
- What's New in Python 2.7
- What's New In Python 3.0
- What's New In Python 3.1
- What's New In Python 3.10
- What's New In Python 3.11
- What's New In Python 3.12
- What's New In Python 3.13
- What's new in Python 3.14
- What's new in Python 3.15
- What's new in Python 3.16
- What's New In Python 3.2
- What's New In Python 3.3
- What's New In Python 3.4
- What's New In Python 3.5
- What's New In Python 3.6
- What's New In Python 3.7
- What's New In Python 3.8
- What's New In Python 3.9
- changelog
- What's New in Python
What's New in Python 2.0
Introduction
A new release of Python, version 2.0, was released on October 16, 2000. This article covers the exciting new features in 2.0, highlights some other useful changes, and points out a few incompatible changes that may require rewriting code.
Python's development never completely stops between releases, and a steady flow of bug fixes and improvements are always being submitted. A host of minor fixes, a few optimizations, additional docstrings, and better error messages went into 2.0; to list them all would be impossible, but they're certainly significant. Consult the publicly available CVS logs if you want to see the full list. This progress is due to the five developers working for PythonLabs are now getting paid to spend their days fixing bugs, and also due to the improved communication resulting from moving to SourceForge.
What About Python 1.6?
Python 1.6 can be thought of as the Contractual Obligations Python release. After the core development team left CNRI in May 2000, CNRI requested that a 1.6 release be created, containing all the work on Python that had been performed at CNRI. Python 1.6 therefore represents the state of the CVS tree as of May 2000, with the most significant new feature being Unicode support. Development continued after May, of course, so the 1.6 tree received a few fixes to ensure that it's forward-compatible with Python 2.0. 1.6 is therefore part of Python's evolution, and not a side branch.
So, should you take much interest in Python 1.6? Probably not. The 1.6final and 2.0beta1 releases were made on the same day (September 5, 2000), the plan being to finalize Python 2.0 within a month or so. If you have applications to maintain, there seems little point in breaking things by moving to 1.6, fixing them, and then having another round of breakage within a month by moving to 2.0; you're better off just going straight to 2.0. Most of the really interesting features described in this document are only in 2.0, because a lot of work was done between May and September.
New Development Process
The most important change in Python 2.0 may not be to the code at all, but to how Python is developed: in May 2000 the Python developers began using the tools made available by SourceForge for storing source code, tracking bug reports, and managing the queue of patch submissions. To report bugs or submit patches for Python 2.0, use the bug tracking and patch manager tools available from Python's project page, located at https://sourceforge.net/projects/python/.
The most important of the services now hosted at SourceForge is the Python CVS tree, the version-controlled repository containing the source code for Python. Previously, there were roughly 7 or so people who had write access to the CVS tree, and all patches had to be inspected and checked in by one of the people on this short list. Obviously, this wasn't very scalable. By moving the CVS tree to SourceForge, it became possible to grant write access to more people; as of September 2000 there were 27 people able to check in changes, a fourfold increase. This makes possible large-scale changes that wouldn't be attempted if they'd have to be filtered through the small group of core developers. For example, one day Peter Schneider-Kamp took it into his head to drop K&R C compatibility and convert the C source for Python to ANSI C. After getting approval on the python-dev mailing list, he launched into a flurry of checkins that lasted about a week, other developers joined in to help, and the job was done. If there were only 5 people with write access, probably that task would have been viewed as "nice, but not worth the time and effort needed" and it would never have gotten done.
The shift to using SourceForge's services has resulted in a remarkable increase in the speed of development. Patches now get submitted, commented on, revised by people other than the original submitter, and bounced back and forth between people until the patch is deemed worth checking in. Bugs are tracked in one central location and can be assigned to a specific person for fixing, and we can count the number of open bugs to measure progress. This didn't come without a cost: developers now have more e-mail to deal with, more mailing lists to follow, and special tools had to be written for the new environment. For example, SourceForge sends default patch and bug notification e-mail messages that are completely unhelpful, so Ka-Ping Yee wrote an HTML screen-scraper that sends more useful messages.
The ease of adding code caused a few initial growing pains, such as code was checked in before it was ready or without getting clear agreement from the developer group. The approval process that has emerged is somewhat similar to that used by the Apache group. Developers can vote +1, +0, -0, or -1 on a patch; +1 and -1 denote acceptance or rejection, while +0 and -0 mean the developer is mostly indifferent to the change, though with a slight positive or negative slant. The most significant change from the Apache model is that the voting is essentially advisory, letting Guido van Rossum, who has Benevolent Dictator For Life status, know what the general opinion is. He can still ignore the result of a vote, and approve or reject a change even if the community disagrees with him.
Producing an actual patch is the last step in adding a new feature, and is usually easy compared to the earlier task of coming up with a good design. Discussions of new features can often explode into lengthy mailing list threads, making the discussion hard to follow, and no one can read every posting to python-dev. Therefore, a relatively formal process has been set up to write Python Enhancement Proposals (PEPs), modelled on the internet RFC process. PEPs are draft documents that describe a proposed new feature, and are continually revised until the community reaches a consensus, either accepting or rejecting the proposal. Quoting from the introduction to 1, "PEP Purpose and Guidelines":
PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python. The PEP should provide a concise technical specification of the feature and a rationale for the feature.
We intend PEPs to be the primary mechanisms for proposing new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions.
Read the rest of 1 for the details of the PEP editorial process, style, and format. PEPs are kept in the Python CVS tree on SourceForge, though they're not part of the Python 2.0 distribution, and are also available in HTML form from https://peps.python.org/. As of September 2000, there are 25 PEPs, ranging from 201, "Lockstep Iteration", to PEP 225, "Elementwise/Objectwise Operators".
Unicode
The largest new feature in Python 2.0 is a new fundamental data type: Unicode strings. Unicode uses 16-bit numbers to represent characters instead of the 8-bit number used by ASCII, meaning that 65,536 distinct characters can be supported.
The final interface for Unicode support was arrived at through countless often-stormy discussions on the python-dev mailing list, and mostly implemented by Marc-André Lemburg, based on a Unicode string type implementation by Fredrik Lundh. A detailed explanation of the interface was written up as 100, "Python Unicode Integration". This article will simply cover the most significant points about the Unicode interfaces.
In Python source code, Unicode strings are written as u"string". Arbitrary Unicode characters can be written using a new escape sequence, \\u{HHHH}, where HHHH is a 4-digit hexadecimal number from 0000 to FFFF. The existing \\x{HH} escape sequence can also be used, and octal escapes can be used for characters up to U+01FF, which is represented by \777.
Unicode strings, just like regular strings, are an immutable sequence type. They can be indexed and sliced, but not modified in place. Unicode strings have an encode( [encoding] ) method that returns an 8-bit string in the desired encoding. Encodings are named by strings, such as 'ascii', 'utf-8', 'iso-8859-1', or whatever. A codec API is defined for implementing and registering new encodings that are then available throughout a Python program. If an encoding isn't specified, the default encoding is usually 7-bit ASCII, though it can be changed for your Python installation by calling the sys.setdefaultencoding(encoding) function in a customized version of site.py.
Combining 8-bit and Unicode strings always coerces to Unicode, using the default ASCII encoding; the result of 'a' + u'bc' is u'abc'.
New built-in functions have been added, and existing built-ins modified to support Unicode:
unichr(ch)returns a Unicode string 1 character long, containing the character ch.ord(u), where u is a 1-character regular or Unicode string, returns the number of the character as an integer.unicode(string [, encoding] [, errors] )creates a Unicode string from an 8-bit string.encodingis a string naming the encoding to use. Theerrorsparameter specifies the treatment of characters that are invalid for the current encoding; passing'strict'as the value causes an exception to be raised on any encoding error, while'ignore'causes errors to be silently ignored and'replace'uses U+FFFD, the official replacement character, in case of any problems.- The
execstatement, and various built-ins such aseval(),getattr(), andsetattr()will also accept Unicode strings as well as regular strings. (It's possible that the process of fixing this missed some built-ins; if you find a built-in function that accepts strings but doesn't accept Unicode strings at all, please report it as a bug.)
A new module, unicodedata, provides an interface to Unicode character properties. For example, unicodedata.category(u'A') returns the 2-character string 'Lu', the 'L' denoting it's a letter, and 'u' meaning that it's uppercase. unicodedata.bidirectional(u'\u0660') returns 'AN', meaning that U+0660 is an Arabic number.
The codecs module contains functions to look up existing encodings and register new ones. Unless you want to implement a new encoding, you'll most often use the codecs.lookup(encoding) function, which returns a 4-element tuple: (encode_func, decode_func, stream_reader, stream_writer).
- encode_func is a function that takes a Unicode string, and returns a 2-tuple
(string, length). string is an 8-bit string containing a portion (perhaps all) of the Unicode string converted into the given encoding, and length tells you how much of the Unicode string was converted. - decode_func is the opposite of encode_func, taking an 8-bit string and returning a 2-tuple
(ustring, length), consisting of the resulting Unicode string ustring and the integer length telling how much of the 8-bit string was consumed. - stream_reader is a class that supports decoding input from a stream. stream_reader(file_obj) returns an object that supports the
!read,!readline, and!readlinesmethods. These methods will all translate from the given encoding and return Unicode strings. - stream_writer, similarly, is a class that supports encoding output to a stream. stream_writer(file_obj) returns an object that supports the
!writeand!writelinesmethods. These methods expect Unicode strings, translating them to the given encoding on output.
For example, the following code writes a Unicode string into a file, encoding it as UTF-8:
import codecs
unistr = u'\u0660\u2000ab ...'
(UTF8_encode, UTF8_decode,
UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')
output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
output.write( unistr )
output.close()
The following code would then read UTF-8 input from the file:
input = UTF8_streamreader( open( '/tmp/output', 'rb') )
print repr(input.read())
input.close()
Unicode-aware regular expressions are available through the re module, which has a new underlying implementation called SRE written by Fredrik Lundh of Secret Labs AB.
A -U command line option was added which causes the Python compiler to interpret all string literals as Unicode string literals. This is intended to be used in testing and future-proofing your Python code, since some future version of Python may drop support for 8-bit strings and provide only Unicode strings.
List Comprehensions
Lists are a workhorse data type in Python, and many programs manipulate a list at some point. Two common operations on lists are to loop over them, and either pick out the elements that meet a certain criterion, or apply some function to each element. For example, given a list of strings, you might want to pull out all the strings containing a given substring, or strip off trailing whitespace from each line.
The existing map and filter functions can be used for this purpose, but they require a function as one of their arguments. This is fine if there's an existing built-in function that can be passed directly, but if there isn't, you have to create a little function to do the required work, and Python's scoping rules make the result ugly if the little function needs additional information. Take the first example in the previous paragraph, finding all the strings in the list containing a given substring. You could write the following to do it:
# Given the list L, make a list of all strings
# containing the substring S.
sublist = filter( lambda s, substring=S:
string.find(s, substring) != -1,
L)
Because of Python's scoping rules, a default argument is used so that the anonymous function created by the lambda expression knows what substring is being searched for. List comprehensions make this cleaner:
sublist = [ s for s in L if string.find(s, S) != -1 ]
List comprehensions have the form:
[ expression for expr in sequence1
for expr2 in sequence2 ...
for exprN in sequenceN
if condition ]
The !for...!in clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are not iterated over in parallel, but from left to right; this is explained more clearly in the following paragraphs. The elements of the generated list will be the successive values of expression. The final !if clause is optional; if present, expression is only evaluated and added to the result if condition is true.
To make the semantics very clear, a list comprehension is equivalent to the following Python code:
for expr1 in sequence1:
for expr2 in sequence2:
...
for exprN in sequenceN:
if (condition):
# Append the value of
# the expression to the
# resulting list.
This means that when there are multiple !for...!in clauses, the resulting list will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long:
seq1 = 'abc'
seq2 = (1,2,3)
>>> [ (x,y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
('c', 2), ('c', 3)]
To avoid introducing an ambiguity into Python's grammar, if expression is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct:
# Syntax error
[ x,y for x in seq1 for y in seq2]
# Correct
[ (x,y) for x in seq1 for y in seq2]
The idea of list comprehensions originally comes from the functional programming language Haskell (https://www.haskell.org). Greg Ewing argued most effectively for adding them to Python and wrote the initial list comprehension patch, which was then discussed for a seemingly endless time on the python-dev mailing list and kept up-to-date by Skip Montanaro.
Augmented Assignment
Augmented assignment operators, another long-requested feature, have been added to Python 2.0. Augmented assignment operators include +=, -=, *=, and so forth. For example, the statement a += 2 increments the value of the variable a by 2, equivalent to the slightly lengthier a = a + 2.
The full list of supported assignment operators is +=, -=, *=, /=, %=, **=, &=, |=, ^=, >>=, and <<=. Python classes can override the augmented assignment operators by defining methods named !__iadd__, !__isub__, etc. For example, the following !Number class stores a number and supports using += to create a new instance with an incremented value.
class Number:
def __init__(self, value):
self.value = value
def __iadd__(self, increment):
return Number( self.value + increment)
n = Number(5)
n += 3
print n.value
The !__iadd__ special method is called with the value of the increment, and should return a new instance with an appropriately modified value; this return value is bound as the new value of the variable on the left-hand side.
Augmented assignment operators were first introduced in the C programming language, and most C-derived languages, such as awk, C++, Java, Perl, and PHP also support them. The augmented assignment patch was implemented by Thomas Wouters.
String Methods
Until now string-manipulation functionality was in the string module, which was usually a front-end for the !strop module written in C. The addition of Unicode posed a difficulty for the !strop module, because the functions would all need to be rewritten in order to accept either 8-bit or Unicode strings. For functions such as !string.replace, which takes 3 string arguments, that means eight possible permutations, and correspondingly complicated code.
Instead, Python 2.0 pushes the problem onto the string type, making string manipulation functionality available through methods on both 8-bit strings and Unicode strings. :
>>> 'andrew'.capitalize()
'Andrew'
>>> 'hostname'.replace('os', 'linux')
'hlinuxtname'
>>> 'moshe'.find('sh')
2
One thing that hasn't changed, a noteworthy April Fools' joke notwithstanding, is that Python strings are immutable. Thus, the string methods return new strings, and do not modify the string on which they operate.
The old string module is still around for backwards compatibility, but it mostly acts as a front-end to the new string methods.
Two methods which have no parallel in pre-2.0 versions, although they did exist in JPython for quite some time, are !startswith and !endswith. s.startswith(t) is equivalent to s[:len(t)] == t, while s.endswith(t) is equivalent to s[-len(t):] == t.
One other method which deserves special mention is !join. The !join method of a string receives one parameter, a sequence of strings, and is equivalent to the !string.join function from the old string module, with the arguments reversed. In other words, s.join(seq) is equivalent to the old string.join(seq, s).
Garbage Collection of Cycles
The C implementation of Python uses reference counting to implement garbage collection. Every Python object maintains a count of the number of references pointing to itself, and adjusts the count as references are created or destroyed. Once the reference count reaches zero, the object is no longer accessible, since you need to have a reference to an object to access it, and if the count is zero, no references exist any longer.
Reference counting has some pleasant properties: it's easy to understand and implement, and the resulting implementation is portable, fairly fast, and reacts well with other libraries that implement their own memory handling schemes. The major problem with reference counting is that it sometimes doesn't realise that objects are no longer accessible, resulting in a memory leak. This happens when there are cycles of references.
Consider the simplest possible cycle, a class instance which has a reference to itself:
instance = SomeClass()
instance.myself = instance
After the above two lines of code have been executed, the reference count of instance is 2; one reference is from the variable named 'instance', and the other is from the myself attribute of the instance.
If the next line of code is del instance, what happens? The reference count of instance is decreased by 1, so it has a reference count of 1; the reference in the myself attribute still exists. Yet the instance is no longer accessible through Python code, and it could be deleted. Several objects can participate in a cycle if they have references to each other, causing all of the objects to be leaked.
Python 2.0 fixes this problem by periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. A new gc module provides functions to perform a garbage collection, obtain debugging statistics, and tuning the collector's parameters.
Running the cycle detection algorithm takes some time, and therefore will result in some additional overhead. It is hoped that after we've gotten experience with the cycle collection from using 2.0, Python 2.1 will be able to minimize the overhead with careful tuning. It's not yet obvious how much performance is lost, because benchmarking this is tricky and depends crucially on how often the program creates and destroys objects. The detection of cycles can be disabled when Python is compiled, if you can't afford even a tiny speed penalty or suspect that the cycle collection is buggy, by specifying the !--without-cycle-gc switch when running the configure script.
Several people tackled this problem and contributed to a solution. An early implementation of the cycle detection approach was written by Toby Kelsey. The current algorithm was suggested by Eric Tiedemann during a visit to CNRI, and Guido van Rossum and Neil Schemenauer wrote two different implementations, which were later integrated by Neil. Lots of other people offered suggestions along the way; the March 2000 archives of the python-dev mailing list contain most of the relevant discussion, especially in the threads titled "Reference cycle collection for Python" and "Finalization again".
Other Core Changes
Various minor changes have been made to Python's syntax and built-in functions. None of the changes are very far-reaching, but they're handy conveniences.
Minor Language Changes
A new syntax makes it more convenient to call a given function with a tuple of arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier, you'd use the !apply built-in function: apply(f, args, kw) calls the function !f with the argument tuple args and the keyword arguments in the dictionary kw. !apply is the same in 2.0, but thanks to a patch from Greg Ewing, f(*args, **kw) is a shorter and clearer way to achieve the same effect. This syntax is symmetrical with the syntax for defining functions:
def f(*args, **kw):
# args is a tuple of positional args,
# kw is a dictionary of keyword args
...
The print statement can now have its output directed to a file-like object by following the print with >> file, similar to the redirection operator in Unix shells. Previously you'd either have to use the !write method of the file-like object, which lacks the convenience and simplicity of print, or you could assign a new value to sys.stdout and then restore the old value. For sending output to standard error, it's much easier to write this:
print >> sys.stderr, "Warning: action field not supplied"
Modules can now be renamed on importing them, using the syntax import module as name or from module import name as othername. The patch was submitted by Thomas Wouters.
A new format style is available when using the % operator; '%r' will insert the repr of its argument. This was also added from symmetry considerations, this time for symmetry with the existing '%s' format style, which inserts the str of its argument. For example, '%r %s' % ('abc', 'abc') returns a string containing 'abc' abc.
Previously there was no way to implement a class that overrode Python's built-in in operator and implemented a custom version. obj in seq returns true if obj is present in the sequence seq; Python computes this by simply trying every index of the sequence until either obj is found or an IndexError is encountered. Moshe Zadka contributed a patch which adds a !__contains__ magic method for providing a custom implementation for !in. Additionally, new built-in objects written in C can define what !in means for them via a new slot in the sequence protocol.
Earlier versions of Python used a recursive algorithm for deleting objects. Deeply nested data structures could cause the interpreter to fill up the C stack and crash; Christian Tismer rewrote the deletion logic to fix this problem. On a related note, comparing recursive objects recursed infinitely and crashed; Jeremy Hylton rewrote the code to no longer crash, producing a useful result instead. For example, after this code:
a = []
b = []
a.append(a)
b.append(b)
The comparison a==b returns true, because the two recursive data structures are isomorphic. See the thread "trashcan and PR#7" in the April 2000 archives of the python-dev mailing list for the discussion leading up to this implementation, and some useful relevant links. Note that comparisons can now also raise exceptions. In earlier versions of Python, a comparison operation such as cmp(a,b) would always produce an answer, even if a user-defined !__cmp__ method encountered an error, since the resulting exception would simply be silently swallowed.
Work has been done on porting Python to 64-bit Windows on the Itanium processor, mostly by Trent Mick of ActiveState. (Confusingly, sys.platform is still 'win32' on Win64 because it seems that for ease of porting, MS Visual C++ treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the Python CE page at https://pythonce.sourceforge.net/ for more information.
Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0. Dynamic loading works, if you specify "configure --with-dyld --with-suffix=.x". Consult the README in the Python source distribution for more instructions.
An attempt has been made to alleviate one of Python's warts, the often-confusing NameError exception when code refers to a local variable before the variable has been assigned a value. For example, the following code raises an exception on the print statement in both 1.5.2 and 2.0; in 1.5.2 a NameError exception is raised, while 2.0 raises a new UnboundLocalError exception. UnboundLocalError is a subclass of NameError, so any existing code that expects NameError to be raised should still work. :
def f():
print "i=",i
i = i + 1
f()
Two new exceptions, TabError and IndentationError, have been introduced. They're both subclasses of SyntaxError, and are raised when Python code is found to be improperly indented.
Changes to Built-in Functions
A new built-in, zip(seq1, seq2, ...), has been added. zip returns a list of tuples where each tuple contains the i-th element from each of the argument sequences. The difference between zip and map(None, seq1, seq2) is that map pads the sequences with None if the sequences aren't all of the same length, while zip truncates the returned list to the length of the shortest argument sequence.
The int and !long functions now accept an optional "base" parameter when the first argument is a string. int('123', 10) returns 123, while int('123', 16) returns 291. int(123, 16) raises a TypeError exception with the message "can't convert non-string with explicit base".
A new variable holding more detailed version information has been added to the sys module. sys.version_info is a tuple (major, minor, micro, level, serial) For example, in a hypothetical 2.0.1beta1, sys.version_info would be (2, 0, 1, 'beta', 1). level is a string such as "alpha", "beta", or "final" for a final release.
Dictionaries have an odd new method, setdefault(key, default), which behaves similarly to the existing !get method. However, if the key is missing, !setdefault both returns the value of default as !get would do, and also inserts it into the dictionary as the value for key. Thus, the following lines of code:
if dict.has_key( key ): return dict[key]
else:
dict[key] = []
return dict[key]
can be reduced to a single return dict.setdefault(key, []) statement.
The interpreter sets a maximum recursion depth in order to catch runaway recursion before filling the C stack and causing a core dump or GPF.. Previously this limit was fixed when you compiled Python, but in 2.0 the maximum recursion depth can be read and modified using sys.getrecursionlimit and sys.setrecursionlimit. The default value is 1000, and a rough maximum value for a given platform can be found by running a new script, Misc/find_recursionlimit.py.
Porting to 2.0
New Python releases try hard to be compatible with previous releases, and the record has been pretty good. However, some changes are considered useful enough, usually because they fix initial design decisions that turned out to be actively mistaken, that breaking backward compatibility can't always be avoided. This section lists the changes in Python 2.0 that may cause old Python code to break.
The change which will probably break the most code is tightening up the arguments accepted by some methods. Some methods would take multiple arguments and treat them as a tuple, particularly various list methods such as ~list.append and ~list.insert. In earlier versions of Python, if L is a list, L.append( 1,2 ) appends the tuple (1,2) to the list. In Python 2.0 this causes a TypeError exception to be raised, with the message: 'append requires exactly 1 argument; 2 given'. The fix is to simply add an extra set of parentheses to pass both values as a tuple: L.append( (1,2) ).
The earlier versions of these methods were more forgiving because they used an old function in Python's C interface to parse their arguments; 2.0 modernizes them to use PyArg_ParseTuple, the current argument parsing function, which provides more helpful error messages and treats multi-argument calls as errors. If you absolutely must use 2.0 but can't fix your code, you can edit Objects/listobject.c and define the preprocessor symbol NO_STRICT_LIST_APPEND to preserve the old behaviour; this isn't recommended.
Some of the functions in the socket module are still forgiving in this way. For example, socket.connect( ('hostname', 25) ) is the correct form, passing a tuple representing an IP address, but socket.connect('hostname', 25) also works. socket.connect_ex <socket.socket.connect_ex> and socket.bind <socket.socket.bind> are similarly easy-going. 2.0alpha1 tightened these functions up, but because the documentation actually used the erroneous multiple argument form, many people wrote code which would break with the stricter checking. GvR backed out the changes in the face of public reaction, so for the socket module, the documentation was fixed and the multiple argument form is simply marked as deprecated; it will be tightened up again in a future Python version.
The \x escape in string literals now takes exactly 2 hex digits. Previously it would consume all the hex digits following the 'x' and take the lowest 8 bits of the result, so \x123456 was equivalent to \x56.
The AttributeError and NameError exceptions have a more friendly error message, whose text will be something like 'Spam' instance has no attribute 'eggs' or name 'eggs' is not defined. Previously the error message was just the missing attribute name eggs, and code written to take advantage of this fact will break in 2.0.
Some work has been done to make integers and long integers a bit more interchangeable. In 1.5.2, large-file support was added for Solaris, to allow reading files larger than 2 GiB; this made the !tell method of file objects return a long integer instead of a regular integer. Some code would subtract two file offsets and attempt to use the result to multiply a sequence or slice a string, but this raised a TypeError. In 2.0, long integers can be used to multiply or slice a sequence, and it'll behave as you'd intuitively expect it to; 3L * 'abc' produces 'abcabcabc', and (0,1,2,3)[2L:4L] produces (2,3). Long integers can also be used in various contexts where previously only integers were accepted, such as in the !seek method of file objects, and in the formats supported by the % operator (%d, %i, %x, etc.). For example, "%d" % 2L**64 will produce the string 18446744073709551616.
The subtlest long integer change of all is that the str of a long integer no longer has a trailing 'L' character, though repr still includes it. The 'L' annoyed many people who wanted to print long integers that looked just like regular integers, since they had to go out of their way to chop off the character. This is no longer a problem in 2.0, but code which does str(longval)[:-1] and assumes the 'L' is there, will now lose the final digit.
Taking the repr of a float now uses a different formatting precision than str. repr uses %.17g format string for C's !sprintf, while str uses %.12g as before. The effect is that repr may occasionally show more decimal places than str, for certain numbers. For example, the number 8.1 can't be represented exactly in binary, so repr(8.1) is '8.0999999999999996', while str(8.1) is '8.1'.
The -X command-line option, which turned all standard exceptions into strings instead of classes, has been removed; the standard exceptions will now always be classes. The !exceptions module containing the standard exceptions was translated from Python to a built-in C module, written by Barry Warsaw and Fredrik Lundh.
Extending/Embedding Changes
Some of the changes are under the covers, and will only be apparent to people writing C extension modules or embedding a Python interpreter in a larger application. If you aren't dealing with Python's C API, you can safely skip this section.
The version number of the Python C API was incremented, so C extensions compiled for 1.5.2 must be recompiled in order to work with 2.0. On Windows, it's not possible for Python 2.0 to import a third party extension built for Python 1.5.x due to how Windows DLLs work, so Python will raise an exception and the import will fail.
Users of Jim Fulton's ExtensionClass module will be pleased to find out that hooks have been added so that ExtensionClasses are now supported by isinstance and issubclass. This means you no longer have to remember to write code such as if type(obj) == myExtensionClass, but can use the more natural if isinstance(obj, myExtensionClass).
The Python/importdl.c file, which was a mass of #ifdefs to support dynamic loading on many different platforms, was cleaned up and reorganised by Greg Stein. importdl.c is now quite small, and platform-specific code has been moved into a bunch of Python/dynload_\*.c files. Another cleanup: there were also a number of my\*.h files in the Include/ directory that held various portability hacks; they've been merged into a single file, Include/pyport.h.
Vladimir Marangozov's long-awaited malloc restructuring was completed, to make it easy to have the Python interpreter use a custom allocator instead of C's standard malloc. For documentation, read the comments in Include/pymem.h and Include/objimpl.h. For the lengthy discussions during which the interface was hammered out, see the web archives of the 'patches' and 'python-dev' lists at python.org.
Recent versions of the GUSI development environment for MacOS support POSIX threads. Therefore, Python's POSIX threading support now works on the Macintosh. Threading support using the user-space GNU pth library was also contributed.
Threading support on Windows was enhanced, too. Windows supports thread locks that use kernel objects only in case of contention; in the common case when there's no contention, they use simpler functions which are an order of magnitude faster. A threaded version of Python 1.5.2 on NT is twice as slow as an unthreaded version; with the 2.0 changes, the difference is only 10%. These improvements were contributed by Yakov Markovitch.
Python 2.0's source now uses only ANSI C prototypes, so compiling Python now requires an ANSI C compiler, and can no longer be done using a compiler that only supports K&R C.
Previously the Python virtual machine used 16-bit numbers in its bytecode, limiting the size of source files. In particular, this affected the maximum size of literal lists and dictionaries in Python source; occasionally people who are generating Python code would run into this limit. A patch by Charles G. Waldman raises the limit from 2**16 to 2**32.
Three new convenience functions intended for adding constants to a module's dictionary at module initialization time were added: PyModule_AddObject, PyModule_AddIntConstant, and PyModule_AddStringConstant. Each of these functions takes a module object, a null-terminated C string containing the name to be added, and a third argument for the value to be assigned to the name. This third argument is, respectively, a Python object, a C long, or a C string.
A wrapper API was added for Unix-style signal handlers. PyOS_getsig gets a signal handler and PyOS_setsig will set a new handler.
Distutils: Making Modules Easy to Install
Before Python 2.0, installing modules was a tedious affair -- there was no way to figure out automatically where Python is installed, or what compiler options to use for extension modules. Software authors had to go through an arduous ritual of editing Makefiles and configuration files, which only really work on Unix and leave Windows and MacOS unsupported. Python users faced wildly differing installation instructions which varied between different extension packages, which made administering a Python installation something of a chore.
The SIG for distribution utilities, shepherded by Greg Ward, has created the Distutils, a system to make package installation much easier. They form the distutils package, a new part of Python's standard library. In the best case, installing a Python module from source will require the same steps: first you simply mean unpack the tarball or zip archive, and the run "python setup.py install". The platform will be automatically detected, the compiler will be recognized, C extension modules will be compiled, and the distribution installed into the proper directory. Optional command-line arguments provide more control over the installation process, the distutils package offers many places to override defaults -- separating the build from the install, building or installing in non-default directories, and more.
In order to use the Distutils, you need to write a setup.py script. For the simple case, when the software contains only .py files, a minimal setup.py can be just a few lines long:
from distutils.core import setup
setup (name = "foo", version = "1.0",
py_modules = ["module1", "module2"])
The setup.py file isn't much more complicated if the software consists of a few packages:
from distutils.core import setup
setup (name = "foo", version = "1.0",
packages = ["package", "package.subpackage"])
A C extension can be the most complicated case; here's an example taken from the PyXML package:
from distutils.core import setup, Extension
expat_extension = Extension('xml.parsers.pyexpat',
define_macros = [('XML_NS', None)],
include_dirs = [ 'extensions/expat/xmltok',
'extensions/expat/xmlparse' ],
sources = [ 'extensions/pyexpat.c',
'extensions/expat/xmltok/xmltok.c',
'extensions/expat/xmltok/xmlrole.c', ]
)
setup (name = "PyXML", version = "0.5.4",
ext_modules =[ expat_extension ] )
The Distutils can also take care of creating source and binary distributions. The "sdist" command, run by "python setup.py sdist', builds a source distribution such as foo-1.0.tar.gz. Adding new commands isn't difficult, "bdist_rpm" and "bdist_wininst" commands have already been contributed to create an RPM distribution and a Windows installer for the software, respectively. Commands to create other distribution formats such as Debian packages and Solaris .pkg files are in various stages of development.
All this is documented in a new manual, Distributing Python Modules, that joins the basic set of Python documentation.
XML Modules
Python 1.5.2 included a simple XML parser in the form of the !xmllib module, contributed by Sjoerd Mullender. Since 1.5.2's release, two different interfaces for processing XML have become common: SAX2 (version 2 of the Simple API for XML) provides an event-driven interface with some similarities to !xmllib, and the DOM (Document Object Model) provides a tree-based interface, transforming an XML document into a tree of nodes that can be traversed and modified. Python 2.0 includes a SAX2 interface and a stripped-down DOM interface as part of the xml package. Here we will give a brief overview of these new interfaces; consult the Python documentation or the source code for complete details. The Python XML SIG is also working on improved documentation.
SAX2 Support
SAX defines an event-driven interface for parsing XML. To use SAX, you must write a SAX handler class. Handler classes inherit from various classes provided by SAX, and override various methods that will then be called by the XML parser. For example, the ~xml.sax.handler.ContentHandler.startElement and ~xml.sax.handler.ContentHandler.endElement methods are called for every starting and end tag encountered by the parser, the ~xml.sax.handler.ContentHandler.characters method is called for every chunk of character data, and so forth.
The advantage of the event-driven approach is that the whole document doesn't have to be resident in memory at any one time, which matters if you are processing really huge documents. However, writing the SAX handler class can get very complicated if you're trying to modify the document structure in some elaborate way.
For example, this little example program defines a handler that prints a message for every starting and ending tag, and then parses the file hamlet.xml using it:
from xml import sax
class SimpleHandler(sax.ContentHandler):
def startElement(self, name, attrs):
print 'Start of element:', name, attrs.keys()
def endElement(self, name):
print 'End of element:', name
# Create a parser object
parser = sax.make_parser()
# Tell it what handler to use
handler = SimpleHandler()
parser.setContentHandler( handler )
# Parse a file!
parser.parse( 'hamlet.xml' )
For more information, consult the Python documentation, or the XML HOWTO at https://pyxml.sourceforge.net/topics/howto/xml-howto.html.
DOM Support
The Document Object Model is a tree-based representation for an XML document. A top-level !Document instance is the root of the tree, and has a single child which is the top-level !Element instance. This !Element has children nodes representing character data and any sub-elements, which may have further children of their own, and so forth. Using the DOM you can traverse the resulting tree any way you like, access element and attribute values, insert and delete nodes, and convert the tree back into XML.
The DOM is useful for modifying XML documents, because you can create a DOM tree, modify it by adding new nodes or rearranging subtrees, and then produce a new XML document as output. You can also construct a DOM tree manually and convert it to XML, which can be a more flexible way of producing XML output than simply writing <tag1>...</tag1> to a file.
The DOM implementation included with Python lives in the xml.dom.minidom module. It's a lightweight implementation of the Level 1 DOM with support for XML namespaces. The !parse and !parseString convenience functions are provided for generating a DOM tree:
from xml.dom import minidom
doc = minidom.parse('hamlet.xml')
doc is a !Document instance. !Document, like all the other DOM classes such as !Element and Text, is a subclass of the !Node base class. All the nodes in a DOM tree therefore support certain common methods, such as !toxml which returns a string containing the XML representation of the node and its children. Each class also has special methods of its own; for example, !Element and !Document instances have a method to find all child elements with a given tag name. Continuing from the previous 2-line example:
perslist = doc.getElementsByTagName( 'PERSONA' )
print perslist[0].toxml()
print perslist[1].toxml()
For the Hamlet XML file, the above few lines output:
<PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
<PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>
The root element of the document is available as doc.documentElement, and its children can be easily modified by deleting, adding, or removing nodes:
root = doc.documentElement
# Remove the first child
root.removeChild( root.childNodes[0] )
# Move the new first child to the end
root.appendChild( root.childNodes[0] )
# Insert the new first child (originally,
# the third child) before the 20th child.
root.insertBefore( root.childNodes[0], root.childNodes[20] )
Again, I will refer you to the Python documentation for a complete listing of the different !Node classes and their various methods.
Relationship to PyXML
The XML Special Interest Group has been working on XML-related Python code for a while. Its code distribution, called PyXML, is available from the SIG's web pages at https://www.python.org/community/sigs/current/xml-sig. The PyXML distribution also used the package name xml. If you've written programs that used PyXML, you're probably wondering about its compatibility with the 2.0 xml package.
The answer is that Python 2.0's xml package isn't compatible with PyXML, but can be made compatible by installing a recent version PyXML. Many applications can get by with the XML support that is included with Python 2.0, but more complicated applications will require that the full PyXML package will be installed. When installed, PyXML versions 0.6.0 or greater will replace the xml package shipped with Python, and will be a strict superset of the standard package, adding a bunch of additional features. Some of the additional features in PyXML include:
- 4DOM, a full DOM implementation from FourThought, Inc.
- The xmlproc validating parser, written by Lars Marius Garshol.
- The
!sgmlopparser accelerator module, written by Fredrik Lundh.
Module changes
Lots of improvements and bugfixes were made to Python's extensive standard library; some of the affected modules include readline, ConfigParser <configparser>, !cgi, calendar, posix, readline, !xmllib, !aifc, !chunk, wave, random, shelve, and !nntplib. Consult the CVS logs for the exact patch-by-patch details.
Brian Gallew contributed OpenSSL support for the socket module. OpenSSL is an implementation of the Secure Socket Layer, which encrypts the data being sent over a socket. When compiling Python, you can edit Modules/Setup to include SSL support, which adds an additional function to the socket module: socket.ssl(socket, keyfile, certfile), which takes a socket object and returns an SSL socket. The httplib <http> and urllib modules were also changed to support https:// URLs, though no one has implemented FTP or SMTP over SSL.
The httplib <http> module has been rewritten by Greg Stein to support HTTP/1.1.
Backward compatibility with the 1.5 version of !httplib is provided, though using HTTP/1.1 features such as pipelining will require rewriting code to use a different set of interfaces.
The !Tkinter module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and support for the older 7.x versions has been dropped. The Tkinter module now supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh contributed an optimization which makes operations like create_line and create_polygon much faster, especially when using lots of coordinates.
The curses module has been greatly extended, starting from Oliver Andrich's enhanced version, to provide many additional functions from ncurses and SYSV curses, such as colour, alternative character set support, pads, and mouse support. This means the module is no longer compatible with operating systems that only have BSD curses, but there don't seem to be any currently maintained OSes that fall into this category.
As mentioned in the earlier discussion of 2.0's Unicode support, the underlying implementation of the regular expressions provided by the re module has been changed. SRE, a new regular expression engine written by Fredrik Lundh and partially funded by Hewlett Packard, supports matching against both 8-bit strings and Unicode strings.
New modules
A number of new modules were added. We'll simply list them with brief descriptions; consult the 2.0 documentation for the details of a particular module.
atexit: For registering functions to be called before the Python interpreter exits. Code that currently setssys.exitfuncdirectly should be changed to use theatexitmodule instead, importingatexitand callingatexit.registerwith the function to be called on exit. (Contributed by Skip Montanaro.)codecs,!encodings,unicodedata: Added as part of the new Unicode support.filecmp: Supersedes the old!cmp,!cmpcacheand!dircmpmodules, which have now become deprecated. (Contributed by Gordon MacMillan and Moshe Zadka.)gettext: This module provides internationalization (I18N) and localization (L10N) support for Python programs by providing an interface to the GNU gettext message catalog library. (Integrated by Barry Warsaw, from separate contributions by Martin von Löwis, Peter Funk, and James Henstridge.)!linuxaudiodev: Support for the/dev/audiodevice on Linux, a twin to the existing!sunaudiodevmodule. (Contributed by Peter Bosch, with fixes by Jeremy Hylton.)mmap: An interface to memory-mapped files on both Windows and Unix. A file's contents can be mapped directly into memory, at which point it behaves like a mutable string, so its contents can be read and modified. They can even be passed to functions that expect ordinary strings, such as theremodule. (Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)!pyexpat: An interface to the Expat XML parser. (Contributed by Paul Prescod.)robotparser <urllib.robotparser>: Parse arobots.txtfile, which is used for writing web spiders that politely avoid certain areas of a web site. The parser accepts the contents of arobots.txtfile, builds a set of rules from it, and can then answer questions about the fetchability of a given URL. (Contributed by Skip Montanaro.)tabnanny: A module/script to check Python source code for ambiguous indentation. (Contributed by Tim Peters.)!UserString: A base class useful for deriving objects that behave like strings.webbrowser: A module that provides a platform independent way to launch a web browser on a specific URL. For each platform, various browsers are tried in a specific order. The user can alter which browser is launched by setting the BROWSER environment variable. (Originally inspired by Eric S. Raymond's patch tourllibwhich added similar functionality, but the final module comes from code originally implemented by Fred Drake asTools/idle/BrowserControl.py, and adapted for the standard library by Fred.)_winreg <winreg>: An interface to the Windows registry.!_winregis an adaptation of functions that have been part of PythonWin since 1995, but has now been added to the core distribution, and enhanced to support Unicode.!_winregwas written by Bill Tutt and Mark Hammond.zipfile: A module for reading and writing ZIP-format archives. These are archives produced byPKZIPon DOS/Windows orzipon Unix, not to be confused withgzip-format files (which are supported by thegzipmodule) (Contributed by James C. Ahlstrom.)!imputil: A module that provides a simpler way for writing customized import hooks, in comparison to the existing!ihooksmodule. (Implemented by Greg Stein, with much discussion on python-dev along the way.)
IDLE Improvements
IDLE is the official Python cross-platform IDE, written using Tkinter. Python 2.0 includes IDLE 0.6, which adds a number of new features and improvements. A partial list:
- UI improvements and optimizations, especially in the area of syntax highlighting and auto-indentation.
- The class browser now shows more information, such as the top level functions in a module.
- Tab width is now a user settable option. When opening an existing Python file, IDLE automatically detects the indentation conventions, and adapts.
- There is now support for calling browsers on various platforms, used to open the Python documentation in a browser.
- IDLE now has a command line, which is largely similar to the vanilla Python interpreter.
- Call tips were added in many places.
- IDLE can now be installed as a package.
- In the editor window, there is now a line/column bar at the bottom.
- Three new keystroke commands: Check module (
Alt-F5), Import module (F5) and Run script (Ctrl-F5).
Deleted and Deprecated Modules
A few modules have been dropped because they're obsolete, or because there are now better ways to do the same thing. The !stdwin module is gone; it was for a platform-independent windowing toolkit that's no longer developed.
A number of modules have been moved to the lib-old subdirectory: !cmp, !cmpcache, !dircmp, !dump, !find, !grep, !packmail, !poly, !util, !whatsound, !zmod. If you have code which relies on a module that's been moved to lib-old, you can simply add that directory to sys.path to get them back, but you're encouraged to update any code that uses these modules.
Acknowledgements
What's New in Python 2.1
Introduction
This article explains the new features in Python 2.1. While there aren't as many changes in 2.1 as there were in Python 2.0, there are still some pleasant surprises in store. 2.1 is the first release to be steered through the use of Python Enhancement Proposals, or PEPs, so most of the sizable changes have accompanying PEPs that provide more complete documentation and a design rationale for the change. This article doesn't attempt to document the new features completely, but simply provides an overview of the new features for Python programmers. Refer to the Python 2.1 documentation, or to the specific PEP, for more details about any new feature that particularly interests you.
One recent goal of the Python development team has been to accelerate the pace of new releases, with a new release coming every 6 to 9 months. 2.1 is the first release to come out at this faster pace, with the first alpha appearing in January, 3 months after the final version of 2.0 was released.
The final release of Python 2.1 was made on April 17, 2001.
PEP 227: Nested Scopes
The largest change in Python 2.1 is to Python's scoping rules. In Python 2.0, at any given time there are at most three namespaces used to look up variable names: local, module-level, and the built-in namespace. This often surprised people because it didn't match their intuitive expectations. For example, a nested recursive function definition doesn't work:
def f():
...
def g(value):
...
return g(value-1) + 1
...
The function !g will always raise a NameError exception, because the binding of the name g isn't in either its local namespace or in the module-level namespace. This isn't much of a problem in practice (how often do you recursively define interior functions like this?), but this also made using the lambda expression clumsier, and this was a problem in practice. In code which uses lambda you can often find local variables being copied by passing them as the default values of arguments. :
def find(self, name):
"Return list of any entries equal to 'name'"
L = filter(lambda x, name=name: x == name,
self.list_attribute)
return L
The readability of Python code written in a strongly functional style suffers greatly as a result.
The most significant change to Python 2.1 is that static scoping has been added to the language to fix this problem. As a first effect, the name=name default argument is now unnecessary in the above example. Put simply, when a given variable name is not assigned a value within a function (by an assignment, or the def, class, or import statements), references to the variable will be looked up in the local namespace of the enclosing scope. A more detailed explanation of the rules, and a dissection of the implementation, can be found in the PEP.
This change may cause some compatibility problems for code where the same variable name is used both at the module level and as a local variable within a function that contains further function definitions. This seems rather unlikely though, since such code would have been pretty confusing to read in the first place.
One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception.
To make the preceding explanation a bit clearer, here's an example:
x = 1
def f():
# The next line is a syntax error
exec 'x=2'
def g():
return x
Line 4 containing the exec statement is a syntax error, since exec would define a new local variable named x whose value should be accessed by !g.
This shouldn't be much of a limitation, since exec is rarely used in most Python code (and when it is used, it's often a sign of a poor design anyway).
Compatibility concerns have led to nested scopes being introduced gradually; in Python 2.1, they aren't enabled by default, but can be turned on within a module by using a future statement as described in 236. (See the following section for further discussion of 236.) In Python 2.2, nested scopes will become the default and there will be no way to turn them off, but users will have had all of 2.1's lifetime to fix any breakage resulting from their introduction.
227 - Statically Nested Scopes
Written and implemented by Jeremy Hylton.
PEP 236: __future__ Directives
The reaction to nested scopes was widespread concern about the dangers of breaking code with the 2.1 release, and it was strong enough to make the Pythoneers take a more conservative approach. This approach consists of introducing a convention for enabling optional functionality in release N that will become compulsory in release N+1.
The syntax uses a from...import statement using the reserved module name __future__. Nested scopes can be enabled by the following statement:
from __future__ import nested_scopes
While it looks like a normal import statement, it's not; there are strict rules on where such a future statement can be put. They can only be at the top of a module, and must precede any Python code or regular !import statements. This is because such statements can affect how the Python bytecode compiler parses code and generates bytecode, so they must precede any statement that will result in bytecodes being produced.
236 - Back to the __future__
Written by Tim Peters, and primarily implemented by Jeremy Hylton.
PEP 207: Rich Comparisons
In earlier versions, Python's support for implementing comparisons on user-defined classes and extension types was quite simple. Classes could implement a !__cmp__ method that was given two instances of a class, and could only return 0 if they were equal or +1 or -1 if they weren't; the method couldn't raise an exception or return anything other than a Boolean value. Users of Numeric Python often found this model too weak and restrictive, because in the number-crunching programs that numeric Python is used for, it would be more useful to be able to perform elementwise comparisons of two matrices, returning a matrix containing the results of a given comparison for each element. If the two matrices are of different sizes, then the compare has to be able to raise an exception to signal the error.
In Python 2.1, rich comparisons were added in order to support this need. Python classes can now individually overload each of the <, <=, >, >=, ==, and != operations. The new magic method names are:
| Operation | Method name |
|---|---|
< |
~object.__lt__ |
<= |
~object.__le__ |
> |
~object.__gt__ |
>= |
~object.__ge__ |
== |
~object.__eq__ |
!= |
~object.__ne__ |
(The magic methods are named after the corresponding Fortran operators .LT.. .LE., &c. Numeric programmers are almost certainly quite familiar with these names and will find them easy to remember.)
Each of these magic methods is of the form method(self, other), where self will be the object on the left-hand side of the operator, while other will be the object on the right-hand side. For example, the expression A < B will cause A.__lt__(B) to be called.
Each of these magic methods can return anything at all: a Boolean, a matrix, a list, or any other Python object. Alternatively they can raise an exception if the comparison is impossible, inconsistent, or otherwise meaningless.
The built-in cmp(A,B) function can use the rich comparison machinery, and now accepts an optional argument specifying which comparison operation to use; this is given as one of the strings "<", "<=", ">", ">=", "==", or "!=". If called without the optional third argument, !cmp will only return -1, 0, or +1 as in previous versions of Python; otherwise it will call the appropriate method and can return any Python object.
There are also corresponding changes of interest to C programmers; there's a new slot tp_richcmp in type objects and an API for performing a given rich comparison. I won't cover the C API here, but will refer you to 207, or to 2.1's C API documentation, for the full list of related functions.
207 - Rich Comparisons
Written by Guido van Rossum, heavily based on earlier work by David Ascher, and implemented by Guido van Rossum.
PEP 230: Warning Framework
Over its 10 years of existence, Python has accumulated a certain number of obsolete modules and features along the way. It's difficult to know when a feature is safe to remove, since there's no way of knowing how much code uses it --- perhaps no programs depend on the feature, or perhaps many do. To enable removing old features in a more structured way, a warning framework was added. When the Python developers want to get rid of a feature, it will first trigger a warning in the next version of Python. The following Python version can then drop the feature, and users will have had a full release cycle to remove uses of the old feature.
Python 2.1 adds the warning framework to be used in this scheme. It adds a warnings module that provide functions to issue warnings, and to filter out warnings that you don't want to be displayed. Third-party modules can also use this framework to deprecate old features that they no longer wish to support.
For example, in Python 2.1 the !regex module is deprecated, so importing it causes a warning to be printed:
>>> import regex
__main__:1: DeprecationWarning: the regex module
is deprecated; please use the re module
>>>
Warnings can be issued by calling the warnings.warn function:
warnings.warn("feature X no longer supported")
The first parameter is the warning message; an additional optional parameters can be used to specify a particular warning category.
Filters can be added to disable certain warnings; a regular expression pattern can be applied to the message or to the module name in order to suppress a warning. For example, you may have a program that uses the !regex module and not want to spare the time to convert it to use the re module right now. The warning can be suppressed by calling :
import warnings
warnings.filterwarnings(action = 'ignore',
message='.*regex module is deprecated',
category=DeprecationWarning,
module = '__main__')
This adds a filter that will apply only to warnings of the class DeprecationWarning triggered in the __main__ module, and applies a regular expression to only match the message about the !regex module being deprecated, and will cause such warnings to be ignored. Warnings can also be printed only once, printed every time the offending code is executed, or turned into exceptions that will cause the program to stop (unless the exceptions are caught in the usual way, of course).
Functions were also added to Python's C API for issuing warnings; refer to PEP 230 or to Python's API documentation for the details.
5 - Guidelines for Language Evolution
Written by Paul Prescod, to specify procedures to be followed when removing old features from Python. The policy described in this PEP hasn't been officially adopted, but the eventual policy probably won't be too different from Prescod's proposal.
230 - Warning Framework
Written and implemented by Guido van Rossum.
PEP 229: New Build System
When compiling Python, the user had to go in and edit the Modules/Setup file in order to enable various additional modules; the default set is relatively small and limited to modules that compile on most Unix platforms. This means that on Unix platforms with many more features, most notably Linux, Python installations often don't contain all useful modules they could.
Python 2.0 added the Distutils, a set of modules for distributing and installing extensions. In Python 2.1, the Distutils are used to compile much of the standard library of extension modules, autodetecting which ones are supported on the current machine. It's hoped that this will make Python installations easier and more featureful.
Instead of having to edit the Modules/Setup file in order to enable modules, a setup.py script in the top directory of the Python source distribution is run at build time, and attempts to discover which modules can be enabled by examining the modules and header files on the system. If a module is configured in Modules/Setup, the setup.py script won't attempt to compile that module and will defer to the Modules/Setup file's contents. This provides a way to specific any strange command-line flags or libraries that are required for a specific platform.
In another far-reaching change to the build mechanism, Neil Schemenauer restructured things so Python now uses a single makefile that isn't recursive, instead of makefiles in the top directory and in each of the Python/, Parser/, Objects/, and Modules/ subdirectories. This makes building Python faster and also makes hacking the Makefiles clearer and simpler.
229 - Using Distutils to Build Python
Written and implemented by A.M. Kuchling.
PEP 205: Weak References
Weak references, available through the weakref module, are a minor but useful new data type in the Python programmer's toolbox.
Storing a reference to an object (say, in a dictionary or a list) has the side effect of keeping that object alive forever. There are a few specific cases where this behaviour is undesirable, object caches being the most common one, and another being circular references in data structures such as trees.
For example, consider a memoizing function that caches the results of another function f(x) by storing the function's argument and its result in a dictionary:
_cache = {}
def memoize(x):
if _cache.has_key(x):
return _cache[x]
retval = f(x)
# Cache the returned object
_cache[x] = retval
return retval
This version works for simple things such as integers, but it has a side effect; the _cache dictionary holds a reference to the return values, so they'll never be deallocated until the Python process exits and cleans up. This isn't very noticeable for integers, but if !f returns an object, or a data structure that takes up a lot of memory, this can be a problem.
Weak references provide a way to implement a cache that won't keep objects alive beyond their time. If an object is only accessible through weak references, the object will be deallocated and the weak references will now indicate that the object it referred to no longer exists. A weak reference to an object obj is created by calling wr = weakref.ref(obj). The object being referred to is returned by calling the weak reference as if it were a function: wr(). It will return the referenced object, or None if the object no longer exists.
This makes it possible to write a !memoize function whose cache doesn't keep objects alive, by storing weak references in the cache. :
_cache = {}
def memoize(x):
if _cache.has_key(x):
obj = _cache[x]()
# If weak reference object still exists,
# return it
if obj is not None: return obj
retval = f(x)
# Cache a weak reference
_cache[x] = weakref.ref(retval)
return retval
The weakref module also allows creating proxy objects which behave like weak references --- an object referenced only by proxy objects is deallocated -- but instead of requiring an explicit call to retrieve the object, the proxy transparently forwards all operations to the object as long as the object still exists. If the object is deallocated, attempting to use a proxy will cause a !weakref.ReferenceError exception to be raised. :
proxy = weakref.proxy(obj)
proxy.attr # Equivalent to obj.attr
proxy.meth() # Equivalent to obj.meth()
del obj
proxy.attr # raises weakref.ReferenceError
205 - Weak References
Written and implemented by Fred L. Drake, Jr.
PEP 232: Function Attributes
In Python 2.1, functions can now have arbitrary information attached to them. People were often using docstrings to hold information about functions and methods, because the ~function.__doc__ attribute was the only way of attaching any information to a function. For example, in the Zope web application server, functions are marked as safe for public access by having a docstring, and in John Aycock's SPARK parsing framework, docstrings hold parts of the BNF grammar to be parsed. This overloading is unfortunate, since docstrings are really intended to hold a function's documentation; for example, it means you can't properly document functions intended for private use in Zope.
Arbitrary attributes can now be set and retrieved on functions using the regular Python syntax:
def f(): pass
f.publish = 1
f.secure = 1
f.grammar = "A ::= B (C D)*"
The dictionary containing attributes can be accessed as the function's ~function.__dict__. Unlike the ~type.__dict__ attribute of class instances, in functions you can actually assign a new dictionary to ~function.__dict__, though the new value is restricted to a regular Python dictionary; you can't be tricky and set it to a !UserDict instance, or any other random object that behaves like a mapping.
232 - Function Attributes
Written and implemented by Barry Warsaw.
PEP 235: Importing Modules on Case-Insensitive Platforms
Some operating systems have filesystems that are case-insensitive, MacOS and Windows being the primary examples; on these systems, it's impossible to distinguish the filenames FILE.PY and file.py, even though they do store the file's name in its original case (they're case-preserving, too).
In Python 2.1, the import statement will work to simulate case-sensitivity on case-insensitive platforms. Python will now search for the first case-sensitive match by default, raising an ImportError if no such file is found, so import file will not import a module named FILE.PY. Case-insensitive matching can be requested by setting the PYTHONCASEOK environment variable before starting the Python interpreter.
PEP 217: Interactive Display Hook
When using the Python interpreter interactively, the output of commands is displayed using the built-in repr function. In Python 2.1, the variable sys.displayhook can be set to a callable object which will be called instead of repr. For example, you can set it to a special pretty-printing function:
>>> # Create a recursive data structure
... L = [1,2,3]
>>> L.append(L)
>>> L # Show Python's default output
[1, 2, 3, [...]]
>>> # Use pprint.pprint() as the display function
... import sys, pprint
>>> sys.displayhook = pprint.pprint
>>> L
[1, 2, 3, <Recursion on list with id=135143996>]
>>>
217 - Display Hook for Interactive Use
Written and implemented by Moshe Zadka.
PEP 208: New Coercion Model
How numeric coercion is done at the C level was significantly modified. This will only affect the authors of C extensions to Python, allowing them more flexibility in writing extension types that support numeric operations.
Extension types can now set the type flag Py_TPFLAGS_CHECKTYPES in their PyTypeObject structure to indicate that they support the new coercion model. In such extension types, the numeric slot functions can no longer assume that they'll be passed two arguments of the same type; instead they may be passed two arguments of differing types, and can then perform their own internal coercion. If the slot function is passed a type it can't handle, it can indicate the failure by returning a reference to the Py_NotImplemented singleton value. The numeric functions of the other type will then be tried, and perhaps they can handle the operation; if the other type also returns Py_NotImplemented, then a TypeError will be raised. Numeric methods written in Python can also return Py_NotImplemented, causing the interpreter to act as if the method did not exist (perhaps raising a TypeError, perhaps trying another object's numeric methods).
208 - Reworking the Coercion Model
Written and implemented by Neil Schemenauer, heavily based upon earlier work by Marc-André Lemburg. Read this to understand the fine points of how numeric operations will now be processed at the C level.
PEP 241: Metadata in Python Packages
A common complaint from Python users is that there's no single catalog of all the Python modules in existence. T. Middleton's Vaults of Parnassus at www.vex.net/parnassus/ (retired in February 2009, available in the Internet Archive Wayback Machine) was the largest catalog of Python modules, but registering software at the Vaults is optional, and many people did not bother.
As a first small step toward fixing the problem, Python software packaged using the Distutils sdist command will include a file named PKG-INFO containing information about the package such as its name, version, and author (metadata, in cataloguing terminology). 241 contains the full list of fields that can be present in the PKG-INFO file. As people began to package their software using Python 2.1, more and more packages will include metadata, making it possible to build automated cataloguing systems and experiment with them. With the result experience, perhaps it'll be possible to design a really good catalog and then build support for it into Python 2.2. For example, the Distutils sdist and bdist_\* commands could support an upload option that would automatically upload your package to a catalog server.
You can start creating packages containing PKG-INFO even if you're not using Python 2.1, since a new release of the Distutils will be made for users of earlier Python versions. Version 1.0.2 of the Distutils includes the changes described in 241, as well as various bugfixes and enhancements. It will be available from the Distutils SIG at https://www.python.org/community/sigs/current/distutils-sig/.
241 - Metadata for Python Software Packages
Written and implemented by A.M. Kuchling.
243 - Module Repository Upload Mechanism
Written by Sean Reifschneider, this draft PEP describes a proposed mechanism for uploading Python packages to a central server.
New and Improved Modules
-
Ka-Ping Yee contributed two new modules:
!inspect.py, a module for getting information about live Python code, and!pydoc.py, a module for interactively converting docstrings to HTML or text. As a bonus,Tools/scripts/pydoc, which is now automatically installed, uses!pydoc.pyto display documentation given a Python module, package, or class name. For example,pydoc xml.domdisplays the following:Python Library Documentation: package xml.dom in xml NAME xml.dom - W3C Document Object Model implementation for Python. FILE /usr/local/lib/python2.1/xml/dom/__init__.pyc DESCRIPTION The Python mapping of the Document Object Model is documented in the Python Library Reference in the section on the xml.dom package. This package contains the following modules: ...pydocalso includes a Tk-based interactive help browser.pydocquickly becomes addictive; try it out! -
Two different modules for unit testing were added to the standard library. The
doctestmodule, contributed by Tim Peters, provides a testing framework based on running embedded examples in docstrings and comparing the results against the expected output. PyUnit, contributed by Steve Purcell, is a unit testing framework inspired by JUnit, which was in turn an adaptation of Kent Beck's Smalltalk testing framework. See https://pyunit.sourceforge.net/ for more information about PyUnit. -
The
difflibmodule contains a class,~difflib.SequenceMatcher, which compares two sequences and computes the changes required to transform one sequence into the other. For example, this module can be used to write a tool similar to the Unixdiffprogram, and in fact the sample programTools/scripts/ndiff.pydemonstrates how to write such a script. -
curses.panel, a wrapper for the panel library, part of ncurses and of SYSV curses, was contributed by Thomas Gellekum. The panel library provides windows with the additional feature of depth. Windows can be moved higher or lower in the depth ordering, and the panel library figures out where panels overlap and which sections are visible. -
The PyXML package has gone through a few releases since Python 2.0, and Python 2.1 includes an updated version of the
xmlpackage. Some of the noteworthy changes include support for Expat 1.2 and later versions, the ability for Expat parsers to handle files in any encoding supported by Python, and various bugfixes for SAX, DOM, and the!minidommodule. -
Ping also contributed another hook for handling uncaught exceptions.
sys.excepthookcan be set to a callable object. When an exception isn't caught by anytry...exceptblocks, the exception will be passed tosys.excepthook, which can then do whatever it likes. At the Ninth Python Conference, Ping demonstrated an application for this hook: printing an extended traceback that not only lists the stack frames, but also lists the function arguments and the local variables for each frame. -
Various functions in the
timemodule, such as~time.asctimeand~time.localtime, require a floating-point argument containing the time in seconds since the epoch. The most common use of these functions is to work with the current time, so the floating-point argument has been made optional; when a value isn't provided, the current time will be used. For example, log file entries usually need a string containing the current time; in Python 2.1,time.asctime()can be used, instead of the lengthiertime.asctime(time.localtime(time.time()))that was previously required.This change was proposed and implemented by Thomas Wouters.
-
The
ftplibmodule now defaults to retrieving files in passive mode, because passive mode is more likely to work from behind a firewall. This request came from the Debian bug tracking system, since other Debian packages useftplibto retrieve files and then don't work from behind a firewall. It's deemed unlikely that this will cause problems for anyone, because Netscape defaults to passive mode and few people complain, but if passive mode is unsuitable for your application or network setup, callset_pasv(0)on FTP objects to disable passive mode. -
Support for raw socket access has been added to the
socketmodule, contributed by Grant Edwards. -
The
pstatsmodule now contains a simple interactive statistics browser for displaying timing profiles for Python programs, invoked when the module is run as a script. Contributed by Eric S. Raymond. -
A new implementation-dependent function,
sys._getframe([depth]), has been added to return a given frame object from the current call stack.sys._getframereturns the frame at the top of the call stack; if the optional integer argument depth is supplied, the function returns the frame that is depth calls below the top of the stack. For example,sys._getframe(1)returns the caller's frame object.This function is only present in CPython, not in Jython or the .NET implementation. Use it for debugging, and resist the temptation to put it into production code.
Other Changes and Fixes
There were relatively few smaller changes made in Python 2.1 due to the shorter release cycle. A search through the CVS change logs turns up 117 patches applied, and 136 bugs fixed; both figures are likely to be underestimates. Some of the more notable changes are:
-
A specialized object allocator is now optionally available, that should be faster than the system
mallocand have less memory overhead. The allocator uses C's!mallocfunction to get large pools of memory, and then fulfills smaller memory requests from these pools. It can be enabled by providing the!--with-pymallocoption to theconfigurescript; seeObjects/obmalloc.cfor the implementation details.Authors of C extension modules should test their code with the object allocator enabled, because some incorrect code may break, causing core dumps at runtime. There are a bunch of memory allocation functions in Python's C API that have previously been just aliases for the C library's
mallocandfree, meaning that if you accidentally called mismatched functions, the error wouldn't be noticeable. When the object allocator is enabled, these functions aren't aliases of!mallocand!freeany more, and calling the wrong function to free memory will get you a core dump. For example, if memory was allocated usingPyMem_New, it has to be freed usingPyMem_Del, not!free. A few modules included with Python fell afoul of this and had to be fixed; doubtless there are more third-party modules that will have the same problem.The object allocator was contributed by Vladimir Marangozov.
-
The speed of line-oriented file I/O has been improved because people often complain about its lack of speed, and because it's often been used as a naïve benchmark. The
readlinemethod of file objects has therefore been rewritten to be much faster. The exact amount of the speedup will vary from platform to platform depending on how slow the C library's!getcwas, but is around 66%, and potentially much faster on some particular operating systems. Tim Peters did much of the benchmarking and coding for this change, motivated by a discussion in comp.lang.python.A new module and method for file objects was also added, contributed by Jeff Epler. The new method,
!xreadlines, is similar to the existing!xrangebuilt-in.!xreadlinesreturns an opaque sequence object that only supports being iterated over, reading a line on every iteration but not reading the entire file into memory as the existing!readlinesmethod does. You'd use it like this:for line in sys.stdin.xreadlines(): # ... do something for each line ... ...For a fuller discussion of the line I/O changes, see the python-dev summary for January 1--15, 2001 at https://mail.python.org/pipermail/python-dev/2001-January/.
-
A new method,
~dict.popitem, was added to dictionaries to enable destructively iterating through the contents of a dictionary; this can be faster for large dictionaries because there's no need to construct a list containing all the keys or values.D.popitem()removes a random(key, value)pair from the dictionaryDand returns it as a 2-tuple. This was implemented mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary patch by Moshe Zadka. -
Modules can now control which names are imported when
from module import *is used, by defining an__all__attribute containing a list of names that will be imported. One common complaint is that if the module imports other modules such assysorstring,from module import *will add them to the importing module's namespace. To fix this, simply list the public names in__all__:# List public names __all__ = ['Database', 'open']A stricter version of this patch was first suggested and implemented by Ben Wolfson, but after some python-dev discussion, a weaker final version was checked in.
-
Applying
reprto strings previously used octal escapes for non-printable characters; for example, a newline was'\012'. This was a vestigial trace of Python's C ancestry, but today octal is of very little practical use. Ka-Ping Yee suggested using hex escapes instead of octal ones, and using the\n,\t,\rescapes for the appropriate characters, and implemented this new formatting. -
Syntax errors detected at compile-time can now raise exceptions containing the filename and line number of the error, a pleasant side effect of the compiler reorganization done by Jeremy Hylton.
-
C extensions which import other modules have been changed to use
PyImport_ImportModule, which means that they will use any import hooks that have been installed. This is also encouraged for third-party extensions that need to import some other module from C code. -
The size of the Unicode character database was shrunk by another 340K thanks to Fredrik Lundh.
-
Some new ports were contributed: MacOS X (by Steven Majewski), Cygwin (by Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7 (by Billy G. Allie).
And there's the usual list of minor bugfixes, minor memory leaks, docstring edits, and other tweaks, too lengthy to be worth itemizing; see the CVS logs for the full details if you want them.
Acknowledgements
What's New in Python 2.2
Introduction
This article explains the new features in Python 2.2.2, released on October 14, 2002. Python 2.2.2 is a bugfix release of Python 2.2, originally released on December 21, 2001.
Python 2.2 can be thought of as the "cleanup release". There are some features such as generators and iterators that are completely new, but most of the changes, significant and far-reaching though they may be, are aimed at cleaning up irregularities and dark corners of the language design.
This article doesn't attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.2, such as the Python Library Reference and the Python Reference Manual. If you want to understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature.
http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm
"What's So Special About Python 2.2?" is also about the new 2.2 features, and was written by Cameron Laird and Kathryn Soraiz.
PEPs 252 and 253: Type and Class Changes
The largest and most far-reaching changes in Python 2.2 are to Python's model of objects and classes. The changes should be backward compatible, so it's likely that your code will continue to run unchanged, but the changes provide some amazing new capabilities. Before beginning this, the longest and most complicated section of this article, I'll provide an overview of the changes and offer some comments.
A long time ago I wrote a web page listing flaws in Python's design. One of the most significant flaws was that it's impossible to subclass Python types implemented in C. In particular, it's not possible to subclass built-in types, so you can't just subclass, say, lists in order to add a single useful method to them. The !UserList module provides a class that supports all of the methods of lists and that can be subclassed further, but there's lots of C code that expects a regular Python list and won't accept a ~collections.UserList instance.
Python 2.2 fixes this, and in the process adds some exciting new capabilities. A brief summary:
- You can subclass built-in types such as lists and even integers, and your subclasses should work in every place that requires the original type.
- It's now possible to define static and class methods, in addition to the instance methods available in previous versions of Python.
- It's also possible to automatically call methods on accessing or setting an instance attribute by using a new mechanism called
properties. Many uses of~object.__getattr__can be rewritten to use properties instead, making the resulting code simpler and faster. As a small side benefit, attributes can now have docstrings, too. - The list of legal attributes for an instance can be limited to a particular set using
slots, making it possible to safeguard against typos and perhaps make more optimizations possible in future versions of Python.
Some users have voiced concern about all these changes. Sure, they say, the new features are neat and lend themselves to all sorts of tricks that weren't possible in previous versions of Python, but they also make the language more complicated. Some people have said that they've always recommended Python for its simplicity, and feel that its simplicity is being lost.
Personally, I think there's no need to worry. Many of the new features are quite esoteric, and you can write a lot of Python code without ever needed to be aware of them. Writing a simple class is no more difficult than it ever was, so you don't need to bother learning or teaching them unless they're actually needed. Some very complicated tasks that were previously only possible from C will now be possible in pure Python, and to my mind that's all for the better.
I'm not going to attempt to cover every single corner case and small change that were required to make the new features work. Instead this section will paint only the broad strokes. See section sect-rellinks, "Related Links", for further sources of information about Python 2.2's new object model.
Old and New Classes
First, you should know that Python 2.2 really has two kinds of classes: classic or old-style classes, and new-style classes. The old-style class model is exactly the same as the class model in earlier versions of Python. All the new features described in this section apply only to new-style classes. This divergence isn't intended to last forever; eventually old-style classes will be dropped, possibly in Python 3.0.
So how do you define a new-style class? You do it by subclassing an existing new-style class. Most of Python's built-in types, such as integers, lists, dictionaries, and even files, are new-style classes now. A new-style class named object, the base class for all built-in types, has also been added so if no built-in type is suitable, you can just subclass object:
class C(object):
def __init__ (self):
...
...
This means that class statements that don't have any base classes are always classic classes in Python 2.2. (Actually you can also change this by setting a module-level variable named !__metaclass__ --- see 253 for the details --- but it's easier to just subclass object.)
The type objects for the built-in types are available as built-ins, named using a clever trick. Python has always had built-in functions named int, float, and str. In 2.2, they aren't functions any more, but type objects that behave as factories when called. :
>>> int
<type 'int'>
>>> int('123')
123
To make the set of types complete, new type objects such as dict and !file have been added. Here's a more interesting example, adding a !lock method to file objects:
class LockableFile(file):
def lock (self, operation, length=0, start=0, whence=0):
import fcntl
return fcntl.lockf(self.fileno(), operation,
length, start, whence)
The now-obsolete !posixfile module contained a class that emulated all of a file object's methods and also added a !lock method, but this class couldn't be passed to internal functions that expected a built-in file, something which is possible with our new !LockableFile.
Descriptors
In previous versions of Python, there was no consistent way to discover what attributes and methods were supported by an object. There were some informal conventions, such as defining !__members__ and !__methods__ attributes that were lists of names, but often the author of an extension type or a class wouldn't bother to define them. You could fall back on inspecting the ~object.__dict__ of an object, but when class inheritance or an arbitrary !__getattr__ hook were in use this could still be inaccurate.
The one big idea underlying the new class model is that an API for describing the attributes of an object using descriptors has been formalized. Descriptors specify the value of an attribute, stating whether it's a method or a field. With the descriptor API, static methods and class methods become possible, as well as more exotic constructs.
Attribute descriptors are objects that live inside class objects, and have a few attributes of their own:
~definition.__name__is the attribute's name.~definition.__doc__is the attribute's docstring.__get__(object)is a method that retrieves the attribute value from object.__set__(object, value)sets the attribute on object to value.__delete__(object, value)deletes the value attribute of object.
For example, when you write obj.x, the steps that Python actually performs are:
descriptor = obj.__class__.x
descriptor.__get__(obj)
For methods, descriptor.__get__ <object.__get__> returns a temporary object that's callable, and wraps up the instance and the method to be called on it. This is also why static methods and class methods are now possible; they have descriptors that wrap up just the method, or the method and the class. As a brief explanation of these new kinds of methods, static methods aren't passed the instance, and therefore resemble regular functions. Class methods are passed the class of the object, but not the object itself. Static and class methods are defined like this:
class C(object):
def f(arg1, arg2):
...
f = staticmethod(f)
def g(cls, arg1, arg2):
...
g = classmethod(g)
The staticmethod function takes the function !f, and returns it wrapped up in a descriptor so it can be stored in the class object. You might expect there to be special syntax for creating such methods (def static f, defstatic f(), or something like that) but no such syntax has been defined yet; that's been left for future versions of Python.
More new features, such as slots and properties, are also implemented as new kinds of descriptors, and it's not difficult to write a descriptor class that does something novel. For example, it would be possible to write a descriptor class that made it possible to write Eiffel-style preconditions and postconditions for a method. A class that used this feature might be defined like this:
from eiffel import eiffelmethod
class C(object):
def f(self, arg1, arg2):
# The actual function
...
def pre_f(self):
# Check preconditions
...
def post_f(self):
# Check postconditions
...
f = eiffelmethod(f, pre_f, post_f)
Note that a person using the new !eiffelmethod doesn't have to understand anything about descriptors. This is why I think the new features don't increase the basic complexity of the language. There will be a few wizards who need to know about it in order to write !eiffelmethod or the ZODB or whatever, but most users will just write code on top of the resulting libraries and ignore the implementation details.
Multiple Inheritance: The Diamond Rule
Multiple inheritance has also been made more useful through changing the rules under which names are resolved. Consider this set of classes (diagram taken from 253 by Guido van Rossum):
class A:
^ ^ def save(self): ...
/ \
/ \
/ \
/ \
class B class C:
^ ^ def save(self): ...
\ /
\ /
\ /
\ /
class D
The lookup rule for classic classes is simple but not very smart; the base classes are searched depth-first, going from left to right. A reference to !D.save will search the classes !D, !B, and then !A, where !save would be found and returned. !C.save would never be found at all. This is bad, because if !C's !save method is saving some internal state specific to !C, not calling it will result in that state never getting saved.
New-style classes follow a different algorithm that's a bit more complicated to explain, but does the right thing in this situation. (Note that Python 2.3 changes this algorithm to one that produces the same results in most cases, but produces more useful results for really complicated inheritance graphs.)
- List all the base classes, following the classic lookup rule and include a class multiple times if it's visited repeatedly. In the above example, the list of visited classes is [
!D,!B,!A,!C,!A]. - Scan the list for duplicated classes. If any are found, remove all but one occurrence, leaving the last one in the list. In the above example, the list becomes [
!D,!B,!C,!A] after dropping duplicates.
Following this rule, referring to !D.save will return !C.save, which is the behaviour we're after. This lookup rule is the same as the one followed by Common Lisp. A new built-in function, super, provides a way to get at a class's superclasses without having to reimplement Python's algorithm. The most commonly used form will be super(class, obj), which returns a bound superclass object (not the actual class object). This form will be used in methods to call a method in the superclass; for example, !D's !save method would look like this:
class D (B,C):
def save (self):
# Call superclass .save()
super(D, self).save()
# Save D's private information here
...
super can also return unbound superclass objects when called as super(class) or super(class1, class2), but this probably won't often be useful.
Attribute Access
A fair number of sophisticated Python classes define hooks for attribute access using ~object.__getattr__; most commonly this is done for convenience, to make code more readable by automatically mapping an attribute access such as obj.parent into a method call such as obj.get_parent. Python 2.2 adds some new ways of controlling attribute access.
First, __getattr__(attr_name) is still supported by new-style classes, and nothing about it has changed. As before, it will be called when an attempt is made to access obj.foo and no attribute named foo is found in the instance's dictionary.
New-style classes also support a new method, __getattribute__(attr_name). The difference between the two methods is that ~object.__getattribute__ is always called whenever any attribute is accessed, while the old ~object.__getattr__ is only called if foo isn't found in the instance's dictionary.
However, Python 2.2's support for properties will often be a simpler way to trap attribute references. Writing a !__getattr__ method is complicated because to avoid recursion you can't use regular attribute accesses inside them, and instead have to mess around with the contents of ~object.__dict__. ~object.__getattr__ methods also end up being called by Python when it checks for other methods such as ~object.__repr__ or !__coerce__, and so have to be written with this in mind. Finally, calling a function on every attribute access results in a sizable performance loss.
property is a new built-in type that packages up three functions that get, set, or delete an attribute, and a docstring. For example, if you want to define a !size attribute that's computed, but also settable, you could write:
class C(object):
def get_size (self):
result = ... computation ...
return result
def set_size (self, size):
... compute something based on the size
and set internal state appropriately ...
# Define a property. The 'delete this attribute'
# method is defined as None, so the attribute
# can't be deleted.
size = property(get_size, set_size,
None,
"Storage size of this instance")
That is certainly clearer and easier to write than a pair of !__getattr__/!__setattr__ methods that check for the !size attribute and handle it specially while retrieving all other attributes from the instance's ~object.__dict__. Accesses to !size are also the only ones which have to perform the work of calling a function, so references to other attributes run at their usual speed.
Finally, it's possible to constrain the list of attributes that can be referenced on an object using the new ~object.__slots__ class attribute. Python objects are usually very dynamic; at any time it's possible to define a new attribute on an instance by just doing obj.new_attr=1. A new-style class can define a class attribute named ~object.__slots__ to limit the legal attributes to a particular set of names. An example will make this clear:
>>> class C(object):
... __slots__ = ('template', 'name')
...
>>> obj = C()
>>> print obj.template
None
>>> obj.template = 'Test'
>>> print obj.template
Test
>>> obj.newattr = None
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'newattr'
Note how you get an AttributeError on the attempt to assign to an attribute not listed in ~object.__slots__.
Related Links
This section has just been a quick overview of the new features, giving enough of an explanation to start you programming, but many details have been simplified or ignored. Where should you go to get a more complete picture?
The descriptorhowto is a lengthy tutorial introduction to the descriptor features, written by Guido van Rossum. If my description has whetted your appetite, go read this tutorial next, because it goes into much more detail about the new features while still remaining quite easy to read.
Next, there are two relevant PEPs, 252 and 253. 252 is titled "Making Types Look More Like Classes", and covers the descriptor API. 253 is titled "Subtyping Built-in Types", and describes the changes to type objects that make it possible to subtype built-in objects. 253 is the more complicated PEP of the two, and at a few points the necessary explanations of types and meta-types may cause your head to explode. Both PEPs were written and implemented by Guido van Rossum, with substantial assistance from the rest of the Zope Corp. team.
Finally, there's the ultimate authority: the source code. Most of the machinery for the type handling is in Objects/typeobject.c, but you should only resort to it after all other avenues have been exhausted, including posting a question to python-list or python-dev.
PEP 234: Iterators
Another significant addition to 2.2 is an iteration interface at both the C and Python levels. Objects can define how they can be looped over by callers.
In Python versions up to 2.1, the usual way to make for item in obj work is to define a ~object.__getitem__ method that looks something like this:
def __getitem__(self, index):
return <next item>
~object.__getitem__ is more properly used to define an indexing operation on an object so that you can write obj[5] to retrieve the sixth element. It's a bit misleading when you're using this only to support for loops. Consider some file-like object that wants to be looped over; the index parameter is essentially meaningless, as the class probably assumes that a series of ~object.__getitem__ calls will be made with index incrementing by one each time. In other words, the presence of the ~object.__getitem__ method doesn't mean that using file[5] to randomly access the sixth element will work, though it really should.
In Python 2.2, iteration can be implemented separately, and ~object.__getitem__ methods can be limited to classes that really do support random access. The basic idea of iterators is simple. A new built-in function, iter(obj) or iter(C, sentinel), is used to get an iterator. iter(obj) returns an iterator for the object obj, while iter(C, sentinel) returns an iterator that will invoke the callable object C until it returns sentinel to signal that the iterator is done.
Python classes can define an !__iter__ method, which should create and return a new iterator for the object; if the object is its own iterator, this method can just return self. In particular, iterators will usually be their own iterators. Extension types implemented in C can implement a ~PyTypeObject.tp_iter function in order to return an iterator, and extension types that want to behave as iterators can define a ~PyTypeObject.tp_iternext function.
So, after all this, what do iterators actually do? They have one required method, next, which takes no arguments and returns the next value. When there are no more values to be returned, calling next should raise the StopIteration exception. :
>>> L = [1,2,3]
>>> i = iter(L)
>>> print i
<iterator object at 0x8116870>
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
>>>
In 2.2, Python's for statement no longer expects a sequence; it expects something for which iter will return an iterator. For backward compatibility and convenience, an iterator is automatically constructed for sequences that don't implement !__iter__ or a ~PyTypeObject.tp_iter slot, so for i in [1,2,3] will still work. Wherever the Python interpreter loops over a sequence, it's been changed to use the iterator protocol. This means you can do things like this:
>>> L = [1,2,3]
>>> i = iter(L)
>>> a,b,c = i
>>> a,b,c
(1, 2, 3)
Iterator support has been added to some of Python's basic types. Calling iter on a dictionary will return an iterator which loops over its keys:
>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
>>> for key in m: print key, m[key]
...
Mar 3
Feb 2
Aug 8
Sep 9
May 5
Jun 6
Jul 7
Jan 1
Apr 4
Nov 11
Dec 12
Oct 10
That's just the default behaviour. If you want to iterate over keys, values, or key/value pairs, you can explicitly call the !iterkeys, !itervalues, or !iteritems methods to get an appropriate iterator. In a minor related change, the in operator now works on dictionaries, so key in dict is now equivalent to dict.has_key(key).
Files also provide an iterator, which calls the readline method until there are no more lines in the file. This means you can now read each line of a file using code like this:
for line in file:
# do something for each line
...
Note that you can only go forward in an iterator; there's no way to get the previous element, reset the iterator, or make a copy of it. An iterator object could provide such additional capabilities, but the iterator protocol only requires a next method.
234 - Iterators
Written by Ka-Ping Yee and GvR; implemented by the Python Labs crew, mostly by GvR and Tim Peters.
PEP 255: Simple Generators
Generators are another new feature, one that interacts with the introduction of iterators.
You're doubtless familiar with how function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a return statement, the local variables are destroyed and the resulting value is returned to the caller. A later call to the same function will get a fresh new set of local variables. But, what if the local variables weren't thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.
Here's the simplest example of a generator function:
def generate_ints(N):
for i in range(N):
yield i
A new keyword, yield, was introduced for generators. Any function containing a !yield statement is a generator function; this is detected by Python's bytecode compiler which compiles the function specially as a result. Because a new keyword was introduced, generators must be explicitly enabled in a module by including a from __future__ import generators statement near the top of the module's source code. In Python 2.3 this statement will become unnecessary.
When you call a generator function, it doesn't return a single value; instead it returns a generator object that supports the iterator protocol. On executing the yield statement, the generator outputs the value of i, similar to a return statement. The big difference between !yield and a !return statement is that on reaching a !yield the generator's state of execution is suspended and local variables are preserved. On the next call to the generator's next() method, the function will resume executing immediately after the !yield statement. (For complicated reasons, the !yield statement isn't allowed inside the !try block of a try...finally statement; read 255 for a full explanation of the interaction between !yield and exceptions.)
Here's a sample usage of the !generate_ints generator:
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in generate_ints
StopIteration
You could equally write for i in generate_ints(5), or a,b,c = generate_ints(3).
Inside a generator function, the return statement can only be used without a value, and signals the end of the procession of values; afterwards the generator cannot return any further values. !return with a value, such as return 5, is a syntax error inside a generator function. The end of the generator's results can also be indicated by raising StopIteration manually, or by just letting the flow of execution fall off the bottom of the function.
You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting self.count to 0, and having the next method increment self.count and return it. However, for a moderately complicated generator, writing a corresponding class would be much messier. Lib/test/test_generators.py contains a number of more interesting examples. The simplest one implements an in-order traversal of a tree using generators recursively. :
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
Two other examples in Lib/test/test_generators.py produce solutions for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no queen threatens another) and the Knight's Tour (a route that takes a knight to every square of an $NxN$ chessboard without visiting any square twice).
The idea of generators comes from other programming languages, especially Icon (https://www2.cs.arizona.edu/icon/), where the idea of generators is central. In Icon, every expression and function call behaves like a generator. One example from "An Overview of the Icon Programming Language" at https://www2.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks like:
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
In Icon the !find function returns the indexes at which the substring "or" is found: 3, 23, 33. In the if statement, i is first assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon retries it with the second value of 23. 23 is greater than 5, so the comparison now succeeds, and the code prints the value 23 to the screen.
Python doesn't go nearly as far as Icon in adopting generators as a central concept. Generators are considered a new part of the core Python language, but learning or using them isn't compulsory; if they don't solve any problems that you have, feel free to ignore them. One novel feature of Python's interface as compared to Icon's is that a generator's state is represented as a concrete object (the iterator) that can be passed around to other functions or stored in a data structure.
255 - Simple Generators
Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
PEP 237: Unifying Long Integers and Integers
In recent versions, the distinction between regular integers, which are 32-bit values on most machines, and long integers, which can be of arbitrary size, was becoming an annoyance. For example, on platforms that support files larger than 2**32 bytes, the !tell method of file objects has to return a long integer. However, there were various bits of Python that expected plain integers and would raise an error if a long integer was provided instead. For example, in Python 1.5, only regular integers could be used as a slice index, and 'abc'[1L:] would raise a TypeError exception with the message 'slice index must be int'.
Python 2.2 will shift values from short to long integers as required. The 'L' suffix is no longer needed to indicate a long integer literal, as now the compiler will choose the appropriate type. (Using the 'L' suffix will be discouraged in future 2.x versions of Python, triggering a warning in Python 2.4, and probably dropped in Python 3.0.) Many operations that used to raise an OverflowError will now return a long integer as their result. For example:
>>> 1234567890123
1234567890123L
>>> 2 ** 64
18446744073709551616L
In most cases, integers and long integers will now be treated identically. You can still distinguish them with the type built-in function, but that's rarely needed.
237 - Unifying Long Integers and Integers
Written by Moshe Zadka and Guido van Rossum. Implemented mostly by Guido van Rossum.
PEP 238: Changing the Division Operator
The most controversial change in Python 2.2 heralds the start of an effort to fix an old design flaw that's been in Python from the beginning. Currently Python's division operator, /, behaves like C's division operator when presented with two integer arguments: it returns an integer result that's truncated down when there would be a fractional part. For example, 3/2 is 1, not 1.5, and (-1)/2 is -1, not -0.5. This means that the results of division can vary unexpectedly depending on the type of the two operands and because Python is dynamically typed, it can be difficult to determine the possible types of the operands.
(The controversy is over whether this is really a design flaw, and whether it's worth breaking existing code to fix this. It's caused endless discussions on python-dev, and in July 2001 erupted into a storm of acidly sarcastic postings on comp.lang.python. I won't argue for either side here and will stick to describing what's implemented in 2.2. Read 238 for a summary of arguments and counter-arguments.)
Because this change might break code, it's being introduced very gradually. Python 2.2 begins the transition, but the switch won't be complete until Python 3.0.
First, I'll borrow some terminology from 238. "True division" is the division that most non-programmers are familiar with: 3/2 is 1.5, 1/4 is 0.25, and so forth. "Floor division" is what Python's / operator currently does when given integer operands; the result is the floor of the value returned by true division. "Classic division" is the current mixed behaviour of /; it returns the result of floor division when the operands are integers, and returns the result of true division when one of the operands is a floating-point number.
Here are the changes 2.2 introduces:
-
A new operator,
//, is the floor division operator. (Yes, we know it looks like C++'s comment symbol.)//always performs floor division no matter what the types of its operands are, so1 // 2is 0 and1.0 // 2.0is also 0.0.//is always available in Python 2.2; you don't need to enable it using a__future__statement. -
By including a
from __future__ import divisionin a module, the/operator will be changed to return the result of true division, so1/2is 0.5. Without the__future__statement,/still means classic division. The default meaning of/will not change until Python 3.0. -
Classes can define methods called
~object.__truediv__and~object.__floordiv__to overload the two division operators. At the C level, there are also slots in thePyNumberMethodsstructure so extension types can define the two operators. -
Python 2.2 supports some command-line arguments for testing whether code will work with the changed division semantics. Running python with
!-Q warnwill cause a warning to be issued whenever division is applied to two integers. You can use this to find code that's affected by the change and fix it. By default, Python 2.2 will simply perform classic division without a warning; the warning will be turned on by default in Python 2.3.
238 - Changing the Division Operator
Written by Moshe Zadka and Guido van Rossum. Implemented by Guido van Rossum..
Unicode Changes
Python's Unicode support has been enhanced a bit in 2.2. Unicode strings are usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by supplying !--enable-unicode=ucs4 to the configure script. (It's also possible to specify !--disable-unicode to completely disable Unicode support.)
When built to use UCS-4 (a "wide Python"), the interpreter can natively handle Unicode characters from U+000000 to U+110000, so the range of legal values for the !unichr function is expanded accordingly. Using an interpreter compiled to use UCS-2 (a "narrow Python"), values greater than 65535 will still cause !unichr to raise a ValueError exception. This is all described in 261, "Support for 'wide' Unicode characters"; consult it for further details.
Another change is simpler to explain. Since their introduction, Unicode strings have supported an !encode method to convert the string to a selected encoding such as UTF-8 or Latin-1. A symmetric decode([*encoding*]) method has been added to 8-bit strings (though not to Unicode strings) in 2.2. !decode assumes that the string is in the specified encoding and decodes it, returning whatever is returned by the codec.
Using this new feature, codecs have been added for tasks not directly related to Unicode. For example, codecs have been added for uu-encoding, MIME's base64 encoding, and compression with the zlib module:
>>> s = """Here is a lengthy piece of redundant, overly verbose,
... and repetitive text.
... """
>>> data = s.encode('zlib')
>>> data
'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...'
>>> data.decode('zlib')
'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n'
>>> print s.encode('uu')
begin 666 <data>
M2&5R92!I<R!A(&QE;F=T:'D@<&EE8V4@;V8@<F5D=6YD86YT+"!O=F5R;'D@
>=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X="X*
end
>>> "sheesh".encode('rot-13')
'furrfu'
To convert a class instance to Unicode, a !__unicode__ method can be defined by a class, analogous to !__str__.
!encode, !decode, and !__unicode__ were implemented by Marc-André Lemburg. The changes to support using UCS-4 internally were implemented by Fredrik Lundh and Martin von Löwis.
261 - Support for 'wide' Unicode characters
Written by Paul Prescod.
PEP 227: Nested Scopes
In Python 2.1, statically nested scopes were added as an optional feature, to be enabled by a from __future__ import nested_scopes directive. In 2.2 nested scopes no longer need to be specially enabled, and are now always present. The rest of this section is a copy of the description of nested scopes from my "What's New in Python 2.1" document; if you read it when 2.1 came out, you can skip the rest of this section.
The largest change introduced in Python 2.1, and made complete in 2.2, is to Python's scoping rules. In Python 2.0, at any given time there are at most three namespaces used to look up variable names: local, module-level, and the built-in namespace. This often surprised people because it didn't match their intuitive expectations. For example, a nested recursive function definition doesn't work:
def f():
...
def g(value):
...
return g(value-1) + 1
...
The function !g will always raise a NameError exception, because the binding of the name g isn't in either its local namespace or in the module-level namespace. This isn't much of a problem in practice (how often do you recursively define interior functions like this?), but this also made using the lambda expression clumsier, and this was a problem in practice. In code which uses !lambda you can often find local variables being copied by passing them as the default values of arguments. :
def find(self, name):
"Return list of any entries equal to 'name'"
L = filter(lambda x, name=name: x == name,
self.list_attribute)
return L
The readability of Python code written in a strongly functional style suffers greatly as a result.
The most significant change to Python 2.2 is that static scoping has been added to the language to fix this problem. As a first effect, the name=name default argument is now unnecessary in the above example. Put simply, when a given variable name is not assigned a value within a function (by an assignment, or the def, class, or import statements), references to the variable will be looked up in the local namespace of the enclosing scope. A more detailed explanation of the rules, and a dissection of the implementation, can be found in the PEP.
This change may cause some compatibility problems for code where the same variable name is used both at the module level and as a local variable within a function that contains further function definitions. This seems rather unlikely though, since such code would have been pretty confusing to read in the first place.
One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception.
To make the preceding explanation a bit clearer, here's an example:
x = 1
def f():
# The next line is a syntax error
exec 'x=2'
def g():
return x
Line 4 containing the exec statement is a syntax error, since exec would define a new local variable named x whose value should be accessed by !g.
This shouldn't be much of a limitation, since exec is rarely used in most Python code (and when it is used, it's often a sign of a poor design anyway).
227 - Statically Nested Scopes
Written and implemented by Jeremy Hylton.
New and Improved Modules
-
The
xmlrpclib <xmlrpc.client>module was contributed to the standard library by Fredrik Lundh, providing support for writing XML-RPC clients. XML-RPC is a simple remote procedure call protocol built on top of HTTP and XML. For example, the following snippet retrieves a list of RSS channels from the O'Reilly Network, and then lists the recent headlines for one channel:import xmlrpclib s = xmlrpclib.Server( 'http://www.oreillynet.com/meerkat/xml-rpc/server.php') channels = s.meerkat.getChannels() # channels is a list of dictionaries, like this: # [{'id': 4, 'title': 'Freshmeat Daily News'} # {'id': 190, 'title': '32Bits Online'}, # {'id': 4549, 'title': '3DGamers'}, ... ] # Get the items for one channel items = s.meerkat.getItems( {'channel': 4} ) # 'items' is another list of dictionaries, like this: # [{'link': 'http://freshmeat.net/releases/52719/', # 'description': 'A utility which converts HTML to XSL FO.', # 'title': 'html2fo 0.3 (Default)'}, ... ]The
SimpleXMLRPCServer <xmlrpc.server>module makes it easy to create straightforward XML-RPC servers. See http://xmlrpc.scripting.com/ for more information about XML-RPC. -
The new
hmacmodule implements the HMAC algorithm described by2104. (Contributed by Gerhard Häring.) -
Several functions that originally returned lengthy tuples now return pseudo-sequences that still behave like tuples but also have mnemonic attributes such as
!memberst_mtimeor~time.struct_time.tm_year. The enhanced functions include~os.stat,~os.fstat,~os.statvfs, and~os.fstatvfsin theosmodule, and~time.localtime,~time.gmtime, and~time.strptimein thetimemodule.For example, to obtain a file's size using the old tuples, you'd end up writing something like
file_size = os.stat(filename)[stat.ST_SIZE], but now this can be written more clearly asfile_size = os.stat(filename).st_size.The original patch for this feature was contributed by Nick Mathewson.
-
The Python profiler has been extensively reworked and various errors in its output have been corrected. (Contributed by Fred L. Drake, Jr. and Tim Peters.)
-
The
socketmodule can be compiled to support IPv6; specify the!--enable-ipv6option to Python's configure script. (Contributed by Jun-ichiro "itojun" Hagino.) -
Two new format characters were added to the
structmodule for 64-bit integers on platforms that support the Clong longtype.qis for a signed 64-bit integer, andQis for an unsigned one. The value is returned in Python's long integer type. (Contributed by Tim Peters.) -
In the interpreter's interactive mode, there's a new built-in function
helpthat uses thepydocmodule introduced in Python 2.1 to provide interactive help.help(object)displays any available help text about object.helpwith no argument puts you in an online help utility, where you can enter the names of functions, classes, or modules to read their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee'spydocmodule.) -
Various bugfixes and performance improvements have been made to the SRE engine underlying the
remodule. For example, there.subandre.splitfunctions have been rewritten in C. Another contributed patch speeds up certain Unicode character ranges by a factor of two, and a new~re.finditermethod that returns an iterator over all the non-overlapping matches in a given string. (SRE is maintained by Fredrik Lundh. The BIGCHARSET patch was contributed by Martin von Löwis.) -
The
smtplibmodule now supports2487, "Secure SMTP over TLS", so it's now possible to encrypt the SMTP traffic between a Python program and the mail transport agent being handed a message.smtplibalso supports SMTP authentication. (Contributed by Gerhard Häring.) -
The
imaplibmodule, maintained by Piers Lauder, has support for several new extensions: the NAMESPACE extension defined in2342, SORT, GETACL and SETACL. (Contributed by Anthony Baxter and Michel Pelletier.) -
The
!rfc822module's parsing of email addresses is now compliant with2822, an update to822. (The module's name is not going to be changed torfc2822.) A new package,email, has also been added for parsing and generating e-mail messages. (Contributed by Barry Warsaw, and arising out of his work on Mailman.) -
The
difflibmodule now contains a new!Differclass for producing human-readable lists of changes (a "delta") between two sequences of lines of text. There are also two generator functions,!ndiffand!restore, which respectively return a delta from two sequences, or one of the original sequences from a delta. (Grunt work contributed by David Goodger, from ndiff.py code by Tim Peters who then did the generatorization.) -
New constants
!ascii_letters,!ascii_lowercase, and!ascii_uppercasewere added to thestringmodule. There were several modules in the standard library that used!string.lettersto mean the ranges A-Za-z, but that assumption is incorrect when locales are in use, because!string.lettersvaries depending on the set of legal characters defined by the current locale. The buggy modules have all been fixed to use!ascii_lettersinstead. (Reported by an unknown person; fixed by Fred L. Drake, Jr.) -
The
mimetypesmodule now makes it easier to use alternative MIME-type databases by the addition of a~mimetypes.MimeTypesclass, which takes a list of filenames to be parsed. (Contributed by Fred L. Drake, Jr.) -
A
~threading.Timerclass was added to thethreadingmodule that allows scheduling an activity to happen at some future time. (Contributed by Itamar Shtull-Trauring.)
Interpreter Changes and Fixes
Some of the changes only affect people who deal with the Python interpreter at the C level because they're writing Python extension modules, embedding the interpreter, or just hacking on the interpreter itself. If you only write Python code, none of the changes described here will affect you very much.
-
Profiling and tracing functions can now be implemented in C, which can operate at much higher speeds than Python-based functions and should reduce the overhead of profiling and tracing. This will be of interest to authors of development environments for Python. Two new C functions were added to Python's API,
PyEval_SetProfileandPyEval_SetTrace. The existingsys.setprofileandsys.settracefunctions still exist, and have simply been changed to use the new C-level interface. (Contributed by Fred L. Drake, Jr.) -
Another low-level API, primarily of interest to implementers of Python debuggers and development tools, was added.
PyInterpreterState_HeadandPyInterpreterState_Nextlet a caller walk through all the existing interpreter objects;PyInterpreterState_ThreadHeadandPyThreadState_Nextallow looping over all the thread states for a given interpreter. (Contributed by David Beazley.) -
The C-level interface to the garbage collector has been changed to make it easier to write extension types that support garbage collection and to debug misuses of the functions. Various functions have slightly different semantics, so a bunch of functions had to be renamed. Extensions that use the old API will still compile but will not participate in garbage collection, so updating them for 2.2 should be considered fairly high priority.
To upgrade an extension module to the new API, perform the following steps:
-
Rename
!Py_TPFLAGS_GCtoPy_TPFLAGS_HAVE_GC. -
Use
PyObject_GC_NeworPyObject_GC_NewVarto allocate objects, andPyObject_GC_Delto deallocate them. -
Rename
!PyObject_GC_InittoPyObject_GC_Trackand!PyObject_GC_FinitoPyObject_GC_UnTrack. -
Remove
!PyGC_HEAD_SIZEfrom object size calculations. -
Remove calls to
!PyObject_AS_GCand!PyObject_FROM_GC. -
A new
etformat sequence was added toPyArg_ParseTuple;ettakes both a parameter and an encoding name, and converts the parameter to the given encoding if the parameter turns out to be a Unicode string, or leaves it alone if it's an 8-bit string, assuming it to already be in the desired encoding. This differs from theesformat character, which assumes that 8-bit strings are in Python's default ASCII encoding and converts them to the specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS support on Windows described in the following section.) -
A different argument parsing function,
PyArg_UnpackTuple, has been added that's simpler and presumably faster. Instead of specifying a format string, the caller simply gives the minimum and maximum number of arguments expected, and a set of pointers toPyObject*variables that will be filled in with argument values. -
Two new flags
METH_NOARGSandMETH_Oare available in method definition tables to simplify implementation of methods with no arguments or a single untyped argument. Calling such methods is more efficient than calling a corresponding method that usesMETH_VARARGS. Also, the old!METH_OLDARGSstyle of writing C methods is now officially deprecated. -
Two new wrapper functions,
PyOS_snprintfandPyOS_vsnprintfwere added to provide cross-platform implementations for the relatively newsnprintfandvsnprintfC lib APIs. In contrast to the standardsprintfand!vsprintffunctions, the Python versions check the bounds of the buffer used to protect against buffer overruns. (Contributed by M.-A. Lemburg.) -
The
_PyTuple_Resizefunction has lost an unused parameter, so now it takes 2 parameters instead of 3. The third argument was never used, and can simply be discarded when porting code from earlier versions to Python 2.2.
Other Changes and Fixes
As usual there were a bunch of other improvements and bugfixes scattered throughout the source tree. A search through the CVS change logs finds there were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1 applied 139 patches and fixed 143 bugs; 2.2.2 applied 106 patches and fixed 82 bugs. These figures are likely to be underestimates.
Some of the more notable changes are:
-
The code for the MacOS port for Python, maintained by Jack Jansen, is now kept in the main Python CVS tree, and many changes have been made to support MacOS X.
The most significant change is the ability to build Python as a framework, enabled by supplying the
!--enable-frameworkoption to the configure script when compiling Python. According to Jack Jansen, "This installs a self-contained Python installation plus the OS X framework "glue" into/Library/Frameworks/Python.framework(or another location of choice). For now there is little immediate added benefit to this (actually, there is the disadvantage that you have to change your PATH to be able to find Python), but it is the basis for creating a full-blown Python application, porting the MacPython IDE, possibly using Python as a standard OSA scripting language and much more."Most of the MacPython toolbox modules, which interface to MacOS APIs such as windowing, QuickTime, scripting, etc. have been ported to OS X, but they've been left commented out in
setup.py. People who want to experiment with these modules can uncomment them manually. -
Keyword arguments passed to built-in functions that don't take them now cause a
TypeErrorexception to be raised, with the message "*function* takes no keyword arguments". -
Weak references, added in Python 2.1 as an extension module, are now part of the core because they're used in the implementation of new-style classes. The
ReferenceErrorexception has therefore moved from theweakrefmodule to become a built-in exception. -
A new script,
Tools/scripts/cleanfuture.pyby Tim Peters, automatically removes obsolete__future__statements from Python source code. -
An additional flags argument has been added to the built-in function
compile, so the behaviour of__future__statements can now be correctly observed in simulated shells, such as those presented by IDLE and other development environments. This is described in264. (Contributed by Michael Hudson.) -
The new license introduced with Python 1.6 wasn't GPL-compatible. This is fixed by some minor textual changes to the 2.2 license, so it's now legal to embed Python inside a GPLed program again. Note that Python itself is not GPLed, but instead is under a license that's essentially equivalent to the BSD license, same as it always was. The license changes were also applied to the Python 2.0.1 and 2.1.1 releases.
-
When presented with a Unicode filename on Windows, Python will now convert it to an MBCS encoded string, as used by the Microsoft file APIs. As MBCS is explicitly used by the file APIs, Python's choice of ASCII as the default encoding turns out to be an annoyance. On Unix, the locale's character set is used if
locale.nl_langinfo(CODESET)is available. (Windows support was contributed by Mark Hammond with assistance from Marc-André Lemburg. Unix support was added by Martin von Löwis.) -
Large file support is now enabled on Windows. (Contributed by Tim Peters.)
-
The
Tools/scripts/ftpmirror.pyscript now parses a.netrcfile, if you have one. (Contributed by Mike Romberg.) -
Some features of the object returned by the
!xrangefunction are now deprecated, and trigger warnings when they're accessed; they'll disappear in Python 2.3.!xrangeobjects tried to pretend they were full sequence types by supporting slicing, sequence multiplication, and theinoperator, but these features were rarely used and therefore buggy. The!tolistmethod and the!start,!stop, and!stepattributes are also being deprecated. At the C level, the fourth argument to the!PyRange_Newfunction,repeat, has also been deprecated. -
There were a bunch of patches to the dictionary implementation, mostly to fix potential core dumps if a dictionary contains objects that sneakily changed their hash value, or mutated the dictionary they were contained in. For a while python-dev fell into a gentle rhythm of Michael Hudson finding a case that dumped core, Tim Peters fixing the bug, Michael finding another case, and round and round it went.
-
On Windows, Python can now be compiled with Borland C thanks to a number of patches contributed by Stephen Hansen, though the result isn't fully functional yet. (But this is progress...)
-
Another Windows enhancement: Wise Solutions generously offered PythonLabs use of their InstallerMaster 8.1 system. Earlier PythonLabs Windows installers used Wise 5.0a, which was beginning to show its age. (Packaged up by Tim Peters.)
-
Files ending in
.pywcan now be imported on Windows..pywis a Windows-only thing, used to indicate that a script needs to be run using PYTHONW.EXE instead of PYTHON.EXE in order to prevent a DOS console from popping up to display the output. This patch makes it possible to import such scripts, in case they're also usable as modules. (Implemented by David Bolen.) -
On platforms where Python uses the C
dlopenfunction to load extension modules, it's now possible to set the flags used bydlopenusing thesys.getdlopenflagsandsys.setdlopenflagsfunctions. (Contributed by Bram Stolk.) -
The
powbuilt-in function no longer supports 3 arguments when floating-point numbers are supplied.pow(x, y, z)returns(x**y) % z, but this is never useful for floating-point numbers, and the final result varies unpredictably depending on the platform. A call such aspow(2.0, 8.0, 7.0)will now raise aTypeErrorexception.
Acknowledgements
What's New in Python 2.3
This article explains the new features in Python 2.3. Python 2.3 was released on July 29, 2003.
The main themes for Python 2.3 are polishing some of the features added in 2.2, adding various small but useful enhancements to the core language, and expanding the standard library. The new object model introduced in the previous version has benefited from 18 months of bugfixes and from optimization efforts that have improved the performance of new-style classes. A few new built-in functions have been added such as sum and enumerate. The in operator can now be used for substring searches (e.g. "ab" in "abc" returns True).
Some of the many new library features include Boolean, set, heap, and date/time data types, the ability to import modules from ZIP-format archives, metadata support for the long-awaited Python catalog, an updated version of IDLE, and modules for logging messages, wrapping text, parsing CSV files, processing command-line options, using BerkeleyDB databases... the list of new and enhanced modules is lengthy.
This article doesn't attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.3, such as the Python Library Reference and the Python Reference Manual. If you want to understand the complete implementation and design rationale, refer to the PEP for a particular new feature.
PEP 218: A Standard Set Datatype
The new !sets module contains an implementation of a set datatype. The Set class is for mutable sets, sets that can have members added and removed. The !ImmutableSet class is for sets that can't be modified, and instances of !ImmutableSet can therefore be used as dictionary keys. Sets are built on top of dictionaries, so the elements within a set must be hashable.
Here's a simple example:
>>> import sets
>>> S = sets.Set([1,2,3])
>>> S
Set([1, 2, 3])
>>> 1 in S
True
>>> 0 in S
False
>>> S.add(5)
>>> S.remove(3)
>>> S
Set([1, 2, 5])
>>>
The union and intersection of sets can be computed with the ~frozenset.union and ~frozenset.intersection methods; an alternative notation uses the bitwise operators & and |. Mutable sets also have in-place versions of these methods, !union_update and ~set.intersection_update. :
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([4,5,6])
>>> S1.union(S2)
Set([1, 2, 3, 4, 5, 6])
>>> S1 | S2 # Alternative notation
Set([1, 2, 3, 4, 5, 6])
>>> S1.intersection(S2)
Set([])
>>> S1 & S2 # Alternative notation
Set([])
>>> S1.union_update(S2)
>>> S1
Set([1, 2, 3, 4, 5, 6])
>>>
It's also possible to take the symmetric difference of two sets. This is the set of all elements in the union that aren't in the intersection. Another way of putting it is that the symmetric difference contains all elements that are in exactly one set. Again, there's an alternative notation (^), and an in-place version with the ungainly name ~set.symmetric_difference_update. :
>>> S1 = sets.Set([1,2,3,4])
>>> S2 = sets.Set([3,4,5,6])
>>> S1.symmetric_difference(S2)
Set([1, 2, 5, 6])
>>> S1 ^ S2
Set([1, 2, 5, 6])
>>>
There are also !issubset and !issuperset methods for checking whether one set is a subset or superset of another:
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([2,3])
>>> S2.issubset(S1)
True
>>> S1.issubset(S2)
False
>>> S1.issuperset(S2)
True
>>>
218 - Adding a Built-In Set Object Type
PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and GvR.
PEP 255: Simple Generators
In Python 2.2, generators were added as an optional feature, to be enabled by a from __future__ import generators directive. In 2.3 generators no longer need to be specially enabled, and are now always present; this means that yield is now always a keyword. The rest of this section is a copy of the description of generators from the "What's New in Python 2.2" document; if you read it back when Python 2.2 came out, you can skip the rest of this section.
You're doubtless familiar with how function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a return statement, the local variables are destroyed and the resulting value is returned to the caller. A later call to the same function will get a fresh new set of local variables. But, what if the local variables weren't thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.
Here's the simplest example of a generator function:
def generate_ints(N):
for i in range(N):
yield i
A new keyword, yield, was introduced for generators. Any function containing a !yield statement is a generator function; this is detected by Python's bytecode compiler which compiles the function specially as a result.
When you call a generator function, it doesn't return a single value; instead it returns a generator object that supports the iterator protocol. On executing the yield statement, the generator outputs the value of i, similar to a return statement. The big difference between !yield and a !return statement is that on reaching a !yield the generator's state of execution is suspended and local variables are preserved. On the next call to the generator's .next() method, the function will resume executing immediately after the !yield statement. (For complicated reasons, the !yield statement isn't allowed inside the try block of a !try...!finally statement; read 255 for a full explanation of the interaction between !yield and exceptions.)
Here's a sample usage of the !generate_ints generator:
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
File "stdin", line 1, in ?
File "stdin", line 2, in generate_ints
StopIteration
You could equally write for i in generate_ints(5), or a,b,c = generate_ints(3).
Inside a generator function, the return statement can only be used without a value, and signals the end of the procession of values; afterwards the generator cannot return any further values. !return with a value, such as return 5, is a syntax error inside a generator function. The end of the generator's results can also be indicated by raising StopIteration manually, or by just letting the flow of execution fall off the bottom of the function.
You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting self.count to 0, and having the next method increment self.count and return it. However, for a moderately complicated generator, writing a corresponding class would be much messier. Lib/test/test_generators.py contains a number of more interesting examples. The simplest one implements an in-order traversal of a tree using generators recursively. :
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
Two other examples in Lib/test/test_generators.py produce solutions for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no queen threatens another) and the Knight's Tour (a route that takes a knight to every square of an $NxN$ chessboard without visiting any square twice).
The idea of generators comes from other programming languages, especially Icon (https://www2.cs.arizona.edu/icon/), where the idea of generators is central. In Icon, every expression and function call behaves like a generator. One example from "An Overview of the Icon Programming Language" at https://www2.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks like:
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
In Icon the !find function returns the indexes at which the substring "or" is found: 3, 23, 33. In the if statement, i is first assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon retries it with the second value of 23. 23 is greater than 5, so the comparison now succeeds, and the code prints the value 23 to the screen.
Python doesn't go nearly as far as Icon in adopting generators as a central concept. Generators are considered part of the core Python language, but learning or using them isn't compulsory; if they don't solve any problems that you have, feel free to ignore them. One novel feature of Python's interface as compared to Icon's is that a generator's state is represented as a concrete object (the iterator) that can be passed around to other functions or stored in a data structure.
255 - Simple Generators
Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
PEP 263: Source Code Encodings
Python source files can now be declared as being in different character set encodings. Encodings are declared by including a specially formatted comment in the first or second line of the source file. For example, a UTF-8 file can be declared with:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
Without such an encoding declaration, the default encoding used is 7-bit ASCII. Executing or importing modules that contain string literals with 8-bit characters and have no encoding declaration will result in a DeprecationWarning being signalled by Python 2.3; in 2.4 this will be a syntax error.
The encoding declaration only affects Unicode string literals, which will be converted to Unicode using the specified encoding. Note that Python identifiers are still restricted to ASCII characters, so you can't have variable names that use characters outside of the usual alphanumerics.
263 - Defining Python Source Code Encodings
Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao and Martin von Löwis.
PEP 273: Importing Modules from ZIP Archives
The new zipimport module adds support for importing modules from a ZIP-format archive. You don't need to import the module explicitly; it will be automatically imported if a ZIP archive's filename is added to sys.path. For example:
amk@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive: /tmp/example.zip
Length Date Time Name
-------- ---- ---- ----
8467 11-26-02 22:30 jwzthreading.py
-------- -------
8467 1 file
amk@nyman:~/src/python$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
>>>
An entry in sys.path can now be the filename of a ZIP archive. The ZIP archive can contain any kind of files, but only files named \*.py, \*.pyc, or \*.pyo can be imported. If an archive only contains \*.py files, Python will not attempt to modify the archive by adding the corresponding \*.pyc file, meaning that if a ZIP archive doesn't contain \*.pyc files, importing may be rather slow.
A path within the archive can also be specified to only import from a subdirectory; for example, the path /tmp/example.zip/lib/ would only import from the lib/ subdirectory within the archive.
273 - Import Modules from Zip Archives
Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in 273, but uses an implementation written by Just van Rossum that uses the import hooks described in 302. See section section-pep302 for a description of the new import hooks.
PEP 277: Unicode file name support for Windows NT
On Windows NT, 2000, and XP, the system stores file names as Unicode strings. Traditionally, Python has represented file names as byte strings, which is inadequate because it renders some file names inaccessible.
Python now allows using arbitrary Unicode strings (within the limitations of the file system) for all functions that expect file names, most notably the open built-in function. If a Unicode string is passed to os.listdir, Python now returns a list of Unicode strings. A new function, !os.getcwdu, returns the current directory as a Unicode string.
Byte strings still work as file names, and on Windows Python will transparently convert them to Unicode using the mbcs encoding.
Other systems also allow Unicode strings as file names but convert them to byte strings before passing them to the system, which can cause a UnicodeError to be raised. Applications can test whether arbitrary Unicode strings are supported as file names by checking os.path.supports_unicode_filenames, a Boolean value.
Under MacOS, os.listdir may now return Unicode filenames.
277 - Unicode file name support for Windows NT
Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark Hammond.
single: universal newlines; What's new
PEP 278: Universal Newline Support
The three major operating systems used today are Microsoft Windows, Apple's Macintosh OS, and the various Unix derivatives. A minor irritation of cross-platform work is that these three platforms all use different characters to mark the ends of lines in text files. Unix uses the linefeed (ASCII character 10), MacOS uses the carriage return (ASCII character 13), and Windows uses a two-character sequence of a carriage return plus a newline.
Python's file objects can now support end of line conventions other than the one followed by the platform on which Python is running. Opening a file with the mode 'U' or 'rU' will open a file for reading in universal newlines mode. All three line ending conventions will be translated to a '\n' in the strings returned by the various file methods such as !read and !readline.
Universal newline support is also used when importing modules and when executing a file with the !execfile function. This means that Python modules can be shared between all three operating systems without needing to convert the line-endings.
This feature can be disabled when compiling Python by specifying the !--without-universal-newlines switch when running Python's configure script.
278 - Universal Newline Support
Written and implemented by Jack Jansen.
PEP 279: enumerate()
A new built-in function, enumerate, will make certain loops a bit clearer. enumerate(thing), where thing is either an iterator or a sequence, returns an iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth.
A common idiom to change every element of a list looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
279 - The enumerate() built-in function
Written and implemented by Raymond D. Hettinger.
PEP 282: The logging Package
A standard package for writing logs, logging, has been added to Python 2.3. It provides a powerful and flexible mechanism for generating logging output which can then be filtered and processed in various ways. A configuration file written in a standard format can be used to control the logging behavior of a program. Python includes handlers that will write log records to standard error or to a file or socket, send them to the system log, or even e-mail them to a particular address; of course, it's also possible to write your own handler classes.
The ~logging.Logger class is the primary class. Most application code will deal with one or more ~logging.Logger objects, each one used by a particular subsystem of the application. Each ~logging.Logger is identified by a name, and names are organized into a hierarchy using . as the component separator. For example, you might have ~logging.Logger instances named server, server.auth and server.network. The latter two instances are below server in the hierarchy. This means that if you turn up the verbosity for server or direct server messages to a different handler, the changes will also apply to records logged to server.auth and server.network. There's also a root ~logging.Logger that's the parent of all other loggers.
For simple uses, the logging package contains some convenience functions that always use the root log:
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
This produces the following output:
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
In the default configuration, informational and debugging messages are suppressed and the output is sent to standard error. You can enable the display of informational and debugging messages by calling the ~logging.Logger.setLevel method on the root logger.
Notice the ~logging.warning call's use of string formatting operators; all of the functions for logging messages take the arguments (msg, arg1, arg2, ...) and log the string resulting from msg % (arg1, arg2, ...).
There's also an ~logging.exception function that records the most recent traceback. Any of the other functions will also record the traceback if you specify a true value for the keyword argument exc_info. :
def f():
try: 1/0
except: logging.exception('Problem recorded')
f()
This produces the following output:
ERROR:root:Problem recorded
Traceback (most recent call last):
File "t.py", line 6, in f
1/0
ZeroDivisionError: integer division or modulo by zero
Slightly more advanced programs will use a logger other than the root logger. The getLogger(name) function is used to get a particular log, creating it if it doesn't exist yet. getLogger(None) returns the root logger. :
log = logging.getLogger('server')
...
log.info('Listening on port %i', port)
...
log.critical('Disk full')
...
Log records are usually propagated up the hierarchy, so a message logged to server.auth is also seen by server and root, but a ~logging.Logger can prevent this by setting its ~logging.Logger.propagate attribute to False.
There are more classes provided by the logging package that can be customized. When a ~logging.Logger instance is told to log a message, it creates a ~logging.LogRecord instance that is sent to any number of different ~logging.Handler instances. Loggers and handlers can also have an attached list of filters, and each filter can cause the ~logging.LogRecord to be ignored or can modify the record before passing it along. When they're finally output, ~logging.LogRecord instances are converted to text by a ~logging.Formatter class. All of these classes can be replaced by your own specially written classes.
With all of these features the logging package should provide enough flexibility for even the most complicated applications. This is only an incomplete overview of its features, so please see the package's reference documentation for all of the details. Reading 282 will also be helpful.
282 - A Logging System
Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.
PEP 285: A Boolean Type
A Boolean type was added to Python 2.3. Two new constants were added to the !__builtin__ module, True and False. (True and False constants were added to the built-ins in Python 2.2.1, but the 2.2.1 versions are simply set to integer values of 1 and 0 and aren't a different type.)
The type object for this new type is named bool; the constructor for it takes any Python value and converts it to True or False. :
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool( (1,) )
True
Most of the standard library modules and built-in functions have been changed to return Booleans. :
>>> obj = []
>>> hasattr(obj, 'append')
True
>>> isinstance(obj, list)
True
>>> isinstance(obj, tuple)
False
Python's Booleans were added with the primary goal of making code clearer. For example, if you're reading a function and encounter the statement return 1, you might wonder whether the 1 represents a Boolean truth value, an index, or a coefficient that multiplies some other quantity. If the statement is return True, however, the meaning of the return value is quite clear.
Python's Booleans were not added for the sake of strict type-checking. A very strict language such as Pascal would also prevent you performing arithmetic with Booleans, and would require that the expression in an if statement always evaluate to a Boolean result. Python is not this strict and never will be, as 285 explicitly says. This means you can still use any expression in an !if statement, even ones that evaluate to a list or tuple or some random object. The Boolean type is a subclass of the int class so that arithmetic using a Boolean still works. :
>>> True + 1
2
>>> False + 1
1
>>> False * 75
0
>>> True * 75
75
To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str and repr return the strings 'True' and 'False' instead of '1' and '0'.
285 - Adding a bool type
Written and implemented by GvR.
PEP 293: Codec Error Handling Callbacks
When encoding a Unicode string into a byte string, unencodable characters may be encountered. So far, Python has allowed specifying the error processing as either "strict" (raising UnicodeError), "ignore" (skipping the character), or "replace" (using a question mark in the output string), with "strict" being the default behavior. It may be desirable to specify alternative processing of such errors, such as inserting an XML character reference or HTML entity reference into the converted string.
Python now has a flexible framework to add different processing strategies. New error handlers can be added with codecs.register_error, and codecs then can access the error handler with codecs.lookup_error. An equivalent C API has been added for codecs written in C. The error handler gets the necessary state information such as the string being converted, the position in the string where the error was detected, and the target encoding. The handler can then either raise an exception or return a replacement string.
Two additional error handlers have been implemented using this framework: "backslashreplace" uses Python backslash quoting to represent unencodable characters and "xmlcharrefreplace" emits XML character references.
293 - Codec Error Handling Callbacks
Written and implemented by Walter Dörwald.
PEP 301: Package Index and Metadata for Distutils
Support for the long-requested Python catalog makes its first appearance in 2.3.
The heart of the catalog is the new Distutils register command. Running python setup.py register will collect the metadata describing a package, such as its name, version, maintainer, description, &c., and send it to a central catalog server. The resulting catalog is available from https://pypi.org.
To make the catalog a bit more useful, a new optional classifiers keyword argument has been added to the Distutils !setup function. A list of Trove-style strings can be supplied to help classify the software.
Here's an example setup.py with classifiers, written to be compatible with older versions of the Distutils:
from distutils import core
kw = {'name': "Quixote",
'version': "0.5.1",
'description': "A highly Pythonic Web application framework",
# ...
}
if (hasattr(core, 'setup_keywords') and
'classifiers' in core.setup_keywords):
kw['classifiers'] = \
['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: Developers'],
core.setup(**kw)
The full list of classifiers can be obtained by running python setup.py register --list-classifiers.
301 - Package Index and Metadata for Distutils
Written and implemented by Richard Jones.
PEP 302: New Import Hooks
While it's been possible to write custom import hooks ever since the !ihooks module was introduced in Python 1.3, no one has ever been really happy with it because writing new import hooks is difficult and messy. There have been various proposed alternatives such as the !imputil and !iu modules, but none of them has ever gained much acceptance, and none of them were easily usable from C code.
302 borrows ideas from its predecessors, especially from Gordon McMillan's !iu module. Three new items are added to the sys module:
sys.path_hooksis a list of callable objects; most often they'll be classes. Each callable takes a string containing a path and either returns an importer object that will handle imports from this path or raises anImportErrorexception if it can't handle this path.sys.path_importer_cachecaches importer objects for each path, sosys.path_hookswill only need to be traversed once for each path.sys.meta_pathis a list of importer objects that will be traversed beforesys.pathis checked. This list is initially empty, but user code can add objects to it. Additional built-in and frozen modules can be imported by an object added to this list.
Importer objects must have a single method, find_module(fullname, path=None). fullname will be a module or package name, e.g. string or distutils.core. !find_module must return a loader object that has a single method, load_module(fullname), that creates and returns the corresponding module object.
Pseudo-code for Python's new import logic, therefore, looks something like this (simplified a bit; see 302 for the full details):
for mp in sys.meta_path:
loader = mp(fullname)
if loader is not None:
<module> = loader.load_module(fullname)
for path in sys.path:
for hook in sys.path_hooks:
try:
importer = hook(path)
except ImportError:
# ImportError, so try the other path hooks
pass
else:
loader = importer.find_module(fullname)
<module> = loader.load_module(fullname)
# Not found!
raise ImportError
302 - New Import Hooks
Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.
PEP 305: Comma-separated Files
Comma-separated files are a format frequently used for exporting data from databases and spreadsheets. Python 2.3 adds a parser for comma-separated files.
Comma-separated format is deceptively simple at first glance:
Costs,150,200,3.95
Read a line and call line.split(','): what could be simpler? But toss in string data that can contain commas, and things get more complicated:
"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
A big ugly regular expression can parse this, but using the new csv package is much simpler:
import csv
input = open('datafile', 'rb')
reader = csv.reader(input)
for line in reader:
print line
The ~csv.reader function takes a number of different options. The field separator isn't limited to the comma and can be changed to any character, and so can the quoting and line-ending characters.
Different dialects of comma-separated files can be defined and registered; currently there are two dialects, both used by Microsoft Excel. A separate csv.writer class will generate comma-separated files from a succession of tuples or lists, quoting strings that contain the delimiter.
305 - CSV File API
Written and implemented by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
PEP 307: Pickle Enhancements
The pickle and !cPickle modules received some attention during the 2.3 development cycle. In 2.2, new-style classes could be pickled without difficulty, but they weren't pickled very compactly; 307 quotes a trivial example where a new-style class results in a pickled string three times longer than that for a classic class.
The solution was to invent a new pickle protocol. The pickle.dumps function has supported a text-or-binary flag for a long time. In 2.3, this flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle format, 1 is the old binary format, and now 2 is a new 2.3-specific format. A new constant, pickle.HIGHEST_PROTOCOL, can be used to select the fanciest protocol available.
Unpickling is no longer considered a safe operation. 2.2's pickle provided hooks for trying to prevent unsafe classes from being unpickled (specifically, a !__safe_for_unpickling__ attribute), but none of this code was ever audited and therefore it's all been ripped out in 2.3. You should not unpickle untrusted data in any version of Python.
To reduce the pickling overhead for new-style classes, a new interface for customizing pickling was added using three special methods: ~object.__getstate__, ~object.__setstate__, and ~object.__getnewargs__. Consult 307 for the full semantics of these methods.
As a way to compress pickles yet further, it's now possible to use integer codes instead of long strings to identify pickled classes. The Python Software Foundation will maintain a list of standardized codes; there's also a range of codes for private use. Currently no codes have been specified.
307 - Extensions to the pickle protocol
Written and implemented by Guido van Rossum and Tim Peters.
Extended Slices
Ever since Python 1.4, the slicing syntax has supported an optional third "step" or "stride" argument. For example, these are all legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. Michael Hudson contributed a patch to fix this shortcoming.
For example, you can now easily extract the elements of a list that have even indexes:
>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
Negative values also work to make a copy of the same list in reverse order:
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
This also works for tuples, arrays, and strings:
>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'
If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence:
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]
Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Deletion is more straightforward:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
One can also now pass slice objects to the ~object.__getitem__ methods of the built-in sequences:
>>> range(10).__getitem__(slice(0, 5, 2))
[0, 2, 4]
Or use slice objects directly in subscripts:
>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]
To simplify implementing sequences that support extended slicing, slice objects now have a method indices(length) which, given the length of a sequence, returns a (start, stop, step) tuple that can be passed directly to range. !indices handles omitted and out-of-bounds indices in a manner consistent with regular slices (and this innocuous phrase hides a welter of confusing details!). The method is intended to be used like this:
class FakeSeq:
...
def calc_item(self, i):
...
def __getitem__(self, item):
if isinstance(item, slice):
indices = item.indices(len(self))
return FakeSeq([self.calc_item(i) for i in range(*indices)])
else:
return self.calc_item(i)
From this example you can also see that the built-in slice object is now the type object for the slice type, and is no longer a function. This is consistent with Python 2.2, where int, str, etc., underwent the same change.
Other Language Changes
Here are all of the changes that Python 2.3 makes to the core Python language.
-
The
yieldstatement is now always a keyword, as described in sectionsection-generatorsof this document. -
A new built-in function
enumeratewas added, as described in sectionsection-enumerateof this document. -
Two new constants,
TrueandFalsewere added along with the built-inbooltype, as described in sectionsection-boolof this document. -
The
inttype constructor will now return a long integer instead of raising anOverflowErrorwhen a string or floating-point number is too large to fit into an integer. This can lead to the paradoxical result thatisinstance(int(expression), int)is false, but that seems unlikely to cause problems in practice. -
Built-in types now support the extended slicing syntax, as described in section
section-slicesof this document. -
A new built-in function,
sum(iterable, start=0), adds up the numeric items in the iterable object and returns their sum.sumonly accepts numbers, meaning that you can't use it to concatenate a bunch of strings. (Contributed by Alex Martelli.) -
list.insert(pos, value)used to insert value at the front of the list when pos was negative. The behaviour has now been changed to be consistent with slice indexing, so when pos is -1 the value will be inserted before the last element, and so forth. -
list.index(value), which searches for value within the list and returns its index, now takes optional start and stop arguments to limit the search to only part of the list. -
Dictionaries have a new method,
pop(key[, *default*]), that returns the value corresponding to key and removes that key/value pair from the dictionary. If the requested key isn't present in the dictionary, default is returned if it's specified andKeyErrorraised if it isn't. :>>> d = {1:2} >>> d {1: 2} >>> d.pop(4) Traceback (most recent call last): File "stdin", line 1, in ? KeyError: 4 >>> d.pop(1) 2 >>> d.pop(1) Traceback (most recent call last): File "stdin", line 1, in ? KeyError: 'pop(): dictionary is empty' >>> d {} >>>There's also a new class method,
dict.fromkeys(iterable, value), that creates a dictionary with keys taken from the supplied iterator iterable and all values set to value, defaulting toNone.(Patches contributed by Raymond Hettinger.)
Also, the
dictconstructor now accepts keyword arguments to simplify creating small dictionaries:>>> dict(red=1, blue=2, green=3, black=4) {'blue': 2, 'black': 4, 'green': 3, 'red': 1}(Contributed by Just van Rossum.)
-
The
assertstatement no longer checks the__debug__flag, so you can no longer disable assertions by assigning to__debug__. Running Python with the-Oswitch will still generate code that doesn't execute any assertions. -
Most type objects are now callable, so you can use them to create new objects such as functions, classes, and modules. (This means that the
!newmodule can be deprecated in a future Python version, because you can now use the type objects available in thetypesmodule.) For example, you can create a new module object with the following code:>>> import types >>> m = types.ModuleType('abc','docstring') >>> m <module 'abc' (built-in)> >>> m.__doc__ 'docstring' -
A new warning,
PendingDeprecationWarningwas added to indicate features which are in the process of being deprecated. The warning will not be printed by default. To check for use of features that will be deprecated in the future, supply-Walways::PendingDeprecationWarning:: <-W>on the command line or usewarnings.filterwarnings. -
The process of deprecating string-based exceptions, as in
raise "Error occurred", has begun. Raising a string will now triggerPendingDeprecationWarning. -
Using
Noneas a variable name will now result in aSyntaxWarningwarning. In a future version of Python,Nonemay finally become a keyword. -
The
!xreadlinesmethod of file objects, introduced in Python 2.1, is no longer necessary because files now behave as their own iterator.!xreadlineswas originally introduced as a faster way to loop over all the lines in a file, but now you can simply writefor line in file_obj. File objects also have a new read-only!encodingattribute that gives the encoding used by the file; Unicode strings written to the file will be automatically converted to bytes using the given encoding. -
The method resolution order used by new-style classes has changed, though you'll only notice the difference if you have a really complicated inheritance hierarchy. Classic classes are unaffected by this change. Python 2.2 originally used a topological sort of a class's ancestors, but 2.3 now uses the C3 algorithm as described in the paper "A Monotonic Superclass Linearization for Dylan". To understand the motivation for this change, read Michele Simionato's article
python_2.3_mro, or read the thread on python-dev starting with the message at https://mail.python.org/pipermail/python-dev/2002-October/029035.html. Samuele Pedroni first pointed out the problem and also implemented the fix by coding the C3 algorithm. -
Python runs multithreaded programs by switching between threads after executing N bytecodes. The default value for N has been increased from 10 to 100 bytecodes, speeding up single-threaded applications by reducing the switching overhead. Some multithreaded applications may suffer slower response time, but that's easily fixed by setting the limit back to a lower number using
sys.setcheckinterval(N). The limit can be retrieved with the new!sys.getcheckintervalfunction. -
One minor but far-reaching change is that the names of extension types defined by the modules included with Python now contain the module and a
'.'in front of the type name. For example, in Python 2.2, if you created a socket and printed its!__class__, you'd get this output:>>> s = socket.socket() >>> s.__class__ <type 'socket'>In 2.3, you get this:
>>> s.__class__ <type '_socket.socket'> -
One of the noted incompatibilities between old- and new-style classes has been removed: you can now assign to the
~type.__name__and~type.__bases__attributes of new-style classes. There are some restrictions on what can be assigned to!__bases__along the lines of those relating to assigning to an instance's~object.__class__attribute.
String Changes
-
The
inoperator now works differently for strings. Previously, when evaluatingX in Ywhere X and Y are strings, X could only be a single character. That's now changed; X can be a string of any length, andX in Ywill returnTrueif X is a substring of Y. If X is the empty string, the result is alwaysTrue. :>>> 'ab' in 'abcd' True >>> 'ad' in 'abcd' False >>> '' in 'abcd' TrueNote that this doesn't tell you where the substring starts; if you need that information, use the
~str.findstring method. -
The
~str.strip,~str.lstrip, and~str.rstripstring methods now have an optional argument for specifying the characters to strip. The default is still to remove all whitespace characters:>>> ' abc '.strip() 'abc' >>> '><><abc<><><>'.strip('<>') 'abc' >>> '><><abc<><><>\n'.strip('<>') 'abc<><><>\n' >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000') u'\u4001abc' >>>(Suggested by Simon Brunning and implemented by Walter Dörwald.)
-
The
~str.startswithand~str.endswithstring methods now accept negative numbers for the start and end parameters. -
Another new string method is
~str.zfill, originally a function in thestringmodule.~str.zfillpads a numeric string with zeros on the left until it's the specified width. Note that the%operator is still more flexible and powerful than~str.zfill. :>>> '45'.zfill(4) '0045' >>> '12345'.zfill(4) '12345' >>> 'goofy'.zfill(6) '0goofy'(Contributed by Walter Dörwald.)
-
A new type object,
!basestring, has been added. Both 8-bit strings and Unicode strings inherit from this type, soisinstance(obj, basestring)will returnTruefor either kind of string. It's a completely abstract type, so you can't create!basestringinstances. -
Interned strings are no longer immortal and will now be garbage-collected in the usual way when the only reference to them is from the internal dictionary of interned strings. (Implemented by Oren Tirosh.)
Optimizations
- The creation of new-style class instances has been made much faster; they're now faster than classic classes!
- The
~list.sortmethod of list objects has been extensively rewritten by Tim Peters, and the implementation is significantly faster. - Multiplication of large long integers is now much faster thanks to an implementation of Karatsuba multiplication, an algorithm that scales better than the O(n2) required for the grade-school multiplication algorithm. (Original patch by Christopher A. Craig, and significantly reworked by Tim Peters.)
- The
SET_LINENOopcode is now gone. This may provide a small speed increase, depending on your compiler's idiosyncrasies. See section23section-otherfor a longer explanation. (Removed by Michael Hudson.) !xrangeobjects now have their own iterator, makingfor i in xrange(n)slightly faster thanfor i in range(n). (Patch by Raymond Hettinger.)- A number of small rearrangements have been made in various hotspots to improve performance, such as inlining a function or removing some code. (Implemented mostly by GvR, but lots of people have contributed single changes.)
The net result of the 2.3 optimizations is that Python 2.3 runs the pystone benchmark around 25% faster than Python 2.2.
New, Improved, and Deprecated Modules
As usual, Python's standard library received a number of enhancements and bug fixes. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the CVS logs for all the details.
-
The
arraymodule now supports arrays of Unicode characters using the'u'format character. Arrays also now support using the+=assignment operator to add another array's contents, and the*=assignment operator to repeat an array. (Contributed by Jason Orendorff.) -
The
!bsddbmodule has been replaced by version 4.1.6 of the PyBSDDB package, providing a more complete interface to the transactional features of the BerkeleyDB library.The old version of the module has been renamed to
!bsddb185and is no longer built automatically; you'll have to editModules/Setupto enable it. Note that the new!bsddbpackage is intended to be compatible with the old module, so be sure to file bugs if you discover any incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled with a new version of the underlying BerkeleyDB library, you will almost certainly have to convert your database files to the new version. You can do this fairly easily with the new scriptsdb2pickle.pyandpickle2db.pywhich you will find in the distribution'sTools/scriptsdirectory. If you've already been using the PyBSDDB package and importing it as!bsddb3, you will have to change yourimportstatements to import it as!bsddb. -
The new
bz2module is an interface to the bz2 data compression library. bz2-compressed data is usually smaller than correspondingzlib-compressed data. (Contributed by Gustavo Niemeyer.) -
A set of standard date/time types has been added in the new
datetimemodule. See the following section for more details. -
The Distutils
!Extensionclass now supports an extra constructor argument named depends for listing additional source files that an extension depends on. This lets Distutils recompile the module if any of the dependency files are modified. For example, ifsampmodule.cincludes the header filesample.h, you would create the!Extensionobject like this:ext = Extension("samp", sources=["sampmodule.c"], depends=["sample.h"])Modifying
sample.hwould then cause the module to be recompiled. (Contributed by Jeremy Hylton.) -
Other minor changes to Distutils: it now checks for the
CC,CFLAGS,!CPP,LDFLAGS, andCPPFLAGSenvironment variables, using them to override the settings in Python's configuration (contributed by Robert Weber). -
Previously the
doctestmodule would only search the docstrings of public methods and functions for test cases, but it now also examines private ones as well. The~doctest.DocTestSuitefunction creates aunittest.TestSuiteobject from a set ofdoctesttests. -
The new
gc.get_referents(object)function returns a list of all the objects referenced by object. -
The
getoptmodule gained a new function,~getopt.gnu_getopt, that supports the same arguments as the existing~getopt.getoptfunction but uses GNU-style scanning mode. The existing~getopt.getoptstops processing options as soon as a non-option argument is encountered, but in GNU-style mode processing continues, meaning that options and arguments can be mixed. For example:>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v') ([('-f', 'filename')], ['output', '-v']) >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v') ([('-f', 'filename'), ('-v', '')], ['output'])(Contributed by Peter Åstrand.)
-
The
grp,pwd, andresourcemodules now return enhanced tuples:>>> import grp >>> g = grp.getgrnam('amk') >>> g.gr_name, g.gr_gid ('amk', 500) -
The
gzipmodule can now handle files exceeding 2 GiB. -
The new
heapqmodule contains an implementation of a heap queue algorithm. A heap is an array-like data structure that keeps items in a partially sorted order such that, for every index k,heap[k] <= heap[2*k+1]andheap[k] <= heap[2*k+2]. This makes it quick to remove the smallest item, and inserting a new item while maintaining the heap property is O(log n). (See https://xlinux.nist.gov/dads//HTML/priorityque.html for more information about the priority queue data structure.)The
heapqmodule provides~heapq.heappushand~heapq.heappopfunctions for adding and removing items while maintaining the heap property on top of some other mutable Python sequence type. Here's an example that uses a Python list:>>> import heapq >>> heap = [] >>> for item in [3, 7, 5, 11, 1]: ... heapq.heappush(heap, item) ... >>> heap [1, 3, 5, 11, 7] >>> heapq.heappop(heap) 1 >>> heapq.heappop(heap) 3 >>> heap [5, 7, 11](Contributed by Kevin O'Connor.)
-
The IDLE integrated development environment has been updated using the code from the IDLEfork project (https://idlefork.sourceforge.net). The most notable feature is that the code being developed is now executed in a subprocess, meaning that there's no longer any need for manual
reload()operations. IDLE's core code has been incorporated into the standard library as theidlelibpackage. -
The
imaplibmodule now supports IMAP over SSL. (Contributed by Piers Lauder and Tino Lange.) -
The
itertoolscontains a number of useful functions for use with iterators, inspired by various functions provided by the ML and Haskell languages. For example,itertools.ifilter(predicate, iterator)returns all elements in the iterator for which the function!predicatereturnsTrue, anditertools.repeat(obj, N)returnsobjN times. There are a number of other functions in the module; see the package's reference documentation for details. (Contributed by Raymond Hettinger.) -
Two new functions in the
mathmodule,degrees(rads)andradians(degs), convert between radians and degrees. Other functions in themathmodule such asmath.sinandmath.coshave always required input values measured in radians. Also, an optional base argument was added tomath.logto make it easier to compute logarithms for bases other thaneand10. (Contributed by Raymond Hettinger.) -
Several new POSIX functions (
!getpgid,!killpg,!lchown,!loadavg,!major,!makedev,!minor, and!mknod) were added to theposixmodule that underlies theosmodule. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.) -
In the
osmodule, the!\*statfamily of functions can now report fractions of a second in a timestamp. Such time stamps are represented as floats, similar to the value returned bytime.time.During testing, it was found that some applications will break if time stamps are floats. For compatibility, when using the tuple interface of the
~os.stat_resulttime stamps will be represented as integers. When using named fields (a feature first introduced in Python 2.2), time stamps are still represented as integers, unless!os.stat_float_timesis invoked to enable float return values:>>> os.stat("/tmp").st_mtime 1034791200 >>> os.stat_float_times(True) >>> os.stat("/tmp").st_mtime 1034791200.6335014In Python 2.4, the default will change to always returning floats.
Application developers should enable this feature only if all their libraries work properly when confronted with floating-point time stamps, or if they use the tuple API. If used, the feature should be activated on an application level instead of trying to enable it on a per-use basis.
-
The
optparsemodule contains a new parser for command-line arguments that can convert option values to a particular Python type and will automatically generate a usage message. See the following section for more details. -
The old and never-documented
!linuxaudiodevmodule has been deprecated, and a new version named!ossaudiodevhas been added. The module was renamed because the OSS sound drivers can be used on platforms other than Linux, and the interface has also been tidied and brought up to date in various ways. (Contributed by Greg Ward and Nicholas FitzRoy-Dale.) -
The new
platformmodule contains a number of functions that try to determine various properties of the platform you're running on. There are functions for getting the architecture, CPU type, the Windows OS version, and even the Linux distribution version. (Contributed by Marc-André Lemburg.) -
The parser objects provided by the
pyexpat <xml.parsers.expat>module can now optionally buffer character data, resulting in fewer calls to your character data handler and therefore faster performance. Setting the parser object's~xml.parsers.expat.xmlparser.buffer_textattribute toTruewill enable buffering. -
The
sample(population, k)function was added to therandommodule. population is a sequence or!xrangeobject containing the elements of a population, and~random.samplechooses k elements from the population without replacing chosen elements. k can be any value up tolen(population). For example:>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn'] >>> random.sample(days, 3) # Choose 3 elements ['St', 'Sn', 'Th'] >>> random.sample(days, 7) # Choose 7 elements ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn'] >>> random.sample(days, 7) # Choose 7 again ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th'] >>> random.sample(days, 8) # Can't choose eight Traceback (most recent call last): File "<stdin>", line 1, in ? File "random.py", line 414, in sample raise ValueError, "sample larger than population" ValueError: sample larger than population >>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000 [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]The
randommodule now uses a new algorithm, the Mersenne Twister, implemented in C. It's faster and more extensively studied than the previous algorithm.(All changes contributed by Raymond Hettinger.)
-
The
readlinemodule also gained a number of new functions:~readline.get_history_item,~readline.get_current_history_length, and~readline.redisplay. -
The
!rexecand!Bastionmodules have been declared dead, and attempts to import them will fail with aRuntimeError. New-style classes provide new ways to break out of the restricted execution environment provided by!rexec, and no one has interest in fixing them or time to do so. If you have applications using!rexec, rewrite them to use something else.(Sticking with Python 2.2 or 2.1 will not make your applications any safer because there are known bugs in the
!rexecmodule in those versions. To repeat: if you're using!rexec, stop using it immediately.) -
The
!rotormodule has been deprecated because the algorithm it uses for encryption is not believed to be secure. If you need encryption, use one of the several AES Python modules that are available separately. -
The
shutilmodule gained amove(src, dest)function that recursively moves a file or directory to a new location. -
Support for more advanced POSIX signal handling was added to the
signalbut then removed again as it proved impossible to make it work reliably across platforms. -
The
socketmodule now supports timeouts. You can call thesettimeout(t)method on a socket object to set a timeout of t seconds. Subsequent socket operations that take longer than t seconds to complete will abort and raise asocket.timeoutexception.The original timeout implementation was by Tim O'Malley. Michael Gilfix integrated it into the Python
socketmodule and shepherded it through a lengthy review. After the code was checked in, Guido van Rossum rewrote parts of it. (This is a good example of a collaborative development process in action.) -
On Windows, the
socketmodule now ships with Secure Sockets Layer (SSL) support. -
The value of the C
!PYTHON_API_VERSIONmacro is now exposed at the Python level assys.api_version. The current exception can be cleared by calling the new!sys.exc_clearfunction. -
The new
tarfilemodule allows reading from and writing totar-format archive files. (Contributed by Lars Gustäbel.) -
The new
textwrapmodule contains functions for wrapping strings containing paragraphs of text. Thewrap(text, width)function takes a string and returns a list containing the text split into lines of no more than the chosen width. Thefill(text, width)function returns a single string, reformatted to fit into lines no longer than the chosen width. (As you can guess,~textwrap.fillis built on top of~textwrap.wrap. For example:>>> import textwrap >>> paragraph = "Not a whit, we defy augury: ... more text ..." >>> textwrap.wrap(paragraph, 60) ["Not a whit, we defy augury: there's a special providence in", "the fall of a sparrow. If it be now, 'tis not to come; if it", ...] >>> print textwrap.fill(paragraph, 35) Not a whit, we defy augury: there's a special providence in the fall of a sparrow. If it be now, 'tis not to come; if it be not to come, it will be now; if it be not now, yet it will come: the readiness is all. >>>The module also contains a
~textwrap.TextWrapperclass that actually implements the text wrapping strategy. Both the~textwrap.TextWrapperclass and the~textwrap.wrapand~textwrap.fillfunctions support a number of additional keyword arguments for fine-tuning the formatting; consult the module's documentation for details. (Contributed by Greg Ward.) -
The
!threadandthreadingmodules now have companion modules,!dummy_threadand!dummy_threading, that provide a do-nothing implementation of the!threadmodule's interface for platforms where threads are not supported. The intention is to simplify thread-aware modules (ones that don't rely on threads to run) by putting the following code at the top:try: import threading as _threading except ImportError: import dummy_threading as _threadingIn this example,
!_threadingis used as the module name to make it clear that the module being used is not necessarily the actualthreadingmodule. Code can call functions and use classes in!_threadingwhether or not threads are supported, avoiding anifstatement and making the code slightly clearer. This module will not magically make multithreaded code run without threads; code that waits for another thread to return or to do something will simply hang forever. -
The
timemodule's~time.strptimefunction has long been an annoyance because it uses the platform C library's~time.strptimeimplementation, and different platforms sometimes have odd bugs. Brett Cannon contributed a portable implementation that's written in pure Python and should behave identically on all platforms. -
The new
timeitmodule helps measure how long snippets of Python code take to execute. Thetimeit.pyfile can be run directly from the command line, or the module's~timeit.Timerclass can be imported and used directly. Here's a short example that figures out whether it's faster to convert an 8-bit string to Unicode by appending an empty Unicode string to it or by using the!unicodefunction:import timeit timer1 = timeit.Timer('unicode("abc")') timer2 = timeit.Timer('"abc" + u""') # Run three trials print timer1.repeat(repeat=3, number=100000) print timer2.repeat(repeat=3, number=100000) # On my laptop this outputs: # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869] # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449] -
The
!Tixmodule has received various bug fixes and updates for the current version of the Tix package. -
The
!Tkintermodule now works with a thread-enabled version of Tcl. Tcl's threading model requires that widgets only be accessed from the thread in which they're created; accesses from another thread can cause Tcl to panic. For certain Tcl interfaces,!Tkinterwill now automatically avoid this when a widget is accessed from a different thread by marshalling a command, passing it to the correct thread, and waiting for the results. Other interfaces can't be handled automatically but!Tkinterwill now raise an exception on such an access so that you can at least find out about the problem. See https://mail.python.org/pipermail/python-dev/2002-December/031107.html for a more detailed explanation of this change. (Implemented by Martin von Löwis.) -
Calling Tcl methods through
!_tkinterno longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a!_tkinter.Tcl_Objobject if no Python equivalent exists. This behavior can be controlled through the!wantobjectsmethod of!tkappobjects.When using
!_tkinterthrough the!Tkintermodule (as most Tkinter applications will), this feature is always activated. It should not cause compatibility problems, since Tkinter would always convert string results to Python types where possible.If any incompatibilities are found, the old behavior can be restored by setting the
!wantobjectsvariable in the!Tkintermodule to false before creating the first!tkappobject. :import Tkinter Tkinter.wantobjects = 0Any breakage caused by this change should be reported as a bug.
-
The
!UserDictmodule has a new!DictMixinclass which defines all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries, such as the classes in theshelvemodule.Adding the mix-in as a superclass provides the full dictionary interface whenever the class defines
~object.__getitem__,~object.__setitem__,~object.__delitem__, and!keys. For example:>>> import UserDict >>> class SeqDict(UserDict.DictMixin): ... """Dictionary lookalike implemented with lists.""" ... def __init__(self): ... self.keylist = [] ... self.valuelist = [] ... def __getitem__(self, key): ... try: ... i = self.keylist.index(key) ... except ValueError: ... raise KeyError ... return self.valuelist[i] ... def __setitem__(self, key, value): ... try: ... i = self.keylist.index(key) ... self.valuelist[i] = value ... except ValueError: ... self.keylist.append(key) ... self.valuelist.append(value) ... def __delitem__(self, key): ... try: ... i = self.keylist.index(key) ... except ValueError: ... raise KeyError ... self.keylist.pop(i) ... self.valuelist.pop(i) ... def keys(self): ... return list(self.keylist) ... >>> s = SeqDict() >>> dir(s) # See that other dictionary methods are implemented ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'valuelist', 'values'](Contributed by Raymond Hettinger.)
-
The DOM implementation in
xml.dom.minidomcan now generate XML output in a particular encoding by providing an optional encoding argument to the~xml.dom.minidom.Node.toxmland~xml.dom.minidom.Node.toprettyxmlmethods of DOM nodes. -
The
!xmlrpclibmodule now supports an XML-RPC extension for handling nil data values such as Python'sNone. Nil values are always supported on unmarshalling an XML-RPC response. To generate requests containingNone, you must supply a true value for the allow_none parameter when creating a!Marshallerinstance. -
The new
!DocXMLRPCServermodule allows writing self-documenting XML-RPC servers. Run it in demo mode (as a program) to see it in action. Pointing the web browser to the RPC server produces pydoc-style documentation; pointing xmlrpclib to the server allows invoking the actual methods. (Contributed by Brian Quinlan.) -
Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492) has been added. The "idna" encoding can be used to convert between a Unicode domain name and the ASCII-compatible encoding (ACE) of that name. :
>{}>{}> u"www.Alliancefrançaise.nu".encode("idna") 'www.xn--alliancefranaise-npb.nu'The
socketmodule has also been extended to transparently convert Unicode hostnames to the ACE version before passing them to the C library. Modules that deal with hostnames such as!httplibandftplib) also support Unicode host names;!httplibalso sends HTTPHostheaders using the ACE version of the domain name.urllibsupports Unicode URLs with non-ASCII host names as long as thepathpart of the URL is ASCII only.To implement this change, the
stringprepmodule, themkstringpreptool and thepunycodeencoding have been added.
Date/Time Type
Date and time types suitable for expressing timestamps were added as the datetime module. The types don't support different calendars or many fancy features, and just stick to the basics of representing time.
The three primary types are: ~datetime.date, representing a day, month, and year; ~datetime.time, consisting of hour, minute, and second; and ~datetime.datetime, which contains all the attributes of both ~datetime.date and ~datetime.time. There's also a ~datetime.timedelta class representing differences between two points in time, and time zone logic is implemented by classes inheriting from the abstract ~datetime.tzinfo class.
You can create instances of ~datetime.date and ~datetime.time by either supplying keyword arguments to the appropriate constructor, e.g. datetime.date(year=1972, month=10, day=15), or by using one of a number of class methods. For example, the ~datetime.date.today class method returns the current local date.
Once created, instances of the date/time classes are all immutable. There are a number of methods for producing formatted strings from objects:
>>> import datetime as dt
>>> now = dt.datetime.now()
>>> now.isoformat()
'2002-12-30T21:27:03.994956'
>>> now.ctime() # Only available on date, datetime
'Mon Dec 30 21:27:03 2002'
>>> now.strftime('%Y %d %b')
'2002 30 Dec'
The ~datetime.datetime.replace method allows modifying one or more fields of a ~datetime.date or ~datetime.datetime instance, returning a new instance:
>>> d = dt.datetime.now()
>>> d
datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
>>> d.replace(year=2001, hour=12)
datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
>>>
Instances can be compared, hashed, and converted to strings (the result is the same as that of ~datetime.datetime.isoformat). ~datetime.date and ~datetime.datetime instances can be subtracted from each other, and added to ~datetime.timedelta instances. The largest missing feature is that there's no standard library support for parsing strings and getting back a ~datetime.date or ~datetime.datetime.
For more information, refer to the module's reference documentation. (Contributed by Tim Peters.)
The optparse Module
The getopt module provides simple parsing of command-line arguments. The new optparse module (originally named Optik) provides more elaborate command-line parsing that follows the Unix conventions, automatically creates the output for !--help, and can perform different actions for different options.
You start by creating an instance of ~optparse.OptionParser and telling it what your program's options are. :
import sys
from optparse import OptionParser
op = OptionParser()
op.add_option('-i', '--input',
action='store', type='string', dest='input',
help='set input filename')
op.add_option('-l', '--length',
action='store', type='int', dest='length',
help='set maximum length of output')
Parsing a command line is then done by calling the ~optparse.OptionParser.parse_args method. :
options, args = op.parse_args(sys.argv[1:])
print options
print args
This returns an object containing all of the option values, and a list of strings containing the remaining arguments.
Invoking the script with the various arguments now works as you'd expect it to. Note that the length argument is automatically converted to an integer.
$ ./python opt.py -i data arg1
<Values at 0x400cad4c: {'input': 'data', 'length': None}>
['arg1']
$ ./python opt.py --input=data --length=4
<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
[]
$
The help message is automatically generated for you:
$ ./python opt.py --help
usage: opt.py [options]
options:
-h, --help show this help message and exit
-iINPUT, --input=INPUT
set input filename
-lLENGTH, --length=LENGTH
set maximum length of output
$
See the module's documentation for more details.
Optik was written by Greg Ward, with suggestions from the readers of the Getopt SIG.
Pymalloc: A Specialized Object Allocator
Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a feature added to Python 2.1. Pymalloc is intended to be faster than the system malloc and to have less memory overhead for allocation patterns typical of Python programs. The allocator uses C's malloc function to get large pools of memory and then fulfills smaller memory requests from these pools.
In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by default; you had to explicitly enable it when compiling Python by providing the !--with-pymalloc option to the configure script. In 2.3, pymalloc has had further enhancements and is now enabled by default; you'll have to supply !--without-pymalloc to disable it.
This change is transparent to code written in Python; however, pymalloc may expose bugs in C extensions. Authors of C extension modules should test their code with pymalloc enabled, because some incorrect code may cause core dumps at runtime.
There's one particularly common error that causes problems. There are a number of memory allocation functions in Python's C API that have previously just been aliases for the C library's malloc and free, meaning that if you accidentally called mismatched functions the error wouldn't be noticeable. When the object allocator is enabled, these functions aren't aliases of malloc and free any more, and calling the wrong function to free memory may get you a core dump. For example, if memory was allocated using PyObject_Malloc, it has to be freed using PyObject_Free, not free. A few modules included with Python fell afoul of this and had to be fixed; doubtless there are more third-party modules that will have the same problem.
As part of this change, the confusing multiple interfaces for allocating memory have been consolidated down into two API families. Memory allocated with one family must not be manipulated with functions from the other family. There is one family for allocating chunks of memory and another family of functions specifically for allocating Python objects.
- To allocate and free an undistinguished chunk of memory use the "raw memory" family:
PyMem_Malloc,PyMem_Realloc, andPyMem_Free. - The "object memory" family is the interface to the pymalloc facility described above and is biased towards a large number of "small" allocations:
PyObject_Malloc,PyObject_Realloc, andPyObject_Free. - To allocate and free Python objects, use the "object" family
PyObject_New,PyObject_NewVar, andPyObject_Del.
Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging features to catch memory overwrites and doubled frees in both extension modules and in the interpreter itself. To enable this support, compile a debugging version of the Python interpreter by running configure with !--with-pydebug.
To aid extension writers, a header file Misc/pymemcompat.h is distributed with the source to Python 2.3 that allows Python extensions to use the 2.3 interfaces to memory allocation while compiling against any version of Python since 1.5.2. You would copy the file from Python's source distribution and bundle it with the source of your extension.
https://hg.python.org/cpython/file/default/Objects/obmalloc.c
For the full details of the pymalloc implementation, see the comments at the top of the file Objects/obmalloc.c in the Python source code. The above link points to the file within the python.org SVN browser.
Build and C API Changes
Changes to Python's build process and to the C API include:
- The cycle detection implementation used by the garbage collection has proven to be stable, so it's now been made mandatory. You can no longer compile Python without it, and the
!--with-cycle-gcswitch toconfigurehas been removed. - Python can now optionally be built as a shared library (
libpython2.3.so) by supplying!--enable-sharedwhen running Python'sconfigurescript. (Contributed by Ondrej Palkovsky.) - The
!DL_EXPORTand!DL_IMPORTmacros are now deprecated. Initialization functions for Python extension modules should now be declared using the new macroPyMODINIT_FUNC, while the Python core will generally use the!PyAPI_FUNCand!PyAPI_DATAmacros. - The interpreter can be compiled without any docstrings for the built-in functions and modules by supplying
!--without-doc-stringsto theconfigurescript. This makes the Python executable about 10% smaller, but will also mean that you can't get help for Python's built-ins. (Contributed by Gustavo Niemeyer.) - The
!PyArg_NoArgsmacro is now deprecated, and code that uses it should be changed. For Python 2.2 and later, the method definition table can specify theMETH_NOARGSflag, signalling that there are no arguments, and the argument checking can then be removed. If compatibility with pre-2.2 versions of Python is important, the code could usePyArg_ParseTuple(args, "")instead, but this will be slower than usingMETH_NOARGS. PyArg_ParseTupleaccepts new format characters for various sizes of unsigned integers:Bforunsigned char,Hforunsigned short int,Iforunsigned int, andKforunsigned long long.- A new function,
PyObject_DelItemString(mapping, char *key)was added as shorthand forPyObject_DelItem(mapping, PyString_New(key)). - File objects now manage their internal string buffer differently, increasing it exponentially when needed. This results in the benchmark tests in
Lib/test/test_bufio.pyspeeding up considerably (from 57 seconds to 1.7 seconds, according to one measurement). - It's now possible to define class and static methods for a C extension type by setting either the
METH_CLASSorMETH_STATICflags in a method'sPyMethodDefstructure. - Python now includes a copy of the Expat XML parser's source code, removing any dependence on a system version or local installation of Expat.
- If you dynamically allocate type objects in your extension, you should be aware of a change in the rules relating to the
~type.__module__and~type.__name__attributes. In summary, you will want to ensure the type's dictionary contains a'__module__'key; making the module name the part of the type name leading up to the final period will no longer have the desired effect. For more detail, read the API reference documentation or the source.
Port-Specific Changes
Support for a port to IBM's OS/2 using the EMX runtime environment was merged into the main Python source tree. EMX is a POSIX emulation layer over the OS/2 system APIs. The Python port for EMX tries to support all the POSIX-like capability exposed by the EMX runtime, and mostly succeeds; !fork and ~fcntl.fcntl are restricted by the limitations of the underlying emulation layer. The standard OS/2 port, which uses IBM's Visual Age compiler, also gained support for case-sensitive import semantics as part of the integration of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
On MacOS, most toolbox modules have been weaklinked to improve backward compatibility. This means that modules will no longer fail to load if a single routine is missing on the current OS version. Instead calling the missing routine will raise an exception. (Contributed by Jack Jansen.)
The RPM spec files, found in the Misc/RPM/ directory in the Python source distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)
Other new platforms now supported by Python include AtheOS (http://www.atheos.cx/), GNU/Hurd, and OpenVMS.
Other Changes and Fixes
As usual, there were a bunch of other improvements and bugfixes scattered throughout the source tree. A search through the CVS change logs finds there were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Both figures are likely to be underestimates.
Some of the more notable changes are:
-
If the
PYTHONINSPECTenvironment variable is set, the Python interpreter will enter the interactive prompt after running a Python program, as if Python had been invoked with the-ioption. The environment variable can be set before running the Python interpreter, or it can be set by the Python program as part of its execution. -
The
regrtest.pyscript now provides a way to allow "all resources except foo." A resource name passed to the!-uoption can now be prefixed with a hyphen ('-') to mean "remove this resource." For example, the option '-uall,-bsddb' could be used to enable the use of all resources exceptbsddb. -
The tools used to build the documentation now work under Cygwin as well as Unix.
-
The
SET_LINENOopcode has been removed. Back in the mists of time, this opcode was needed to produce line numbers in tracebacks and support trace functions (for, e.g.,pdb). Since Python 1.5, the line numbers in tracebacks have been computed using a different mechanism that works with "python -O". For Python 2.3 Michael Hudson implemented a similar scheme to determine when to call the trace function, removing the need forSET_LINENOentirely.It would be difficult to detect any resulting difference from Python code, apart from a slight speed up when Python is run without
-O.C extensions that access the
~frame.f_linenofield of frame objects should instead callPyCode_Addr2Line(f->f_code, f->f_lasti). This will have the added effect of making the code work as desired under "python -O" in earlier versions of Python.A nifty new feature is that trace functions can now assign to the
~frame.f_linenoattribute of frame objects, changing the line that will be executed next. Ajumpcommand has been added to thepdbdebugger taking advantage of this new feature. (Implemented by Richie Hindle.)
Porting to Python 2.3
This section lists previously described changes that may require changes to your code:
-
yieldis now always a keyword; if it's used as a variable name in your code, a different name must be chosen. -
For strings X and Y,
X in Ynow works if X is more than one character long. -
The
inttype constructor will now return a long integer instead of raising anOverflowErrorwhen a string or floating-point number is too large to fit into an integer. -
If you have Unicode strings that contain 8-bit characters, you must declare the file's encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top of the file. See section
section-encodingsfor more information. -
Calling Tcl methods through
!_tkinterno longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a!_tkinter.Tcl_Objobject if no Python equivalent exists. -
Large octal and hex literals such as
0xffffffffnow trigger aFutureWarning. Currently they're stored as 32-bit numbers and result in a negative value, but in Python 2.4 they'll become positive long integers.There are a few ways to fix this warning. If you really need a positive number, just add an
Lto the end of the literal. If you're trying to get a 32-bit integer with low bits set and have previously used an expression such as~(1 << 31), it's probably clearest to start with all bits set and clear the desired upper bits. For example, to clear just the top bit (bit 31), you could write0xffffffffL &~(1L<<31). -
You can no longer disable assertions by assigning to
__debug__. -
The Distutils
!setupfunction has gained various new keyword arguments such as depends. Old versions of the Distutils will abort if passed unknown keywords. A solution is to check for the presence of the new!get_distutil_optionsfunction in yoursetup.pyand only uses the new keywords with a version of the Distutils that supports them:from distutils import core kw = {'sources': 'foo.c', ...} if hasattr(core, 'get_distutil_options'): kw['depends'] = ['foo.h'] ext = Extension(**kw) -
Using
Noneas a variable name will now result in aSyntaxWarningwarning. -
Names of extension types defined by the modules included with Python now contain the module and a
'.'in front of the type name.
Acknowledgements
What's New in Python 2.4
This article explains the new features in Python 2.4.1, released on March 30, 2005.
Python 2.4 is a medium-sized release. It doesn't introduce as many changes as the radical Python 2.2, but introduces more features than the conservative 2.3 release. The most significant new language features are function decorators and generator expressions; most other changes are to the standard library.
According to the CVS change logs, there were 481 patches applied and 502 bugs fixed between Python 2.3 and 2.4. Both figures are likely to be underestimates.
This article doesn't attempt to provide a complete specification of every single new feature, but instead provides a brief introduction to each feature. For full details, you should refer to the documentation for Python 2.4, such as the Python Library Reference and the Python Reference Manual. Often you will be referred to the PEP for a particular new feature for explanations of the implementation and design rationale.
PEP 218: Built-In Set Objects
Python 2.3 introduced the !sets module. C implementations of set data types have now been added to the Python core as two new built-in types, set(iterable) and frozenset(iterable). They provide high speed operations for membership testing, for eliminating duplicates from sequences, and for mathematical operations like unions, intersections, differences, and symmetric differences. :
>>> a = set('abracadabra') # form a set from a string
>>> 'z' in a # fast membership testing
False
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> ''.join(a) # convert back into a string
'arbcd'
>>> b = set('alacazam') # form a second set
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
>>> a.add('z') # add a new element
>>> a.update('wxy') # add multiple new elements
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
>>> a.remove('x') # take one element out
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
The frozenset type is an immutable version of set. Since it is immutable and hashable, it may be used as a dictionary key or as a member of another set.
The !sets module remains in the standard library, and may be useful if you wish to subclass the !Set or !ImmutableSet classes. There are currently no plans to deprecate the module.
218 - Adding a Built-In Set Object Type
Originally proposed by Greg Wilson and ultimately implemented by Raymond Hettinger.
PEP 237: Unifying Long Integers and Integers
The lengthy transition process for this PEP, begun in Python 2.2, takes another step forward in Python 2.4. In 2.3, certain integer operations that would behave differently after int/long unification triggered FutureWarning warnings and returned values limited to 32 or 64 bits (depending on your platform). In 2.4, these expressions no longer produce a warning and instead produce a different result that's usually a long integer.
The problematic expressions are primarily left shifts and lengthy hexadecimal and octal constants. For example, 2 << 32 results in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python 2.4, this expression now returns the correct answer, 8589934592.
237 - Unifying Long Integers and Integers
Original PEP written by Moshe Zadka and GvR. The changes for 2.4 were implemented by Kalle Svensson.
PEP 289: Generator Expressions
The iterator feature introduced in Python 2.2 and the itertools module make it easier to write programs that loop through large data sets without having the entire data set in memory at one time. List comprehensions don't fit into this picture very well because they produce a Python list object containing all of the items. This unavoidably pulls all of the objects into memory, which can be a problem if your data set is very large. When trying to write a functionally styled program, it would be natural to write something like:
links = [link for link in get_all_links() if not link.followed]
for link in links:
...
instead of :
for link in get_all_links():
if link.followed:
continue
...
The first form is more concise and perhaps more readable, but if you're dealing with a large number of link objects you'd have to write the second form to avoid having all link objects in memory at the same time.
Generator expressions work similarly to list comprehensions but don't materialize the entire list; instead they create a generator that will return elements one by one. The above example could be written as:
links = (link for link in get_all_links() if not link.followed)
for link in links:
...
Generator expressions always have to be written inside parentheses, as in the above example. The parentheses signalling a function call also count, so if you want to create an iterator that will be immediately passed to a function you could write:
print sum(obj.count for obj in list_all_objects())
Generator expressions differ from list comprehensions in various small ways. Most notably, the loop variable (obj in the above example) is not accessible outside of the generator expression. List comprehensions leave the variable assigned to its last value; future versions of Python will change this, making list comprehensions match generator expressions in this respect.
289 - Generator Expressions
Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.
PEP 292: Simpler String Substitutions
Some new classes in the standard library provide an alternative mechanism for substituting variables into strings; this style of substitution may be better for applications where untrained users need to edit templates.
The usual way of substituting variables by name is the % operator:
>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
'2: The Best of Times'
When writing the template string, it can be easy to forget the i or s after the closing parenthesis. This isn't a big problem if the template is in a Python module, because you run the code, get an "Unsupported format character" ValueError, and fix the problem. However, consider an application such as Mailman where template strings or translations are being edited by users who aren't aware of the Python language. The format string's syntax is complicated to explain to such users, and if they make a mistake, it's difficult to provide helpful feedback to them.
PEP 292 adds a ~string.Template class to the string module that uses $ to indicate a substitution:
>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute({'page':2, 'title': 'The Best of Times'})
'2: The Best of Times'
If a key is missing from the dictionary, the ~string.Template.substitute method will raise a KeyError. There's also a ~string.Template.safe_substitute method that ignores missing keys:
>>> t = string.Template('$page: $title')
>>> t.safe_substitute({'page':3})
'3: $title'
292 - Simpler String Substitutions
Written and implemented by Barry Warsaw.
PEP 318: Decorators for Functions and Methods
Python 2.2 extended Python's object model by adding static methods and class methods, but it didn't extend Python's syntax to provide any new way of defining static or class methods. Instead, you had to write a def statement in the usual way, and pass the resulting method to a staticmethod or classmethod function that would wrap up the function as a method of the new type. Your code would look like this:
class C:
def meth (cls):
...
meth = classmethod(meth) # Rebind name to wrapped-up class method
If the method was very long, it would be easy to miss or forget the classmethod invocation after the function body.
The intention was always to add some syntax to make such definitions more readable, but at the time of 2.2's release a good syntax was not obvious. Today a good syntax still isn't obvious but users are asking for easier access to the feature; a new syntactic feature has been added to meet this need.
The new feature is called "function decorators". The name comes from the idea that classmethod, staticmethod, and friends are storing additional information on a function object; they're decorating functions with more details.
The notation borrows from Java and uses the '@' character as an indicator. Using the new syntax, the example above would be written:
class C:
@classmethod
def meth (cls):
...
The @classmethod is shorthand for the meth=classmethod(meth) assignment. More generally, if you have the following:
@A
@B
@C
def f ():
...
It's equivalent to the following pre-decorator code:
def f(): ...
f = A(B(C(f)))
Decorators must come on the line before a function definition, one decorator per line, and can't be on the same line as the def statement, meaning that @A def f(): ... is illegal. You can only decorate function definitions, either at the module level or inside a class; you can't decorate class definitions.
A decorator is just a function that takes the function to be decorated as an argument and returns either the same function or some new object. The return value of the decorator need not be callable (though it typically is), unless further decorators will be applied to the result. It's easy to write your own decorators. The following simple example just sets an attribute on the function object:
>>> def deco(func):
... func.attr = 'decorated'
... return func
...
>>> @deco
... def f(): pass
...
>>> f
<function f at 0x402ef0d4>
>>> f.attr
'decorated'
>>>
As a slightly more realistic example, the following decorator checks that the supplied argument is an integer:
def require_int (func):
def wrapper (arg):
assert isinstance(arg, int)
return func(arg)
return wrapper
@require_int
def p1 (arg):
print arg
@require_int
def p2(arg):
print arg*2
An example in 318 contains a fancier version of this idea that lets you both specify the required type and check the returned type.
Decorator functions can take arguments. If arguments are supplied, your decorator function is called with only those arguments and must return a new decorator function; this function must take a single function and return a function, as previously described. In other words, @A @B @C(args) becomes:
def f(): ...
_deco = C(args)
f = A(B(_deco(f)))
Getting this right can be slightly brain-bending, but it's not too difficult.
318 - Decorators for Functions, Methods and Classes
Written by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people wrote patches implementing function decorators, but the one that was actually checked in was patch #979728, written by Mark Russell.
https://wiki.python.org/moin/PythonDecoratorLibrary
This Wiki page contains several examples of decorators.
PEP 322: Reverse Iteration
A new built-in function, reversed(seq), takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order. :
>>> for i in reversed(xrange(1,4)):
... print i
...
3
2
1
Compared to extended slicing, such as range(1,4)[::-1], reversed is easier to read, runs faster, and uses substantially less memory.
Note that reversed only accepts sequences, not arbitrary iterators. If you want to reverse an iterator, first convert it to a list with list. :
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
... print line
...
root:*:0:0:System Administrator:/var/root:/bin/tcsh
...
322 - Reverse Iteration
Written and implemented by Raymond Hettinger.
PEP 324: New subprocess Module
The standard library provides a number of ways to execute a subprocess, offering different features and different levels of complexity. os.system(command) is easy to use, but slow (it runs a shell process which executes the command) and dangerous (you have to be careful about escaping the shell's metacharacters). The !popen2 module offers classes that can capture standard output and standard error from the subprocess, but the naming is confusing. The subprocess module cleans this up, providing a unified interface that offers all the features you might need.
Instead of !popen2's collection of classes, subprocess contains a single class called subprocess.Popen whose constructor supports a number of different keyword arguments. :
class Popen(args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
args is commonly a sequence of strings that will be the arguments to the program executed as the subprocess. (If the shell argument is true, args can be a string which will then be passed on to the shell for interpretation, just as os.system does.)
stdin, stdout, and stderr specify what the subprocess's input, output, and error streams will be. You can provide a file object or a file descriptor, or you can use the constant subprocess.PIPE to create a pipe between the subprocess and the parent.
single: universal newlines; What's new
The constructor has a number of handy options:
- close_fds requests that all file descriptors be closed before running the subprocess.
- cwd specifies the working directory in which the subprocess will be executed (defaulting to whatever the parent's working directory is).
- env is a dictionary specifying environment variables.
- preexec_fn is a function that gets called before the child is started.
- universal_newlines opens the child's input and output using Python's
universal newlinesfeature.
Once you've created the ~subprocess.Popen instance, you can call its ~subprocess.Popen.wait method to pause until the subprocess has exited, ~subprocess.Popen.poll to check if it's exited without pausing, or communicate(data) to send the string data to the subprocess's standard input. communicate(data) then reads any data that the subprocess has sent to its standard output or standard error, returning a tuple (stdout_data, stderr_data).
~subprocess.call is a shortcut that passes its arguments along to the ~subprocess.Popen constructor, waits for the command to complete, and returns the status code of the subprocess. It can serve as a safer analog to os.system:
sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
if sts == 0:
# Success
...
else:
# dpkg returned an error
...
The command is invoked without use of the shell. If you really do want to use the shell, you can add shell=True as a keyword argument and provide a string instead of a sequence:
sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)
The PEP takes various examples of shell and Python code and shows how they'd be translated into Python code that uses subprocess. Reading this section of the PEP is highly recommended.
324 - subprocess - New process module
Written and implemented by Peter Åstrand, with assistance from Fredrik Lundh and others.
PEP 327: Decimal Data Type
Python has always supported floating-point (FP) numbers, based on the underlying C double type, as a data type. However, while most programming languages provide a floating-point type, many people (even programmers) are unaware that floating-point numbers don't represent certain decimal fractions accurately. The new ~decimal.Decimal type can represent these fractions accurately, up to a user-specified precision limit.
Why is Decimal needed?
The limitations arise from the representation used for floating-point numbers. FP numbers are made up of three components:
- The sign, which is positive or negative.
- The mantissa, which is a single-digit binary number followed by a fractional part. For example,
1.01in base-2 notation is1 + 0/2 + 1/4, or 1.25 in decimal notation. - The exponent, which tells where the decimal point is located in the number represented.
For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in binary), and an exponent of 0 (the decimal point doesn't need to be shifted). The number 5 has the same sign and mantissa, but the exponent is 2 because the mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 * 4 equals 5.
Modern systems usually provide floating-point support that conforms to a standard called IEEE 754. C's double type is usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This means that numbers can only be specified to 52 bits of precision. If you're trying to represent numbers whose expansion repeats endlessly, the expansion is cut off after 52 bits. Unfortunately, most software needs to produce output in base 10, and common fractions in base 10 are often repeating decimals in binary. For example, 1.1 decimal is binary 1.0001100110011 ...; .1 = 1/16 + 1/32 + 1/256 plus an infinite number of additional terms. IEEE 754 has to chop off that infinitely repeated decimal after 52 digits, so the representation is slightly inaccurate.
Sometimes you can see this inaccuracy when the number is printed:
>>> 1.1
1.1000000000000001
The inaccuracy isn't always visible when you print the number because the FP-to-decimal-string conversion is provided by the C library, and most C libraries try to produce sensible output. Even if it's not displayed, however, the inaccuracy is still there and subsequent operations can magnify the error.
For many applications this doesn't matter. If I'm plotting points and displaying them on my monitor, the difference between 1.1 and 1.1000000000000001 is too small to be visible. Reports often limit output to a certain number of decimal places, and if you round the number to two or three or even eight decimal places, the error is never apparent. However, for applications where it does matter, it's a lot of work to implement your own custom arithmetic routines.
Hence, the ~decimal.Decimal type was created.
The ~decimal.Decimal type
A new module, decimal, was added to Python's standard library. It contains two classes, ~decimal.Decimal and ~decimal.Context. ~decimal.Decimal instances represent numbers, and ~decimal.Context instances are used to wrap up various settings such as the precision and default rounding mode.
~decimal.Decimal instances are immutable, like regular Python integers and FP numbers; once it's been created, you can't change the value an instance represents. ~decimal.Decimal instances can be created from integers or strings:
>>> import decimal
>>> decimal.Decimal(1972)
Decimal("1972")
>>> decimal.Decimal("1.1")
Decimal("1.1")
You can also provide tuples containing the sign, the mantissa represented as a tuple of decimal digits, and the exponent:
>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
Decimal("-14.75")
Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is negative.
Converting from floating-point numbers poses a bit of a problem: should the FP number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced? The decision was to dodge the issue and leave such a conversion out of the API. Instead, you should convert the floating-point number into a string using the desired precision and pass the string to the ~decimal.Decimal constructor:
>>> f = 1.1
>>> decimal.Decimal(str(f))
Decimal("1.1")
>>> decimal.Decimal('%.12f' % f)
Decimal("1.100000000000")
Once you have ~decimal.Decimal instances, you can perform the usual mathematical operations on them. One limitation: exponentiation requires an integer exponent:
>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")
>>> a-b
Decimal("33.99")
>>> a*b
Decimal("61.7956")
>>> a/b
Decimal("20.64739884393063583815028902")
>>> a ** 2
Decimal("1275.9184")
>>> a**b
Traceback (most recent call last):
...
decimal.InvalidOperation: x ** (non-integer)
You can combine ~decimal.Decimal instances with integers, but not with floating-point numbers:
>>> a + 4
Decimal("39.72")
>>> a + 4.5
Traceback (most recent call last):
...
TypeError: You can interact Decimal only with int, long or Decimal data types.
>>>
~decimal.Decimal numbers can be used with the math and cmath modules, but note that they'll be immediately converted to floating-point numbers before the operation is performed, resulting in a possible loss of precision and accuracy. You'll also get back a regular floating-point number and not a ~decimal.Decimal. :
>>> import math, cmath
>>> d = decimal.Decimal('123456789012.345')
>>> math.sqrt(d)
351364.18288201344
>>> cmath.sqrt(-d)
351364.18288201344j
~decimal.Decimal instances have a ~decimal.Decimal.sqrt method that returns a ~decimal.Decimal, but if you need other things such as trigonometric functions you'll have to implement them. :
>>> d.sqrt()
Decimal("351364.1828820134592177245001")
The ~decimal.Context type
Instances of the ~decimal.Context class encapsulate several settings for decimal operations:
~decimal.Context.precis the precision, the number of decimal places.~decimal.Context.roundingspecifies the rounding mode. Thedecimalmodule has constants for the various possibilities:~decimal.ROUND_DOWN,~decimal.ROUND_CEILING,~decimal.ROUND_HALF_EVEN, and various others.~decimal.Context.trapsis a dictionary specifying what happens on encountering certain error conditions: either an exception is raised or a value is returned. Some examples of error conditions are division by zero, loss of precision, and overflow.
There's a thread-local default context available by calling ~decimal.getcontext; you can change the properties of this context to alter the default precision, rounding, or trap handling. The following example shows the effect of changing the precision of the default context:
>>> decimal.getcontext().prec
28
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1428571428571428571428571429")
>>> decimal.getcontext().prec = 9
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.142857143")
The default action for error conditions is selectable; the module can either return a special value such as infinity or not-a-number, or exceptions can be raised:
>>> decimal.Decimal(1) / decimal.Decimal(0)
Traceback (most recent call last):
...
decimal.DivisionByZero: x / 0
>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
>>> decimal.Decimal(1) / decimal.Decimal(0)
Decimal("Infinity")
>>>
The ~decimal.Context instance also has various methods for formatting numbers such as ~decimal.Context.to_eng_string and ~decimal.Context.to_sci_string.
For more information, see the documentation for the decimal module, which includes a quick-start tutorial and a reference.
327 - Decimal Data Type
Written by Facundo Batista and implemented by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.
http://www.lahey.com/float.htm
The article uses Fortran code to illustrate many of the problems that floating-point inaccuracy can cause.
https://speleotrove.com/decimal/
A description of a decimal-based representation. This representation is being proposed as a standard, and underlies the new Python decimal type. Much of this material was written by Mike Cowlishaw, designer of the Rexx language.
PEP 328: Multi-line Imports
One language change is a small syntactic tweak aimed at making it easier to import many names from a module. In a from module import names statement, names is a sequence of names separated by commas. If the sequence is very long, you can either write multiple imports from the same module, or you can use backslashes to escape the line endings like this:
from SimpleXMLRPCServer import SimpleXMLRPCServer,\
SimpleXMLRPCRequestHandler,\
CGIXMLRPCRequestHandler,\
resolve_dotted_attribute
The syntactic change in Python 2.4 simply allows putting the names within parentheses. Python ignores newlines within a parenthesized expression, so the backslashes are no longer needed:
from SimpleXMLRPCServer import (SimpleXMLRPCServer,
SimpleXMLRPCRequestHandler,
CGIXMLRPCRequestHandler,
resolve_dotted_attribute)
The PEP also proposes that all import statements be absolute imports, with a leading . character to indicate a relative import. This part of the PEP was not implemented for Python 2.4, but was completed for Python 2.5.
328 - Imports: Multi-Line and Absolute/Relative
Written by Aahz. Multi-line imports were implemented by Dima Dorfman.
PEP 331: Locale-Independent Float/String Conversions
The locale modules lets Python software select various conversions and display conventions that are localized to a particular country or language. However, the module was careful to not change the numeric locale because various functions in Python's implementation required that the numeric locale remain set to the 'C' locale. Often this was because the code was using the C library's !atof function.
Not setting the numeric locale caused trouble for extensions that used third-party C libraries, however, because they wouldn't have the correct locale set. The motivating example was GTK+, whose user interface widgets weren't displaying numbers in the current locale.
The solution described in the PEP is to add three new functions to the Python API that perform ASCII-only conversions, ignoring the locale setting:
PyOS_ascii_strtod(str, ptr)andPyOS_ascii_atof(str, ptr)both convert a string to a Cdouble.PyOS_ascii_formatd(buffer, buf_len, format, d)converts adoubleto an ASCII string.
The code for these functions came from the GLib library (https://developer-old.gnome.org/glib/2.26/), whose developers kindly relicensed the relevant functions and donated them to the Python Software Foundation. The locale module can now change the numeric locale, letting extensions such as GTK+ produce the correct results.
331 - Locale-Independent Float/String Conversions
Written by Christian R. Reis, and implemented by Gustavo Carneiro.
Other Language Changes
Here are all of the changes that Python 2.4 makes to the core Python language.
-
Decorators for functions and methods were added (
318). -
Built-in
setandfrozensettypes were added (218). Other new built-ins include thereversed(seq)function (322). -
Generator expressions were added (
289). -
Certain numeric expressions no longer return values restricted to 32 or 64 bits (
237). -
You can now put parentheses around the list of names in a
from module import namesstatement (328). -
The
dict.updatemethod now accepts the same argument forms as thedictconstructor. This includes any mapping, any iterable of key/value pairs, and keyword arguments. (Contributed by Raymond Hettinger.) -
The string methods
~str.ljust,~str.rjust, and~str.centernow take an optional argument for specifying a fill character other than a space. (Contributed by Raymond Hettinger.) -
Strings also gained an
~str.rsplitmethod that works like the~str.splitmethod but splits from the end of the string. (Contributed by Sean Reifschneider.) :>>> 'www.python.org'.split('.', 1) ['www', 'python.org'] 'www.python.org'.rsplit('.', 1) ['www.python', 'org'] -
Three keyword parameters, cmp, key, and reverse, were added to the
~list.sortmethod of lists. These parameters make some common usages of~list.sortsimpler. All of these parameters are optional.For the cmp parameter, the value should be a comparison function that takes two parameters and returns -1, 0, or +1 depending on how the parameters compare. This function will then be used to sort the list. Previously this was the only parameter that could be provided to
~list.sort.key should be a single-parameter function that takes a list element and returns a comparison key for the element. The list is then sorted using the comparison keys. The following example sorts a list case-insensitively:
>>> L = ['A', 'b', 'c', 'D'] >>> L.sort() # Case-sensitive sort >>> L ['A', 'D', 'b', 'c'] >>> # Using 'key' parameter to sort list >>> L.sort(key=lambda x: x.lower()) >>> L ['A', 'b', 'c', 'D'] >>> # Old-fashioned way >>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower())) >>> L ['A', 'b', 'c', 'D']The last example, which uses the cmp parameter, is the old way to perform a case-insensitive sort. It works but is slower than using a key parameter. Using key calls
~str.lowermethod once for each element in the list while using cmp will call it twice for each comparison, so using key saves on invocations of the~str.lowermethod.For simple key functions and comparison functions, it is often possible to avoid a
lambdaexpression by using an unbound method instead. For example, the above case-insensitive sort is best written as:>>> L.sort(key=str.lower) >>> L ['A', 'b', 'c', 'D']Finally, the reverse parameter takes a Boolean value. If the value is true, the list will be sorted into reverse order. Instead of
L.sort(); L.reverse(), you can now writeL.sort(reverse=True).The results of sorting are now guaranteed to be stable. This means that two entries with equal keys will be returned in the same order as they were input. For example, you can sort a list of people by name, and then sort the list by age, resulting in a list sorted by age where people with the same age are in name-sorted order.
(All changes to
~list.sortcontributed by Raymond Hettinger.) -
There is a new built-in function
sorted(iterable)that works like the in-placelist.sortmethod but can be used in expressions. The differences are: -
the input may be any iterable;
-
a newly formed copy is sorted, leaving the original intact; and
-
the expression returns the new sorted copy
>>> L = [9,7,8,3,2,4,1,6,5] >>> [10+i for i in sorted(L)] # usable in a list comprehension [11, 12, 13, 14, 15, 16, 17, 18, 19] >>> L # original is left unchanged [9,7,8,3,2,4,1,6,5] >>> sorted('Monty Python') # any iterable may be an input [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y'] >>> # List the contents of a dict sorted by key values >>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5) >>> for k, v in sorted(colormap.iteritems()): ... print k, v ... black 4 blue 2 green 3 red 1 yellow 5(Contributed by Raymond Hettinger.)
-
Integer operations will no longer trigger an
!OverflowWarning. The!OverflowWarningwarning will disappear in Python 2.5. -
The interpreter gained a new switch,
-m, that takes a name, searches for the corresponding module onsys.path, and runs the module as a script. For example, you can now run the Python profiler withpython -m profile. (Contributed by Nick Coghlan.) -
The
eval(expr, globals, locals)andexecfile(filename, globals, locals)functions and theexecstatement now accept any mapping type for the locals parameter. Previously this had to be a regular Python dictionary. (Contributed by Raymond Hettinger.) -
The
zipbuilt-in function and!itertools.izipnow return an empty list if called with no arguments. Previously they raised aTypeErrorexception. This makes them more suitable for use with variable length argument lists:>>> def transpose(array): ... return zip(*array) ... >>> transpose([(1,2,3), (4,5,6)]) [(1, 4), (2, 5), (3, 6)] >>> transpose([]) [](Contributed by Raymond Hettinger.)
-
Encountering a failure while importing a module no longer leaves a partially initialized module object in
sys.modules. The incomplete module object left behind would fool further imports of the same module into succeeding, leading to confusing errors. (Fixed by Tim Peters.) -
Noneis now a constant; code that binds a new value to the nameNoneis now a syntax error. (Contributed by Raymond Hettinger.)
Optimizations
- The inner loops for list and tuple slicing were optimized and now run about one-third faster. The inner loops for dictionaries were also optimized, resulting in performance boosts for
~dict.keys,~dict.values,~dict.items,!iterkeys,!itervalues, and!iteritems. (Contributed by Raymond Hettinger.) - The machinery for growing and shrinking lists was optimized for speed and for space efficiency. Appending and popping from lists now runs faster due to more efficient code paths and less frequent use of the underlying system
realloc. List comprehensions also benefit.list.extendwas also optimized and no longer converts its argument into a temporary list before extending the base list. (Contributed by Raymond Hettinger.) list,tuple,map,filter, andzipnow run several times faster with non-sequence arguments that supply a~object.__len__method. (Contributed by Raymond Hettinger.)- The methods
!list.__getitem__,!dict.__getitem__, and!dict.__contains__are now implemented as!method_descriptorobjects rather than!wrapper_descriptorobjects. This form of access doubles their performance and makes them more suitable for use as arguments to functionals:map(mydict.__getitem__, keylist). (Contributed by Raymond Hettinger.) - Added a new opcode,
LIST_APPEND, that simplifies the generated bytecode for list comprehensions and speeds them up by about a third. (Contributed by Raymond Hettinger.) - The peephole bytecode optimizer has been improved to produce shorter, faster bytecode; remarkably, the resulting bytecode is more readable. (Enhanced by Raymond Hettinger.)
- String concatenations in statements of the form
s = s + "abc"ands += "abc"are now performed more efficiently in certain circumstances. This optimization won't be present in other Python implementations such as Jython, so you shouldn't rely on it; using the~str.joinmethod of strings is still recommended when you want to efficiently glue a large number of strings together. (Contributed by Armin Rigo.)
The net result of the 2.4 optimizations is that Python 2.4 runs the pystone benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2. (pystone is not a particularly good benchmark, but it's the most commonly used measurement of Python's performance. Your own applications may show greater or smaller benefits from Python 2.4.)
New, Improved, and Deprecated Modules
As usual, Python's standard library received a number of enhancements and bug fixes. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the CVS logs for all the details.
-
The
!asyncoremodule's!loopfunction now has a count parameter that lets you perform a limited number of passes through the polling loop. The default is still to loop forever. -
The
base64module now has more complete3548support for Base64, Base32, and Base16 encoding and decoding, including optional case folding and optional alternative alphabets. (Contributed by Barry Warsaw.) -
The
bisectmodule now has an underlying C implementation for improved performance. (Contributed by Dmitry Vasiliev.) -
The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang, was integrated into 2.4. The new encodings are:
-
Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz
-
Chinese (ROC): big5, cp950
-
Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004, shift-jis, shift-jisx0213, shift-jis-2004
-
Korean: cp949, euc-kr, johab, iso-2022-kr
-
Some other new encodings were added: HP Roman8, ISO_8859-11, ISO_8859-16, PCTP-154, and TIS-620.
-
The UTF-8 and UTF-16 codecs now cope better with receiving partial input. Previously the
~codecs.StreamReaderclass would try to read more data, making it impossible to resume decoding from the stream. The~codecs.StreamReader.readmethod will now return as much data as it can and future calls will resume decoding where previous ones left off. (Implemented by Walter Dörwald.) -
There is a new
collectionsmodule for various specialized collection datatypes. Currently it contains just one type,~collections.deque, a double-ended queue that supports efficiently adding and removing elements from either end:>>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> d.append('j') # add a new entry to the right side >>> d.appendleft('f') # add a new entry to the left side >>> d # show the representation of the deque deque(['f', 'g', 'h', 'i', 'j']) >>> d.pop() # return and remove the rightmost item 'j' >>> d.popleft() # return and remove the leftmost item 'f' >>> list(d) # list the contents of the deque ['g', 'h', 'i'] >>> 'h' in d # search the deque TrueSeveral modules, such as the
queueandthreadingmodules, now take advantage ofcollections.dequefor improved performance. (Contributed by Raymond Hettinger.) -
The
ConfigParser <configparser>classes have been enhanced slightly. The~configparser.ConfigParser.readmethod now returns a list of the files that were successfully parsed, and the~configparser.ConfigParser.setmethod raisesTypeErrorif passed a value argument that isn't a string. (Contributed by John Belmonte and David Goodger.) -
The
cursesmodule now supports the ncurses extension~curses.use_default_colors. On platforms where the terminal supports transparency, this makes it possible to use a transparent background. (Contributed by Jörg Lehmann.) -
The
difflibmodule now includes an~difflib.HtmlDiffclass that creates an HTML table showing a side by side comparison of two versions of a text. (Contributed by Dan Gass.) -
The
emailpackage was updated to version 3.0, which dropped various deprecated APIs and removes support for Python versions earlier than 2.3. The 3.0 version of the package uses a new incremental parser for MIME messages, available in the!email.FeedParsermodule. The new parser doesn't require reading the entire message into memory, and doesn't raise exceptions if a message is malformed; instead it records any problems in the!defectattribute of the message. (Developed by Anthony Baxter, Barry Warsaw, Thomas Wouters, and others.) -
The
heapqmodule has been converted to C. The resulting tenfold improvement in speed makes the module suitable for handling high volumes of data. In addition, the module has two new functions~heapq.nlargestand~heapq.nsmallestthat use heaps to find the N largest or smallest values in a dataset without the expense of a full sort. (Contributed by Raymond Hettinger.) -
The
httplib <http>module now contains constants for HTTP status codes defined in various HTTP-related RFC documents. Constants have names such as!OK,!CREATED,!CONTINUE, and!MOVED_PERMANENTLY; use pydoc to get a full list. (Contributed by Andrew Eland.) -
The
imaplibmodule now supports IMAP's THREAD command (contributed by Yves Dionne) and new~imaplib.IMAP4.deleteacland~imaplib.IMAP4.myrightsmethods (contributed by Arnaud Mazin). -
The
itertoolsmodule gained agroupby(iterable[, *func*])function. iterable is something that can be iterated over to return a stream of elements, and the optional func parameter is a function that takes an element and returns a key value; if omitted, the key is simply the element itself.~itertools.groupbythen groups the elements into subsequences which have matching values of the key, and returns a series of 2-tuples containing the key value and an iterator over the subsequence.Here's an example to make this clearer. The key function simply returns whether a number is even or odd, so the result of
~itertools.groupbyis to return consecutive runs of odd or even numbers. :>>> import itertools >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14] >>> for key_val, it in itertools.groupby(L, lambda x: x % 2): ... print key_val, list(it) ... 0 [2, 4, 6] 1 [7] 0 [8] 1 [9, 11] 0 [12, 14] >>>~itertools.groupbyis typically used with sorted input. The logic for~itertools.groupbyis similar to the Unixuniqfilter which makes it handy for eliminating, counting, or identifying duplicate elements:>>> word = 'abracadabra' >>> letters = sorted(word) # Turn string into a sorted list of letters >>> letters ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] >>> for k, g in itertools.groupby(letters): ... print k, list(g) ... a ['a', 'a', 'a', 'a', 'a'] b ['b', 'b'] c ['c'] d ['d'] r ['r', 'r'] >>> # List unique letters >>> [k for k, g in groupby(letters)] ['a', 'b', 'c', 'd', 'r'] >>> # Count letter occurrences >>> [(k, len(list(g))) for k, g in groupby(letters)] [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)](Contributed by Hye-Shik Chang.)
-
itertoolsalso gained a function namedtee(iterator, N)that returns N independent iterators that replicate iterator. If N is omitted, the default is 2. :>>> L = [1,2,3] >>> i1, i2 = itertools.tee(L) >>> i1,i2 (<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>) >>> list(i1) # Run the first iterator to exhaustion [1, 2, 3] >>> list(i2) # Run the second iterator to exhaustion [1, 2, 3]Note that
~itertools.teehas to keep copies of the values returned by the iterator; in the worst case, it may need to keep all of them. This should therefore be used carefully if the leading iterator can run far ahead of the trailing iterator in a long stream of inputs. If the separation is large, then you might as well uselistinstead. When the iterators track closely with one another,~itertools.teeis ideal. Possible applications include bookmarking, windowing, or lookahead iterators. (Contributed by Raymond Hettinger.) -
A number of functions were added to the
localemodule, such as~locale.bind_textdomain_codesetto specify a particular encoding and a family of!l\*gettextfunctions that return messages in the chosen encoding. (Contributed by Gustavo Niemeyer.) -
Some keyword arguments were added to the
loggingpackage's~logging.basicConfigfunction to simplify log configuration. The default behavior is to log messages to standard error, but various keyword arguments can be specified to log to a particular file, change the logging format, or set the logging level. For example:import logging logging.basicConfig(filename='/var/log/application.log', level=0, # Log all messages format='%(levelname):%(process):%(thread):%(message)')Other additions to the
loggingpackage include alog(level, msg)convenience method, as well as a~logging.handlers.TimedRotatingFileHandlerclass that rotates its log files at a timed interval. The module already had~logging.handlers.RotatingFileHandler, which rotated logs once the file exceeded a certain size. Both classes derive from a new~logging.handlers.BaseRotatingHandlerclass that can be used to implement other rotating handlers.(Changes implemented by Vinay Sajip.)
-
The
marshalmodule now shares interned strings on unpacking a data structure. This may shrink the size of certain pickle strings, but the primary effect is to make.pycfiles significantly smaller. (Contributed by Martin von Löwis.) -
The
!nntplibmodule's!NNTPclass gained!descriptionand!descriptionsmethods to retrieve newsgroup descriptions for a single group or for a range of groups. (Contributed by Jürgen A. Erhard.) -
Two new functions were added to the
operatormodule,attrgetter(attr)anditemgetter(index). Both functions return callables that take a single argument and return the corresponding attribute or item; these callables make excellent data extractors when used withmaporsorted. For example:>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)] >>> map(operator.itemgetter(0), L) ['c', 'd', 'a', 'b'] >>> map(operator.itemgetter(1), L) [2, 1, 4, 3] >>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item [('d', 1), ('c', 2), ('b', 3), ('a', 4)](Contributed by Raymond Hettinger.)
-
The
optparsemodule was updated in various ways. The module now passes its messages throughgettext.gettext, making it possible to internationalize Optik's help and error messages. Help messages for options can now include the string'%default', which will be replaced by the option's default value. (Contributed by Greg Ward.) -
The long-term plan is to deprecate the
!rfc822module in some future Python release in favor of theemailpackage. To this end, theemail.Utils.formatdate <email.utils.formatdate>function has been changed to make it usable as a replacement for!rfc822.formatdate. You may want to write new e-mail processing code with this in mind. (Change implemented by Anthony Baxter.) -
A new
urandom(n)function was added to theosmodule, returning a string containing n bytes of random data. This function provides access to platform-specific sources of randomness such as/dev/urandomon Linux or the Windows CryptoAPI. (Contributed by Trevor Perrin.) -
Another new function:
os.path.lexists(path)returns true if the file specified by path exists, whether or not it's a symbolic link. This differs from the existingos.path.exists(path)function, which returns false if path is a symlink that points to a destination that doesn't exist. (Contributed by Beni Cherniavsky.) -
A new
~os.getsidfunction was added to theposixmodule that underlies theosmodule. (Contributed by J. Raynor.) -
The
poplibmodule now supports POP over SSL. (Contributed by Hector Urtubia.) -
The
profilemodule can now profile C extension functions. (Contributed by Nick Bastin.) -
The
randommodule has a new method calledgetrandbits(N)that returns a long integer N bits in length. The existing~random.randrangemethod now uses~random.getrandbitswhere appropriate, making generation of arbitrarily large random numbers more efficient. (Contributed by Raymond Hettinger.) -
The regular expression language accepted by the
remodule was extended with simple conditional expressions, written as(?(group)A|B). group is either a numeric group ID or a group name defined with(?P<group>...)earlier in the expression. If the specified group matched, the regular expression pattern A will be tested against the string; if the group didn't match, the pattern B will be used instead. (Contributed by Gustavo Niemeyer.) -
The
remodule is also no longer recursive, thanks to a massive amount of work by Gustavo Niemeyer. In a recursive regular expression engine, certain patterns result in a large amount of C stack space being consumed, and it was possible to overflow the stack. For example, if you matched a 30000-byte string ofacharacters against the expression(a|b)+, one stack frame was consumed per character. Python 2.3 tried to check for stack overflow and raise aRuntimeErrorexception, but certain patterns could sidestep the checking and if you were unlucky Python could segfault. Python 2.4's regular expression engine can match this pattern without problems. -
The
signalmodule now performs tighter error-checking on the parameters to thesignal.signalfunction. For example, you can't set a handler on the~signal.SIGKILLsignal; previous versions of Python would quietly accept this, but 2.4 will raise aRuntimeErrorexception. -
Two new functions were added to the
socketmodule.~socket.socketpairreturns a pair of connected sockets andgetservbyport(port)looks up the service name for a given port number. (Contributed by Dave Cole and Barry Warsaw.) -
The
!sys.exitfuncfunction has been deprecated. Code should be using the existingatexitmodule, which correctly handles calling multiple exit functions. Eventually!sys.exitfuncwill become a purely internal interface, accessed only byatexit. -
The
tarfilemodule now generates GNU-format tar files by default. (Contributed by Lars Gustäbel.) -
The
threadingmodule now has an elegantly simple way to support thread-local data. The module contains a~threading.localclass whose attribute values are local to different threads. :import threading data = threading.local() data.number = 42 data.url = ('www.python.org', 80)Other threads can assign and retrieve their own values for the
!numberand!urlattributes. You can subclass~threading.localto initialize attributes or to add methods. (Contributed by Jim Fulton.) -
The
timeitmodule now automatically disables periodic garbage collection during the timing loop. This change makes consecutive timings more comparable. (Contributed by Raymond Hettinger.) -
The
weakrefmodule now supports a wider variety of objects including Python functions, class instances, sets, frozensets, deques, arrays, files, sockets, and regular expression pattern objects. (Contributed by Raymond Hettinger.) -
The
xmlrpclib <xmlrpc.client>module now supports a multi-call extension for transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by Brian Quinlan.) -
The
!mpz,!rotor, and!xreadlinesmodules have been removed.
cookielib
In order to store cookies across sessions, two implementations of cookie jars are provided: one that stores cookies in the Netscape format so applications can use the Mozilla or Lynx cookie files, and one that stores cookies in the same format as the Perl libwww library.
urllib2 <urllib.request> has been changed to interact with cookielib <http.cookiejar>: ~urllib.request.HTTPCookieProcessor manages a cookie jar that is used when accessing URLs.
This module was contributed by John J. Lee.
doctest
The doctest module underwent considerable refactoring thanks to Edward Loper and Tim Peters. Testing can still be as simple as running doctest.testmod, but the refactorings allow customizing the module's operation in various ways
The new ~doctest.DocTestFinder class extracts the tests from a given object's docstrings:
def f (x, y):
""">>> f(2,2)
4
>>> f(3,2)
6
"""
return x*y
finder = doctest.DocTestFinder()
# Get list of DocTest instances
tests = finder.find(f)
The new ~doctest.DocTestRunner class then runs individual tests and can produce a summary of the results:
runner = doctest.DocTestRunner()
for t in tests:
tried, failed = runner.run(t)
runner.summarize(verbose=1)
The above example produces the following output:
1 items passed all tests:
2 tests in f
2 tests in 1 items.
2 passed and 0 failed.
Test passed.
~doctest.DocTestRunner uses an instance of the ~doctest.OutputChecker class to compare the expected output with the actual output. This class takes a number of different flags that customize its behaviour; ambitious users can also write a completely new subclass of ~doctest.OutputChecker.
The default output checker provides a number of handy features. For example, with the doctest.ELLIPSIS option flag, an ellipsis (...) in the expected output matches any substring, making it easier to accommodate outputs that vary in minor ways:
def o (n):
""">>> o(1)
<__main__.C instance at 0x...>
>>>
"""
Another special string, <BLANKLINE>, matches a blank line:
def p (n):
""">>> p(1)
<BLANKLINE>
>>>
"""
Another new capability is producing a diff-style display of the output by specifying the doctest.REPORT_UDIFF (unified diffs), doctest.REPORT_CDIFF (context diffs), or doctest.REPORT_NDIFF (delta-style) option flags. For example:
def g (n):
""">>> g(4)
here
is
a
lengthy
>>>"""
L = 'here is a rather lengthy list of words'.split()
for word in L[:n]:
print word
Running the above function's tests with doctest.REPORT_UDIFF specified, you get the following output:
**********************************************************************
File "t.py", line 15, in g
Failed example:
g(4)
Differences (unified diff with -expected +actual):
@@ -2,3 +2,3 @@
is
a
-lengthy
+rather
**********************************************************************
Build and C API Changes
Some of the changes to Python's build process and to the C API are:
- Three new convenience macros were added for common return values from extension functions:
Py_RETURN_NONE,Py_RETURN_TRUE, andPy_RETURN_FALSE. (Contributed by Brett Cannon.) - Another new macro,
Py_CLEAR, decreases the reference count of obj and sets obj to the null pointer. (Contributed by Jim Fulton.) - A new function,
PyTuple_Pack(N, obj1, obj2, ..., objN), constructs tuples from a variable length argument list of Python objects. (Contributed by Raymond Hettinger.) - A new function,
PyDict_Contains(d, k), implements fast dictionary lookups without masking exceptions raised during the look-up process. (Contributed by Raymond Hettinger.) - The
Py_IS_NANmacro returns 1 if its float or double argument X is a NaN. (Contributed by Tim Peters.) - C code can avoid unnecessary locking by using the new
!PyEval_ThreadsInitializedfunction to tell if any thread operations have been performed. If this function returns false, no lock operations are needed. (Contributed by Nick Coghlan.) - A new function,
PyArg_VaParseTupleAndKeywords, is the same asPyArg_ParseTupleAndKeywordsbut takes ava_listinstead of a number of arguments. (Contributed by Greg Chapman.) - A new method flag,
METH_COEXIST, allows a function defined in slots to co-exist with aPyCFunctionhaving the same name. This can halve the access time for a method such as!set.__contains__. (Contributed by Raymond Hettinger.) - Python can now be built with additional profiling for the interpreter itself, intended as an aid to people developing the Python core. Providing
!--enable-profilingto theconfigurescript will let you profile the interpreter withgprof, and providing the!--with-tscswitch enables profiling using the Pentium's Time-Stamp-Counter register. Note that the!--with-tscswitch is slightly misnamed, because the profiling feature also works on the PowerPC platform, though that processor architecture doesn't call that register "the TSC register". (Contributed by Jeremy Hylton.) - The
!tracebackobjecttype has been renamed to!PyTracebackObject.
Port-Specific Changes
- The Windows port now builds under MSVC++ 7.1 as well as version 6. (Contributed by Martin von Löwis.)
Porting to Python 2.4
This section lists previously described changes that may require changes to your code:
- Left shifts and hexadecimal/octal constants that are too large no longer trigger a
FutureWarningand return a value limited to 32 or 64 bits; instead they return a long integer. - Integer operations will no longer trigger an
!OverflowWarning. The!OverflowWarningwarning will disappear in Python 2.5. - The
zipbuilt-in function and!itertools.izipnow return an empty list instead of raising aTypeErrorexception if called with no arguments. - You can no longer compare the
~datetime.dateand~datetime.datetimeinstances provided by thedatetimemodule. Two instances of different classes will now always be unequal, and relative comparisons (<,>) will raise aTypeError. !dircache.listdirnow passes exceptions to the caller instead of returning empty lists.LexicalHandler.startDTD <xml.sax.handler.LexicalHandler.startDTD>used to receive the public and system IDs in the wrong order. This has been corrected; applications relying on the wrong order need to be fixed.fcntl.ioctlnow warns if the mutate argument is omitted and relevant.- The
tarfilemodule now generates GNU-format tar files by default. - Encountering a failure while importing a module no longer leaves a partially initialized module object in
sys.modules. Noneis now a constant; code that binds a new value to the nameNoneis now a syntax error.- The
signal.signalfunction now raises aRuntimeErrorexception for certain illegal values; previously these errors would pass silently. For example, you can no longer set a handler on the~signal.SIGKILLsignal.
Acknowledgements
What's New in Python 2.5
This article explains the new features in Python 2.5. The final release of Python 2.5 is scheduled for August 2006; 356 describes the planned release schedule. Python 2.5 was released on September 19, 2006.
The changes in Python 2.5 are an interesting mix of language and library improvements. The library enhancements will be more important to Python's user community, I think, because several widely useful packages were added. New modules include ElementTree for XML processing (xml.etree.ElementTree), the SQLite database module (sqlite3), and the ctypes module for calling C functions.
The language changes are of middling significance. Some pleasant new features were added, but most of them aren't features that you'll use every day. Conditional expressions were finally added to the language using a novel syntax; see section pep-308. The new 'with' statement will make writing cleanup code easier (section pep-343). Values can now be passed into generators (section pep-342). Imports are now visible as either absolute or relative (section pep-328). Some corner cases of exception handling are handled better (section pep-341). All these improvements are worthwhile, but they're improvements to one specific language feature or another; none of them are broad modifications to Python's semantics.
As well as the language and library additions, other improvements and bugfixes were made throughout the source tree. A search through the SVN change logs finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and 2.5. (Both figures are likely to be underestimates.)
This article doesn't try to be a complete specification of the new features; instead changes are briefly introduced using helpful examples. For full details, you should always refer to the documentation for Python 2.5 at https://docs.python.org. If you want to understand the complete implementation and design rationale, refer to the PEP for a particular new feature.
Comments, suggestions, and error reports for this document are welcome; please e-mail them to the author or open a bug in the Python bug tracker.
PEP 308: Conditional Expressions
For a long time, people have been requesting a way to write conditional expressions, which are expressions that return value A or value B depending on whether a Boolean value is true or false. A conditional expression lets you write a single assignment statement that has the same effect as the following:
if condition:
x = true_value
else:
x = false_value
There have been endless tedious discussions of syntax on both python-dev and comp.lang.python. A vote was even held that found the majority of voters wanted conditional expressions in some form, but there was no syntax that was preferred by a clear majority. Candidates included C's cond ? true_v : false_v, if cond then true_v else false_v, and 16 other variations.
Guido van Rossum eventually chose a surprising syntax:
x = true_value if condition else false_value
Evaluation is still lazy as in existing Boolean expressions, so the order of evaluation jumps around a bit. The condition expression in the middle is evaluated first, and the true_value expression is evaluated only if the condition was true. Similarly, the false_value expression is only evaluated when the condition is false.
This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C's c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the 'common case' and one value is an 'exceptional case', used only on rarer occasions when the condition isn't met. The conditional syntax makes this pattern a bit more obvious:
contents = ((doc + '\n') if doc else '')
I read the above statement as meaning "here contents is usually assigned a value of doc+'\n'; sometimes doc is empty, in which special case an empty string is returned." I doubt I will use conditional expressions very often where there isn't a clear common and uncommon case.
There was some discussion of whether the language should require surrounding conditional expressions with parentheses. The decision was made to not require parentheses in the Python language's grammar, but as a matter of style I think you should always use them. Consider these two statements:
# First version -- no parens
level = 1 if logging else 0
# Second version -- with parens
level = (1 if logging else 0)
In the first version, I think a reader's eye might group the statement into 'level = 1', 'if logging', 'else 0', and think that the condition decides whether the assignment to level is performed. The second version reads better, in my opinion, because it makes it clear that the assignment is always performed and the choice is being made between two values.
Another reason for including the brackets: a few odd combinations of list comprehensions and lambdas could look like incorrect conditional expressions. See 308 for some examples. If you put parentheses around your conditional expressions, you won't run into this case.
308 - Conditional Expressions
PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas Wouters.
PEP 309: Partial Function Application
The functools module is intended to contain tools for functional-style programming.
One useful tool in this module is the ~functools.partial function. For programs written in a functional style, you'll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function f(a, b, c); you could create a new function g(b, c) that was equivalent to f(1, b, c). This is called "partial function application".
~functools.partial takes the arguments (function, arg1, arg2, ... kwarg1=value1, kwarg2=value2). The resulting object is callable, so you can just call it to invoke function with the filled-in arguments.
Here's a small but realistic example:
import functools
def log (message, subsystem):
"Write the contents of 'message' to the specified subsystem."
print '%s: %s' % (subsystem, message)
...
server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
Here's another example, from a program that uses PyGTK. Here a context-sensitive pop-up menu is being constructed dynamically. The callback provided for the menu option is a partially applied version of the open_item() method, where the first argument has been provided. :
...
class Application:
def open_item(self, path):
...
def init (self):
open_func = functools.partial(self.open_item, item_path)
popup_menu.append( ("Open", open_func, 1) )
Another function in the functools module is the update_wrapper(wrapper, wrapped) function that helps you write well-behaved decorators. ~functools.update_wrapper copies the name, module, and docstring attribute to a wrapper function so that tracebacks inside the wrapped function are easier to understand. For example, you might write:
def my_decorator(f):
def wrapper(*args, **kwds):
print 'Calling decorated function'
return f(*args, **kwds)
functools.update_wrapper(wrapper, f)
return wrapper
~functools.wraps is a decorator that can be used inside your own decorators to copy the wrapped function's information. An alternate version of the previous example would be:
def my_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
print 'Calling decorated function'
return f(*args, **kwds)
return wrapper
309 - Partial Function Application
PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick Coghlan, with adaptations by Raymond Hettinger.
PEP 314: Metadata for Python Software Packages v1.1
Some simple dependency support was added to Distutils. The !setup function now has requires, provides, and obsoletes keyword parameters. When you build a source distribution using the sdist command, the dependency information will be recorded in the PKG-INFO file.
Another new keyword parameter is download_url, which should be set to a URL for the package's source code. This means it's now possible to look up an entry in the package index, determine the dependencies for a package, and download the required packages. :
VERSION = '1.0'
setup(name='PyPackage',
version=VERSION,
requires=['numarray', 'zlib (>=1.1.4)'],
obsoletes=['OldPackage']
download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
% VERSION),
)
Another new enhancement to the Python package index at https://pypi.org is storing source and binary archives for a package. The new upload Distutils command will upload a package to the repository.
Before a package can be uploaded, you must be able to build a distribution using the sdist Distutils command. Once that works, you can run python setup.py upload to add your package to the PyPI archive. Optionally you can GPG-sign the package by supplying the !--sign and !--identity options.
Package uploading was implemented by Martin von Löwis and Richard Jones.
314 - Metadata for Python Software Packages v1.1
PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake; implemented by Richard Jones and Fred Drake.
PEP 328: Absolute and Relative Imports
The simpler part of 328 was implemented in Python 2.4: parentheses could now be used to enclose the names imported from a module using the from ... import ... statement, making it easier to import many different names.
The more complicated part has been implemented in Python 2.5: importing a module can be specified to use absolute or package-relative imports. The plan is to move toward making absolute imports the default in future versions of Python.
Let's say you have a package directory like this:
pkg/
pkg/__init__.py
pkg/main.py
pkg/string.py
This defines a package named pkg containing the pkg.main and pkg.string submodules.
Consider the code in the main.py module. What happens if it executes the statement import string? In Python 2.4 and earlier, it will first look in the package's directory to perform a relative import, finds pkg/string.py, imports the contents of that file as the pkg.string module, and that module is bound to the name string in the pkg.main module's namespace.
That's fine if pkg.string was what you wanted. But what if you wanted Python's standard string module? There's no clean way to ignore pkg.string and look for the standard module; generally you had to look at the contents of sys.modules, which is slightly unclean. Holger Krekel's !py.std package provides a tidier way to perform imports from the standard library, import py; py.std.string.join(), but that package isn't available on all Python installations.
Reading code which relies on relative imports is also less clear, because a reader may be confused about which module, string or pkg.string, is intended to be used. Python users soon learned not to duplicate the names of standard library modules in the names of their packages' submodules, but you can't protect against having your submodule's name being used for a new module added in a future version of Python.
In Python 2.5, you can switch import's behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute-import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import string will always find the standard library's version. It's suggested that users should begin using absolute imports as much as possible, so it's preferable to begin writing from pkg import string in your code.
Relative imports are still possible by adding a leading period to the module name when using the from ... import form:
# Import names from pkg.string
from .string import name1, name2
# Import pkg.string
from . import string
This imports the string module relative to the current package, so in pkg.main this will import name1 and name2 from pkg.string. Additional leading periods perform the relative import starting from the parent of the current package. For example, code in the A.B.C module can do:
from . import D # Imports A.B.D
from .. import E # Imports A.E
from ..F import G # Imports A.F.G
Leading periods cannot be used with the import modname form of the import statement, only the from ... import form.
328 - Imports: Multi-Line and Absolute/Relative
PEP written by Aahz; implemented by Thomas Wouters.
https://pylib.readthedocs.io/
The py library by Holger Krekel, which contains the !py.std package.
PEP 338: Executing Modules as Scripts
The -m switch added in Python 2.4 to execute a module as a script gained a few more abilities. Instead of being implemented in C code inside the Python interpreter, the switch now uses an implementation in a new module, runpy.
The runpy module implements a more sophisticated import mechanism so that it's now possible to run modules in a package such as !pychecker.checker. The module also supports alternative import mechanisms such as the zipimport module. This means you can add a .zip archive's path to sys.path and then use the -m switch to execute code from the archive.
338 - Executing modules as scripts
PEP written and implemented by Nick Coghlan.
PEP 341: Unified try/except/finally
Until Python 2.5, the try statement came in two flavours. You could use a finally block to ensure that code is always executed, or one or more except blocks to catch specific exceptions. You couldn't combine both !except blocks and a !finally block, because generating the right bytecode for the combined version was complicated and it wasn't clear what the semantics of the combined statement should be.
Guido van Rossum spent some time working with Java, which does support the equivalent of combining except blocks and a finally block, and this clarified what the statement should mean. In Python 2.5, you can now write:
try:
block-1 ...
except Exception1:
handler-1 ...
except Exception2:
handler-2 ...
else:
else-block
finally:
final-block
The code in block-1 is executed. If the code raises an exception, the various except blocks are tested: if the exception is of class Exception1, handler-1 is executed; otherwise if it's of class Exception2, handler-2 is executed, and so forth. If no exception is raised, the else-block is executed.
No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.
341 - Unifying try-except and try-finally
PEP written by Georg Brandl; implementation by Thomas Lee.
PEP 342: New Generator Features
Python 2.5 adds a simple way to pass values into a generator. As introduced in Python 2.3, generators only produce output; once a generator's code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. Sometimes the ability to pass in some information would be useful. Hackish solutions to this include making the generator's code look at a global variable and then changing the global variable's value, or passing in some mutable object that callers then modify.
To refresh your memory of basic generators, here's a simple example:
def counter (maximum):
i = 0
while i < maximum:
yield i
i += 1
When you call counter(10), the result is an iterator that returns the values from 0 up to 9. On encountering the yield statement, the iterator returns the provided value and suspends the function's execution, preserving the local variables. Execution resumes on the following call to the iterator's next method, picking up after the !yield statement.
In Python 2.3, yield was a statement; it didn't return any value. In 2.5, !yield is now an expression, returning a value that can be assigned to a variable or otherwise operated on:
val = (yield i)
I recommend that you always put parentheses around a yield expression when you're doing something with the returned value, as in the above example. The parentheses aren't always necessary, but it's easier to always add them instead of having to remember when they're needed.
(342 explains the exact rules, which are that a yield-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write val = yield i but have to use parentheses when there's an operation, as in val = (yield i) + 12.)
Values are sent into a generator by calling its send(value) method. The generator's code is then resumed and the yield expression returns the specified value. If the regular next method is called, the !yield returns None.
Here's the previous example, modified to allow changing the value of the internal counter. :
def counter (maximum):
i = 0
while i < maximum:
val = (yield i)
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
And here's an example of changing the counter:
>>> it = counter(10)
>>> print it.next()
0
>>> print it.next()
1
>>> print it.send(8)
8
>>> print it.next()
9
>>> print it.next()
Traceback (most recent call last):
File "t.py", line 15, in ?
print it.next()
StopIteration
yield will usually return None, so you should always check for this case. Don't just use its value in expressions unless you're sure that the ~generator.send method will be the only method used to resume your generator function.
In addition to ~generator.send, there are two other new methods on generators:
-
throw(type, value=None, traceback=None)is used to raise an exception inside the generator; the exception is raised by theyieldexpression where the generator's execution is paused. -
~generator.closeraises a newGeneratorExitexception inside the generator to terminate the iteration. On receiving this exception, the generator's code must either raiseGeneratorExitorStopIteration. Catching theGeneratorExitexception and returning a value is illegal and will trigger aRuntimeError; if the function raises some other exception, that exception is propagated to the caller.~generator.closewill also be called by Python's garbage collector when the generator is garbage-collected.If you need to run cleanup code when a
GeneratorExitoccurs, I suggest using atry: ... finally:suite instead of catchingGeneratorExit.
The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers.
Generators also become coroutines, a more generalized form of subroutines. Subroutines are entered at one point and exited at another point (the top of the function, and a return statement), but coroutines can be entered, exited, and resumed at many different points (the yield statements). We'll have to figure out patterns for using coroutines effectively in Python.
The addition of the ~generator.close method has one side effect that isn't obvious. ~generator.close is called when a generator is garbage-collected, so this means the generator's code gets one last chance to run before the generator is destroyed. This last chance means that try...finally statements in generators can now be guaranteed to work; the finally clause will now always get a chance to run. The syntactic restriction that you couldn't mix yield statements with a try...finally suite has therefore been removed. This seems like a minor bit of language trivia, but using generators and try...finally is actually necessary in order to implement the with statement described by 343. I'll look at this new statement in the following section.
Another even more esoteric effect of this change: previously, the !gi_frame attribute of a generator was always a frame object. It's now possible for !gi_frame to be None once the generator has been exhausted.
342 - Coroutines via Enhanced Generators
PEP written by Guido van Rossum and Phillip J. Eby; implemented by Phillip J. Eby. Includes examples of some fancier uses of generators as coroutines.
Earlier versions of these features were proposed in 288 by Raymond Hettinger and 325 by Samuele Pedroni.
https://en.wikipedia.org/wiki/Coroutine
The Wikipedia entry for coroutines.
https://web.archive.org/web/20160321211320/http://www.sidhe.org/~dan/blog/archives/000178.html
An explanation of coroutines from a Perl point of view, written by Dan Sugalski.
PEP 343: The 'with' statement
The 'with' statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I'll discuss the statement as it will commonly be used. In the next section, I'll examine the implementation details and show how to write objects for use with this statement.
The 'with' statement is a new control-flow structure whose basic structure is:
with expression [as variable]:
with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has ~object.__enter__ and ~object.__exit__ methods.
The object's ~object.__enter__ is called before with-block is executed and therefore can run set-up code. It also may return a value that is bound to the name variable, if given. (Note carefully that variable is not assigned the result of expression.)
After execution of the with-block is finished, the object's ~object.__exit__ method is called, even if the block raised an exception, and can therefore run clean-up code.
To enable the statement in Python 2.5, you need to add the following directive to your module:
from __future__ import with_statement
The statement will always be enabled in Python 2.6.
Some standard Python objects now support the context management protocol and can be used with the 'with' statement. File objects are one example:
with open('/etc/passwd', 'r') as f:
for line in f:
print line
... more processing code ...
After this statement has executed, the file object in f will have been automatically closed, even if the for loop raised an exception part-way through the block.
[!NOTE] In this case, f is the same object created by
open, because~object.__enter__returns self.
The threading module's locks and condition variables also support the 'with' statement:
lock = threading.Lock()
with lock:
# Critical section of code
...
The lock is acquired before the block is executed and always released once the block is complete.
The new ~decimal.localcontext function in the decimal module makes it easy to save and restore the current decimal context, which encapsulates the desired precision and rounding characteristics for computations:
from decimal import Decimal, Context, localcontext
# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()
with localcontext(Context(prec=16)):
# All code in this block uses a precision of 16 digits.
# The original context is restored on exiting the block.
print v.sqrt()
Writing Context Managers
Under the hood, the 'with' statement is fairly complicated. Most people will only use '!with' in company with existing objects and don't need to know these details, so you can skip the rest of this section if you like. Authors of new objects will need to understand the details of the underlying implementation and should keep reading.
A high-level explanation of the context management protocol is:
- The expression is evaluated and should result in an object called a "context manager". The context manager must have
~object.__enter__and~object.__exit__methods. - The context manager's
~object.__enter__method is called. The value returned is assigned to VAR. If no'as VAR'clause is present, the value is simply discarded. - The code in BLOCK is executed.
- If BLOCK raises an exception, the
__exit__(type, value, traceback)is called with the exception details, the same values returned bysys.exc_info. The method's return value controls whether the exception is re-raised: any false value re-raises the exception, andTruewill result in suppressing it. You'll only rarely want to suppress the exception, because if you do the author of the code containing the 'with' statement will never realize anything went wrong. - If BLOCK didn't raise an exception, the
~object.__exit__method is still called, but type, value, and traceback are allNone.
Let's think through an example. I won't present detailed code but will only sketch the methods necessary for a database that supports transactions.
(For people unfamiliar with database terminology: a set of changes to the database are grouped into a transaction. Transactions can be either committed, meaning that all the changes are written into the database, or rolled back, meaning that the changes are all discarded and the database is unchanged. See any database textbook for more information.)
Let's assume there's an object representing a database connection. Our goal will be to let the user write code like this:
db_connection = DatabaseConnection()
with db_connection as cursor:
cursor.execute('insert into ...')
cursor.execute('delete from ...')
# ... more operations ...
The transaction should be committed if the code in the block runs flawlessly or rolled back if there's an exception. Here's the basic interface for DatabaseConnection that I'll assume:
class DatabaseConnection:
# Database interface
def cursor (self):
"Returns a cursor object and starts a new transaction"
def commit (self):
"Commits current transaction"
def rollback (self):
"Rolls back current transaction"
The ~object.__enter__ method is pretty easy, having only to start a new transaction. For this application the resulting cursor object would be a useful result, so the method will return it. The user can then add as cursor to their 'with' statement to bind the cursor to a variable name. :
class DatabaseConnection:
...
def __enter__ (self):
# Code to start a new transaction
cursor = self.cursor()
return cursor
The ~object.__exit__ method is the most complicated because it's where most of the work has to be done. The method has to check if an exception occurred. If there was no exception, the transaction is committed. The transaction is rolled back if there was an exception.
In the code below, execution will just fall off the end of the function, returning the default value of None. None is false, so the exception will be re-raised automatically. If you wished, you could be more explicit and add a return statement at the marked location. :
class DatabaseConnection:
...
def __exit__ (self, type, value, tb):
if tb is None:
# No exception, so commit
self.commit()
else:
# Exception occurred, so rollback.
self.rollback()
# return False
The contextlib module
The new contextlib module provides some functions and a decorator that are useful for writing objects for use with the 'with' statement.
The decorator is called ~contextlib.contextmanager, and lets you write a single generator function instead of defining a new class. The generator should yield exactly one value. The code up to the yield will be executed as the ~object.__enter__ method, and the value yielded will be the method's return value that will get bound to the variable in the 'with' statement's !as clause, if any. The code after the yield will be executed in the ~object.__exit__ method. Any exception raised in the block will be raised by the !yield statement.
Our database example from the previous section could be written using this decorator as:
from contextlib import contextmanager
@contextmanager
def db_transaction (connection):
cursor = connection.cursor()
try:
yield cursor
except:
connection.rollback()
raise
else:
connection.commit()
db = DatabaseConnection()
with db_transaction(db) as cursor:
...
The contextlib module also has a nested(mgr1, mgr2, ...) function that combines a number of context managers so you don't need to write nested 'with' statements. In this example, the single '!with' statement both starts a database transaction and acquires a thread lock:
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
...
Finally, the closing(object) function returns object so that it can be bound to a variable, and calls object.close at the end of the block. :
import urllib, sys
from contextlib import closing
with closing(urllib.urlopen('http://www.yahoo.com')) as f:
for line in f:
sys.stdout.write(line)
343 - The "with" statement
PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland, Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a 'with' statement, which can be helpful in learning how the statement works.
The documentation for the contextlib module.
PEP 352: Exceptions as New-Style Classes
Exception classes can now be new-style classes, not just classic classes, and the built-in Exception class and all the standard built-in exceptions (NameError, ValueError, etc.) are now new-style classes.
The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the inheritance relationships are:
BaseException # New in Python 2.5
|- KeyboardInterrupt
|- SystemExit
|- Exception
|- (all other current built-in exceptions)
This rearrangement was done because people often want to catch all exceptions that indicate program errors. KeyboardInterrupt and SystemExit aren't errors, though, and usually represent an explicit action such as the user hitting Control-C or code calling sys.exit. A bare except: will catch all exceptions, so you commonly need to list KeyboardInterrupt and SystemExit in order to re-raise them. The usual pattern is:
try:
...
except (KeyboardInterrupt, SystemExit):
raise
except:
# Log error...
# Continue running program...
In Python 2.5, you can now write except Exception to achieve the same result, catching all the exceptions that usually indicate errors but leaving KeyboardInterrupt and SystemExit alone. As in previous versions, a bare except: still catches all exceptions.
The goal for Python 3.0 is to require any class raised as an exception to derive from BaseException or some descendant of BaseException, and future releases in the Python 2.x series may begin to enforce this constraint. Therefore, I suggest you begin making all your exception classes derive from Exception now. It's been suggested that the bare except: form should be removed in Python 3.0, but Guido van Rossum hasn't decided whether to do this or not.
Raising of strings as exceptions, as in the statement raise "Error occurred", is deprecated in Python 2.5 and will trigger a warning. The aim is to be able to remove the string-exception feature in a few releases.
352 - Required Superclass for Exceptions
PEP written by Brett Cannon and Guido van Rossum; implemented by Brett Cannon.
PEP 353: Using ssize_t as the index type
A wide-ranging change to Python's C API, using a new Py_ssize_t type definition instead of int, will permit the interpreter to handle more data on 64-bit platforms. This change doesn't affect Python's capacity on 32-bit platforms.
Various pieces of the Python interpreter used C's int type to store sizes or counts; for example, the number of items in a list or tuple were stored in an int. The C compilers for most 64-bit platforms still define int as a 32-bit type, so that meant that lists could only hold up to 2**31 - 1 = 2147483647 items. (There are actually a few different programming models that 64-bit C compilers can use -- see https://unix.org/version2/whatsnew/lp64_wp.html for a discussion -- but the most commonly available model leaves int as 32 bits.)
A limit of 2147483647 items doesn't really matter on a 32-bit platform because you'll run out of memory before hitting the length limit. Each list item requires space for a pointer, which is 4 bytes, plus space for a PyObject representing the item. 2147483647*4 is already more bytes than a 32-bit address space can contain.
It's possible to address that much memory on a 64-bit platform, however. The pointers for a list that size would only require 16 GiB of space, so it's not unreasonable that Python programmers might construct lists that large. Therefore, the Python interpreter had to be changed to use some type other than int, and this will be a 64-bit type on 64-bit platforms. The change will cause incompatibilities on 64-bit machines, so it was deemed worth making the transition now, while the number of 64-bit users is still relatively small. (In 5 or 10 years, we may all be on 64-bit machines, and the transition would be more painful then.)
This change most strongly affects authors of C extension modules. Python strings and container types such as lists and tuples now use Py_ssize_t to store their size. Functions such as PyList_Size now return Py_ssize_t. Code in extension modules may therefore need to have some variables changed to Py_ssize_t.
The PyArg_ParseTuple and Py_BuildValue functions have a new conversion code, n, for Py_ssize_t. PyArg_ParseTuple's s# and t# still output int by default, but you can define the macro !PY_SSIZE_T_CLEAN before including Python.h to make them return Py_ssize_t.
353 has a section on conversion guidelines that extension authors should read to learn about supporting 64-bit platforms.
353 - Using ssize_t as the index type
PEP written and implemented by Martin von Löwis.
PEP 357: The '__index__' method
The NumPy developers had a problem that could only be solved by adding a new special method, ~object.__index__. When using slice notation, as in [start:stop:step], the values of the start, stop, and step indexes must all be either integers or long integers. NumPy defines a variety of specialized integer types corresponding to unsigned and signed integers of 8, 16, 32, and 64 bits, but there was no way to signal that these types could be used as slice indexes.
Slicing can't just use the existing ~object.__int__ method because that method is also used to implement coercion to integers. If slicing used ~object.__int__, floating-point numbers would also become legal slice indexes and that's clearly an undesirable behaviour.
Instead, a new special method called ~object.__index__ was added. It takes no arguments and returns an integer giving the slice index to use. For example:
class C:
def __index__ (self):
return self.value
The return value must be either a Python integer or long integer. The interpreter will check that the type returned is correct, and raises a TypeError if this requirement isn't met.
A corresponding ~PyNumberMethods.nb_index slot was added to the C-level PyNumberMethods structure to let C extensions implement this protocol. PyNumber_Index(obj) can be used in extension code to call the ~object.__index__ function and retrieve its result.
357 - Allowing Any Object to be Used for Slicing
PEP written and implemented by Travis Oliphant.
Other Language Changes
Here are all of the changes that Python 2.5 makes to the core Python language.
-
The
dicttype has a new hook for letting subclasses provide a default value when a key isn't contained in the dictionary. When a key isn't found, the dictionary's__missing__(key)method will be called. This hook is used to implement the new~collections.defaultdictclass in thecollectionsmodule. The following example defines a dictionary that returns zero for any missing key:class zerodict (dict): def __missing__ (self, key): return 0 d = zerodict({1:1, 2:2}) print d[1], d[2] # Prints 1, 2 print d[3], d[4] # Prints 0, 0 -
Both 8-bit and Unicode strings have new
partition(sep)andrpartition(sep)methods that simplify a common use case.The
find(S)method is often used to get an index which is then used to slice the string and obtain the pieces that are before and after the separator.partition(sep)condenses this pattern into a single method call that returns a 3-tuple containing the substring before the separator, the separator itself, and the substring after the separator. If the separator isn't found, the first element of the tuple is the entire string and the other two elements are empty.rpartition(sep)also returns a 3-tuple but starts searching from the end of the string; therstands for 'reverse'.Some examples:
>>> ('http://www.python.org').partition('://') ('http', '://', 'www.python.org') >>> ('file:/usr/share/doc/index.html').partition('://') ('file:/usr/share/doc/index.html', '', '') >>> (u'Subject: a quick question').partition(':') (u'Subject', u':', u' a quick question') >>> 'www.python.org'.rpartition('.') ('www.python', '.', 'org') >>> 'www.python.org'.rpartition(':') ('', '', 'www.python.org')(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
-
The
~str.startswithand~str.endswithmethods of string types now accept tuples of strings to check for. :def is_image_file (filename): return filename.endswith(('.gif', '.jpg', '.tiff'))(Implemented by Georg Brandl following a suggestion by Tom Lynn.)
-
The
minandmaxbuilt-in functions gained akeykeyword parameter analogous to thekeyargument for~list.sort. This parameter supplies a function that takes a single argument and is called for every value in the list;min/maxwill return the element with the smallest/largest return value from this function. For example, to find the longest string in a list, you can do:L = ['medium', 'longest', 'short'] # Prints 'longest' print max(L, key=len) # Prints 'short', because lexicographically 'short' has the largest value print max(L)(Contributed by Steven Bethard and Raymond Hettinger.)
-
Two new built-in functions,
anyandall, evaluate whether an iterator contains any true or false values.anyreturnsTrueif any value returned by the iterator is true; otherwise it will returnFalse.allreturnsTrueonly if all of the values returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and implemented by Raymond Hettinger.) -
The result of a class's
~object.__hash__method can now be either a long integer or a regular integer. If a long integer is returned, the hash of that value is taken. In earlier versions the hash value was required to be a regular integer, but in 2.5 theidbuilt-in was changed to always return non-negative numbers, and users often seem to useid(self)in~object.__hash__methods (though this is discouraged). -
ASCII is now the default encoding for modules. It's now a syntax error if a module contains string literals with 8-bit characters but doesn't have an encoding declaration. In Python 2.4 this triggered a warning, not a syntax error. See
263for how to declare a module's encoding; for example, you might add a line like this near the top of the source file:# -*- coding: latin1 -*- -
A new warning,
UnicodeWarning, is triggered when you attempt to compare a Unicode string and an 8-bit string that can't be converted to Unicode using the default ASCII encoding. The result of the comparison is false:>>> chr(128) == unichr(128) # Can't convert chr(128) to Unicode __main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal False >>> chr(127) == unichr(127) # chr(127) can be converted TruePreviously this would raise a
UnicodeDecodeErrorexception, but in 2.5 this could result in puzzling problems when accessing a dictionary. If you looked upunichr(128)andchr(128)was being used as a key, you'd get aUnicodeDecodeErrorexception. Other changes in 2.5 resulted in this exception being raised instead of suppressed by the code indictobject.cthat implements dictionaries.Raising an exception for such a comparison is strictly correct, but the change might have broken code, so instead
UnicodeWarningwas introduced.(Implemented by Marc-André Lemburg.)
-
One error that Python programmers sometimes make is forgetting to include an
__init__.pymodule in a package directory. Debugging this mistake can be confusing, and usually requires running Python with the-vswitch to log all the paths searched. In Python 2.5, a newImportWarningwarning is triggered when an import would have picked up a directory as a package but no__init__.pywas found. This warning is silently ignored by default; provide the-Wd <-W>option when running the Python executable to display the warning message. (Implemented by Thomas Wouters.) -
The list of base classes in a class definition can now be empty. As an example, this is now legal:
class C(): pass(Implemented by Brett Cannon.)
Interactive Interpreter Changes
In the interactive interpreter, quit and exit have long been strings so that new users get a somewhat helpful message when they try to quit:
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
In Python 2.5, quit and exit are now objects that still produce string representations of themselves, but are also callable. Newbies who try quit() or exit() will now exit the interpreter as they expect. (Implemented by Georg Brandl.)
The Python executable now accepts the standard long options --help and --version; on Windows, it also accepts the /? <-?> option for displaying a help message. (Implemented by Georg Brandl.)
Optimizations
Several of the optimizations were developed at the NeedForSpeed sprint, an event held in Reykjavik, Iceland, from May 21--28 2006. The sprint focused on speed enhancements to the CPython implementation and was funded by EWT LLC with local support from CCP Games. Those optimizations added at this sprint are specially marked in the following list.
- When they were introduced in Python 2.4, the built-in
setandfrozensettypes were built on top of Python's dictionary type. In 2.5 the internal data structure has been customized for implementing sets, and as a result sets will use a third less memory and are somewhat faster. (Implemented by Raymond Hettinger.) - The speed of some Unicode operations, such as finding substrings, string splitting, and character map encoding and decoding, has been improved. (Substring search and splitting improvements were added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter Dörwald and Martin von Löwis.)
- The
long(str, base)function is now faster on long digit strings because fewer intermediate results are calculated. The peak is for strings of around 800--1000 digits where the function is 6 times faster. (Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.) - It's now illegal to mix iterating over a file with
for line in fileand calling the file object's!read/!readline/!readlinesmethods. Iteration uses an internal buffer and the!read\*methods don't use that buffer. Instead they would return the data following the buffer, causing the data to appear out of order. Mixing iteration and these methods will now trigger aValueErrorfrom the!read\*method. (Implemented by Thomas Wouters.) - The
structmodule now compiles structure format strings into an internal representation and caches this representation, yielding a 20% speedup. (Contributed by Bob Ippolito at the NeedForSpeed sprint.) - The
remodule got a 1 or 2% speedup by switching to Python's allocator functions instead of the system'smallocandfree. (Contributed by Jack Diederich at the NeedForSpeed sprint.) - The code generator's peephole optimizer now performs simple constant folding in expressions. If you write something like
a = 2+3, the code generator will do the arithmetic and produce code corresponding toa = 5. (Proposed and implemented by Raymond Hettinger.) - Function calls are now faster because code objects now keep the most recently finished frame (a "zombie frame") in an internal field of the code object, reusing it the next time the code object is invoked. (Original patch by Michael Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed sprint.) Frame objects are also slightly smaller, which may improve cache locality and reduce memory usage a bit. (Contributed by Neal Norwitz.)
- Python's built-in exceptions are now new-style classes, a change that speeds up instantiation considerably. Exception handling in Python 2.5 is therefore about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and Sean Reifschneider at the NeedForSpeed sprint.)
- Importing now caches the paths tried, recording whether they exist or not so that the interpreter makes fewer
!openand!statcalls on startup. (Contributed by Martin von Löwis and Georg Brandl.)
New, Improved, and Removed Modules
The standard library received many enhancements and bug fixes in Python 2.5. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the SVN logs for all the details.
-
The
!audioopmodule now supports the a-LAW encoding, and the code for u-LAW encoding has been improved. (Contributed by Lars Immisch.) -
The
codecsmodule gained support for incremental codecs. Thecodecs.lookupfunction now returns a~codecs.CodecInfoinstance instead of a tuple.~codecs.CodecInfoinstances behave like a 4-tuple to preserve backward compatibility but also have the attributes~codecs.CodecInfo.encode,~codecs.CodecInfo.decode,~codecs.CodecInfo.incrementalencoder,~codecs.CodecInfo.incrementaldecoder,~codecs.CodecInfo.streamwriter, and~codecs.CodecInfo.streamreader. Incremental codecs can receive input and produce output in multiple chunks; the output is the same as if the entire input was fed to the non-incremental codec. See thecodecsmodule documentation for details. (Designed and implemented by Walter Dörwald.) -
The
collectionsmodule gained a new type,~collections.defaultdict, that subclasses the standarddicttype. The new type mostly behaves like a dictionary but constructs a default value when a key isn't present, automatically adding it to the dictionary for the requested key value.The first argument to
~collections.defaultdict's constructor is a factory function that gets called whenever a key is requested but not found. This factory function receives no arguments, so you can use built-in type constructors such aslistorint. For example, you can make an index of words based on their initial letter like this:words = """Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura che la diritta via era smarrita""".lower().split() index = defaultdict(list) for w in words: init_letter = w[0] index[init_letter].append(w)Printing
indexresults in the following output:defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'], 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'], 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'], 'p': ['per'], 's': ['selva', 'smarrita'], 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}(Contributed by Guido van Rossum.)
-
The
~collections.dequedouble-ended queue type supplied by thecollectionsmodule now has aremove(value)method that removes the first occurrence of value in the queue, raisingValueErrorif the value isn't found. (Contributed by Raymond Hettinger.) -
New module: The
contextlibmodule contains helper functions for use with the new 'with' statement. See sectioncontextlibmodfor more about this module. -
New module: The
!cProfilemodule is a C implementation of the existing!profilemodule that has much lower overhead. The module's interface is the same as!profile: you runcProfile.run('main()')to profile a function, can save profile data to a file, etc. It's not yet known if the Hotshot profiler, which is also written in C but doesn't match the!profilemodule's interface, will continue to be maintained in future versions of Python. (Contributed by Armin Rigo.)Also, the
pstatsmodule for analyzing the data measured by the profiler now supports directing the output to any file object by supplying a stream argument to the~pstats.Statsconstructor. (Contributed by Skip Montanaro.) -
The
csvmodule, which parses files in comma-separated value format, received several enhancements and a number of bugfixes. You can now set the maximum size in bytes of a field by calling thecsv.field_size_limit(new_limit)function; omitting the new_limit argument will return the currently set limit. The~csv.readerclass now has a~csv.csvreader.line_numattribute that counts the number of physical lines read from the source; records can span multiple physical lines, so~csv.csvreader.line_numis not the same as the number of records read.The CSV parser is now stricter about multi-line quoted fields. Previously, if a line ended within a quoted field without a terminating newline character, a newline would be inserted into the returned field. This behavior caused problems when reading files that contained carriage return characters within fields, so the code was changed to return the field without inserting newlines. As a consequence, if newlines embedded within fields are important, the input should be split into lines in a manner that preserves the newline characters.
(Contributed by Skip Montanaro and Andrew McNamara.)
-
The
~datetime.datetimeclass in thedatetimemodule now has astrptime(string, format)method for parsing date strings, contributed by Josh Spoerri. It uses the same format characters astime.strptimeandtime.strftime:import datetime as dt ts = dt.datetime.strptime('10:13:15 2006-03-07', '%H:%M:%S %Y-%m-%d') -
The
difflib.SequenceMatcher.get_matching_blocksmethod in thedifflibmodule now guarantees to return a minimal list of blocks describing matching subsequences. Previously, the algorithm would occasionally break a block of matching elements into two list entries. (Enhancement by Tim Peters.) -
The
doctestmodule gained aSKIPoption that keeps an example from being executed at all. This is intended for code snippets that are usage examples intended for the reader and aren't actually test cases.An encoding parameter was added to the
~doctest.testfilefunction and the~doctest.DocFileSuiteclass to specify the file's encoding. This makes it easier to use non-ASCII characters in tests contained within a docstring. (Contributed by Bjorn Tillenius.) -
The
emailpackage has been updated to version 4.0. (Contributed by Barry Warsaw.)single: universal newlines; What's new
-
The
fileinputmodule was made more flexible. Unicode filenames are now supported, and a mode parameter that defaults to"r"was added to theinputfunction to allow opening files in binary oruniversal newlinesmode. Another new parameter, openhook, lets you use a function other thanopento open the input files. Once you're iterating over the set of files, the~fileinput.FileInputobject's new~fileinput.filenoreturns the file descriptor for the currently opened file. (Contributed by Georg Brandl.) -
In the
gcmodule, the new~gc.get_countfunction returns a 3-tuple containing the current collection counts for the three GC generations. This is accounting information for the garbage collector; when these counts reach a specified threshold, a garbage collection sweep will be made. The existinggc.collectfunction now takes an optional generation argument of 0, 1, or 2 to specify which generation to collect. (Contributed by Barry Warsaw.) -
The
~heapq.nsmallestand~heapq.nlargestfunctions in theheapqmodule now support akeykeyword parameter similar to the one provided by themin/maxfunctions and the~list.sortmethods. For example:>>> import heapq >>> L = ["short", 'medium', 'longest', 'longer still'] >>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically ['longer still', 'longest'] >>> heapq.nsmallest(2, L, key=len) # Return two shortest elements ['short', 'medium'](Contributed by Raymond Hettinger.)
-
The
itertools.islicefunction now acceptsNonefor the start and step arguments. This makes it more compatible with the attributes of slice objects, so that you can now write the following:s = slice(5) # Create slice object itertools.islice(iterable, s.start, s.stop, s.step)(Contributed by Raymond Hettinger.)
-
The
formatfunction in thelocalemodule has been modified and two new functions were added,~locale.format_stringand~locale.currency.The
formatfunction's val parameter could previously be a string as long as no more than one %char specifier appeared; now the parameter must be exactly one %char specifier with no surrounding text. An optional monetary parameter was also added which, ifTrue, will use the locale's rules for formatting currency in placing a separator between groups of three digits.To format strings with multiple %char specifiers, use the new
~locale.format_stringfunction that works likeformatbut also supports mixing %char specifiers with arbitrary text.A new
~locale.currencyfunction was also added that formats a number according to the current locale's settings.(Contributed by Georg Brandl.)
-
The
mailboxmodule underwent a massive rewrite to add the capability to modify mailboxes in addition to reading them. A new set of classes that include~mailbox.mbox,~mailbox.MH, and~mailbox.Maildirare used to read mailboxes, and have anadd(message)method to add messages,remove(key)to remove messages, and~mailbox.Mailbox.lock/~mailbox.Mailbox.unlockto lock/unlock the mailbox. The following example converts a maildir-format mailbox into an mbox-format one:import mailbox # 'factory=None' uses email.Message.Message as the class representing # individual messages. src = mailbox.Maildir('maildir', factory=None) dest = mailbox.mbox('/tmp/mbox') for msg in src: dest.add(msg)(Contributed by Gregory K. Johnson. Funding was provided by Google's 2005 Summer of Code.)
-
New module: the
!msilibmodule allows creating Microsoft Installer.msifiles and CAB files. Some support for reading the.msidatabase is also included. (Contributed by Martin von Löwis.) -
The
!nismodule now supports accessing domains other than the system default domain by supplying a domain argument to the!nis.matchand!nis.mapsfunctions. (Contributed by Ben Bell.) -
The
operatormodule's~operator.itemgetterand~operator.attrgetterfunctions now support multiple fields. A call such asoperator.attrgetter('a', 'b')will return a function that retrieves theaandbattributes. Combining this new feature with the~list.sortmethod'skeyparameter lets you easily sort lists using multiple fields. (Contributed by Raymond Hettinger.) -
The
optparsemodule was updated to version 1.5.1 of the Optik library. The~optparse.OptionParserclass gained an!epilogattribute, a string that will be printed after the help message, and a!destroymethod to break reference cycles created by the object. (Contributed by Greg Ward.) -
The
osmodule underwent several changes. The!stat_float_timesvariable now defaults to true, meaning thatos.statwill now return time values as floats. (This doesn't necessarily mean thatos.statwill return times that are precise to fractions of a second; not all systems support such precision.)Constants named
os.SEEK_SET,os.SEEK_CUR, andos.SEEK_ENDhave been added; these are the parameters to theos.lseekfunction. Two new constants for locking areos.O_SHLOCKandos.O_EXLOCK.Two new functions,
~os.wait3and~os.wait4, were added. They're similar the~os.waitpidfunction which waits for a child process to exit and returns a tuple of the process ID and its exit status, but~os.wait3and~os.wait4return additional information.~os.wait3doesn't take a process ID as input, so it waits for any child process to exit and returns a 3-tuple of process-id, exit-status, resource-usage as returned from theresource.getrusagefunction.wait4(pid)does take a process ID. (Contributed by Chad J. Schroeder.)On FreeBSD, the
os.statfunction now returns times with nanosecond resolution, and the returned object now has~os.stat_result.st_genand~os.stat_result.st_birthtime. The~os.stat_result.st_flagsattribute is also available, if the platform supports it. (Contributed by Antti Louko and Diego Pettenò.) -
The Python debugger provided by the
pdbmodule can now store lists of commands to execute when a breakpoint is reached and execution stops. Once breakpoint #1 has been created, entercommands 1and enter a series of commands to be executed, finishing the list withend. The command list can include commands that resume execution, such ascontinueornext. (Contributed by Grégoire Dooms.) -
The
pickleand!cPicklemodules no longer accept a return value ofNonefrom the~object.__reduce__method; the method must return a tuple of arguments instead. The ability to returnNonewas deprecated in Python 2.4, so this completes the removal of the feature. -
The
pkgutilmodule, containing various utility functions for finding packages, was enhanced to support302's import hooks and now also works for packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.) -
The pybench benchmark suite by Marc-André Lemburg is now included in the
Tools/pybenchdirectory. The pybench suite is an improvement on the commonly usedpystone.pyprogram because pybench provides a more detailed measurement of the interpreter's speed. It times particular operations such as function calls, tuple slicing, method lookups, and numeric operations, instead of performing many different operations and reducing the result to a single number aspystone.pydoes. -
The
!pyexpatmodule now uses version 2.0 of the Expat parser. (Contributed by Trent Mick.) -
The
~queue.Queueclass provided by thequeuemodule gained two new methods.~queue.Queue.joinblocks until all items in the queue have been retrieved and all processing work on the items have been completed. Worker threads call the other new method,~queue.Queue.task_done, to signal that processing for an item has been completed. (Contributed by Raymond Hettinger.) -
The old
!regexand!regsubmodules, which have been deprecated ever since Python 2.0, have finally been deleted. Other deleted modules:!statcache,!tzparse,!whrandom. -
Also deleted: the
lib-olddirectory, which includes ancient modules such as!dircmpand!ni, was removed.lib-oldwasn't on the defaultsys.path, so unless your programs explicitly added the directory tosys.path, this removal shouldn't affect your code. -
The
rlcompletermodule is no longer dependent on importing thereadlinemodule and therefore now works on non-Unix platforms. (Patch from Robert Kiendl.) -
The
SimpleXMLRPCServer <xmlrpc.server>andDocXMLRPCServer <xmlrpc.server>classes now have a~xmlrpc.server.SimpleXMLRPCRequestHandler.rpc_pathsattribute that constrains XML-RPC operations to a limited set of URL paths; the default is to allow only'/'and'/RPC2'. Setting~xmlrpc.server.SimpleXMLRPCRequestHandler.rpc_pathstoNoneor an empty tuple disables this path checking. -
The
socketmodule now supports!AF_NETLINKsockets on Linux, thanks to a patch from Philippe Biondi. Netlink sockets are a Linux-specific mechanism for communications between a user-space process and kernel code; an introductory article about them is at https://www.linuxjournal.com/article/7356. In Python code, netlink addresses are represented as a tuple of 2 integers,(pid, group_mask).Two new methods on socket objects,
recv_into(buffer)andrecvfrom_into(buffer), store the received data in an object that supports the buffer protocol instead of returning the data as a string. This means you can put the data directly into an array or a memory-mapped file.Socket objects also gained
!getfamily,!gettype, and!getprotoaccessor methods to retrieve the family, type, and protocol values for the socket. -
New module: the
!spwdmodule provides functions for accessing the shadow password database on systems that support shadow passwords. -
The
structis now faster because it compiles format strings into~struct.Structobjects with~struct.Struct.packand~struct.Struct.unpackmethods. This is similar to how theremodule lets you create compiled regular expression objects. You can still use the module-level~struct.packand~struct.unpackfunctions; they'll create~struct.Structobjects and cache them. Or you can use~struct.Structinstances directly:s = struct.Struct('ih3s') data = s.pack(1972, 187, 'abc') year, number, name = s.unpack(data)You can also pack and unpack data to and from buffer objects directly using the
pack_into(buffer, offset, v1, v2, ...)andunpack_from(buffer, offset)methods. This lets you store data directly into an array or a memory-mapped file.(
~struct.Structobjects were implemented by Bob Ippolito at the NeedForSpeed sprint. Support for buffer objects was added by Martin Blais, also at the NeedForSpeed sprint.) -
The Python developers switched from CVS to Subversion during the 2.5 development process. Information about the exact build version is available as the
sys.subversionvariable, a 3-tuple of(interpreter-name, branch-name, revision-range). For example, at the time of writing my copy of 2.5 was reporting('CPython', 'trunk', '45313:45315').This information is also available to C extensions via the
Py_GetBuildInfofunction that returns a string of build information like this:"trunk:45355:45356M, Apr 13 2006, 07:42:19". (Contributed by Barry Warsaw.) -
Another new function,
sys._current_frames, returns the current stack frames for all running threads as a dictionary mapping thread identifiers to the topmost stack frame currently active in that thread at the time the function is called. (Contributed by Tim Peters.) -
The
~tarfile.TarFileclass in thetarfilemodule now has an~tarfile.TarFile.extractallmethod that extracts all members from the archive into the current working directory. It's also possible to set a different directory as the extraction target, and to unpack only a subset of the archive's members.The compression used for a tarfile opened in stream mode can now be autodetected using the mode
'r|*'. (Contributed by Lars Gustäbel.) -
The
threadingmodule now lets you set the stack size used when new threads are created. Thestack_size([*size*])function returns the currently configured stack size, and supplying the optional size parameter sets a new value. Not all platforms support changing the stack size, but Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.) -
The
unicodedatamodule has been updated to use version 4.1.0 of the Unicode character database. Version 3.2.0 is required by some specifications, so it's still available asunicodedata.ucd_3_2_0. -
New module: the
uuidmodule generates universally unique identifiers (UUIDs) according to4122. The RFC defines several different UUID versions that are generated from a starting string, from system properties, or purely randomly. This module contains a~uuid.UUIDclass and functions named~uuid.uuid1,~uuid.uuid3,~uuid.uuid4, and~uuid.uuid5to generate different versions of UUID. (Version 2 UUIDs are not specified in4122and are not supported by this module.) :>>> import uuid >>> # make a UUID based on the host ID and current time >>> uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') >>> # make a UUID using an MD5 hash of a namespace UUID and a name >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') >>> # make a random UUID >>> uuid.uuid4() UUID('16fd2706-8baf-433b-82eb-8c7fada847da') >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')(Contributed by Ka-Ping Yee.)
-
The
weakrefmodule's~weakref.WeakKeyDictionaryand~weakref.WeakValueDictionarytypes gained new methods for iterating over the weak references contained in the dictionary.!iterkeyrefsand~weakref.WeakKeyDictionary.keyrefsmethods were added to~weakref.WeakKeyDictionary, and!itervaluerefsand~weakref.WeakValueDictionary.valuerefswere added to~weakref.WeakValueDictionary. (Contributed by Fred L. Drake, Jr.) -
The
webbrowsermodule received a number of enhancements. It's now usable as a script withpython -m webbrowser, taking a URL as the argument; there are a number of switches to control the behaviour (!-nfor a new browser window,!-tfor a new tab). New module-level functions,~webbrowser.open_newand~webbrowser.open_new_tab, were added to support this. The module'sopenfunction supports an additional feature, an autoraise parameter that signals whether to raise the open window when possible. A number of additional browsers were added to the supported list such as Firefox, Opera, Konqueror, and elinks. (Contributed by Oleg Broytmann and Georg Brandl.) -
The
xmlrpclib <xmlrpc.client>module now supports returning~datetime.datetimeobjects for the XML-RPC date type. Supplyuse_datetime=Trueto the~xmlrpc.client.loadsfunction or the!Unmarshallerclass to enable this feature. (Contributed by Skip Montanaro.) -
The
zipfilemodule now supports the ZIP64 version of the format, meaning that a .zip archive can now be larger than 4 GiB and can contain individual files larger than 4 GiB. (Contributed by Ronald Oussoren.) -
The
zlibmodule's!Compressand!Decompressobjects now support acopymethod that makes a copy of the object's internal state and returns a new!Compressor!Decompressobject. (Contributed by Chris AtLee.)
The ctypes package
The ctypes package, written by Thomas Heller, has been added to the standard library. ctypes lets you call arbitrary functions in shared libraries or DLLs. Long-time users may remember the !dl module, which provides functions for loading shared libraries and calling functions in them. The ctypes package is much fancier.
import ctypes
libc = ctypes.CDLL('libc.so.6')
result = libc.printf("Line of output\n")
Type constructors for the various C types are provided: ~ctypes.c_int, ~ctypes.c_float, ~ctypes.c_double, ~ctypes.c_char_p (equivalent to char \*), and so forth. Unlike Python's types, the C versions are all mutable; you can assign to their ~ctypes._SimpleCData.value attribute to change the wrapped value. Python integers and strings will be automatically converted to the corresponding C types, but for other types you must call the correct type constructor. (And I mean must; getting it wrong will often result in the interpreter crashing with a segmentation fault.)
You shouldn't use ~ctypes.c_char_p with a Python string when the C function will be modifying the memory area, because Python strings are supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area, use ~ctypes.create_string_buffer:
s = "this is a string"
buf = ctypes.create_string_buffer(s)
libc.strfry(buf)
C functions are assumed to return integers, but you can set the ~ctypes._CFuncPtr.restype attribute of the function object to change this:
>>> libc.atof('2.71828')
-1783957616
>>> libc.atof.restype = ctypes.c_double
>>> libc.atof('2.71828')
2.71828
ctypes also provides a wrapper for Python's C API as the ctypes.pythonapi object. This object does not release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code. There's a ~ctypes.py_object type constructor that will create a PyObject * pointer. A simple usage:
import ctypes
d = {}
ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
ctypes.py_object("abc"), ctypes.py_object(1))
# d is now {'abc', 1}.
Don't forget to use ~ctypes.py_object; if it's omitted you end up with a segmentation fault.
ctypes has been around for a while, but people still write and distribution hand-coded extension modules because you can't rely on ctypes being present. Perhaps developers will begin to write Python wrappers atop a library accessed through ctypes instead of extension modules, now that ctypes is included with core Python.
https://web.archive.org/web/20180410025338/http://starship.python.net/crew/theller/ctypes/
The pre-stdlib ctypes web page, with a tutorial, reference, and FAQ.
The documentation for the ctypes module.
The ElementTree package
A subset of Fredrik Lundh's ElementTree library for processing XML has been added to the standard library as !xml.etree. The available modules are !ElementTree, !ElementPath, and !ElementInclude from ElementTree 1.2.6. The !cElementTree accelerator module is also included.
The rest of this section will provide a brief overview of using ElementTree. Full documentation for ElementTree is available at https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm.
ElementTree represents an XML document as a tree of element nodes. The text content of the document is stored as the ~xml.etree.ElementTree.Element.text and ~xml.etree.ElementTree.Element.tail attributes of (This is one of the major differences between ElementTree and the Document Object Model; in the DOM there are many different types of node, including !TextNode.)
The most commonly used parsing function is ~xml.etree.ElementTree.parse, that takes either a string (assumed to contain a filename) or a file-like object and returns an ~xml.etree.ElementTree.ElementTree instance:
from xml.etree import ElementTree as ET
tree = ET.parse('ex-1.xml')
feed = urllib.urlopen(
'http://planet.python.org/rss10.xml')
tree = ET.parse(feed)
Once you have an ~xml.etree.ElementTree.ElementTree instance, you can call its ~xml.etree.ElementTree.ElementTree.getroot method to get the root ~xml.etree.ElementTree.Element node.
There's also an ~xml.etree.ElementTree.XML function that takes a string literal and returns an ~xml.etree.ElementTree.Element node (not an ~xml.etree.ElementTree.ElementTree). This function provides a tidy way to incorporate XML fragments, approaching the convenience of an XML literal:
svg = ET.XML("""<svg width="10px" version="1.0">
</svg>""")
svg.set('height', '320px')
svg.append(elem1)
Each XML element supports some dictionary-like and some list-like access methods. Dictionary-like operations are used to access attribute values, and list-like operations are used to access child nodes.
| Operation | Result |
|---|---|
elem[n] |
Returns n'th child element. |
elem[m:n] |
Returns list of m'th through n'th child elements. |
len(elem) |
Returns number of child elements. |
list(elem) |
Returns list of child elements. |
elem.append(elem2) |
Adds elem2 as a child. |
elem.insert(index, elem2) |
Inserts elem2 at the specified location. |
del elem[n] |
Deletes n'th child element. |
elem.keys() |
Returns list of attribute names. |
elem.get(name) |
Returns value of attribute name. |
elem.set(name, value) |
Sets new value for attribute name. |
elem.attrib |
Retrieves the dictionary containing attributes. |
del elem.attrib[name] |
Deletes attribute name. |
Comments and processing instructions are also represented as ~xml.etree.ElementTree.Element nodes. To check if a node is a comment or processing instructions:
if elem.tag is ET.Comment:
...
elif elem.tag is ET.ProcessingInstruction:
...
To generate XML output, you should call the xml.etree.ElementTree.ElementTree.write method. Like ~xml.etree.ElementTree.parse, it can take either a string or a file-like object:
# Encoding is US-ASCII
tree.write('output.xml')
# Encoding is UTF-8
f = open('output.xml', 'w')
tree.write(f, encoding='utf-8')
(Caution: the default encoding used for output is ASCII. For general XML work, where an element's name may contain arbitrary Unicode characters, ASCII isn't a very useful encoding because it will raise an exception if an element's name contains any characters with values greater than 127. Therefore, it's best to specify a different encoding such as UTF-8 that can handle any Unicode character.)
This section is only a partial description of the ElementTree interfaces. Please read the package's official documentation for more details.
https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm
Official documentation for ElementTree.
The hashlib package
A new hashlib module, written by Gregory P. Smith, has been added to replace the !md5 and !sha modules. hashlib adds support for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When available, the module uses OpenSSL for fast platform optimized implementations of algorithms.
The old !md5 and !sha modules still exist as wrappers around hashlib to preserve backwards compatibility. The new module's interface is very close to that of the old modules, but not identical. The most significant difference is that the constructor functions for creating new hashing objects are named differently. :
# Old versions
h = md5.md5()
h = md5.new()
# New version
h = hashlib.md5()
# Old versions
h = sha.sha()
h = sha.new()
# New version
h = hashlib.sha1()
# Hash that weren't previously available
h = hashlib.sha224()
h = hashlib.sha256()
h = hashlib.sha384()
h = hashlib.sha512()
# Alternative form
h = hashlib.new('md5') # Provide algorithm as a string
Once a hash object has been created, its methods are the same as before: update(string) hashes the specified string into the current digest state, ~hashlib.hash.digest and ~hashlib.hash.hexdigest return the digest value as a binary string or a string of hex digits, and copy returns a new hashing object with the same digest state.
The documentation for the hashlib module.
The sqlite3 package
The pysqlite module (https://www.pysqlite.org), a wrapper for the SQLite embedded database, has been added to the standard library under the package name sqlite3.
SQLite is a C library that provides a lightweight disk-based database that doesn't require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It's also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
pysqlite was written by Gerhard Häring and provides a SQL interface compliant with the DB-API 2.0 specification described by 249.
If you're compiling the Python source yourself, note that the source tree doesn't include the SQLite code, only the wrapper module. You'll need to have the SQLite libraries and headers installed before compiling Python, and the build process will compile the module when the necessary headers are available.
To use the module, you must first create a ~sqlite3.Connection object that represents the database. Here the data will be stored in the /tmp/example file:
conn = sqlite3.connect('/tmp/example')
You can also supply the special name :memory: to create a database in RAM.
Once you have a ~sqlite3.Connection, you can create a ~sqlite3.Cursor object and call its ~sqlite3.Cursor.execute method to perform SQL commands:
c = conn.cursor()
# Create table
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
# Insert a row of data
c.execute("""insert into stocks
values ('2006-01-05','BUY','RHAT',100,35.14)""")
Usually your SQL operations will need to use values from Python variables. You shouldn't assemble your query using Python's string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack.
Instead, use the DB-API's parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor's ~sqlite3.Cursor.execute method. (Other database modules may use a different placeholder, such as %s or :1.) For example:
# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)
# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)
# Larger example
for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
):
c.execute('insert into stocks values (?,?,?,?,?)', t)
To retrieve data after executing a SELECT statement, you can either treat the cursor as an iterator, call the cursor's ~sqlite3.Cursor.fetchone method to retrieve a single matching row, or call ~sqlite3.Cursor.fetchall to get a list of the matching rows.
This example uses the iterator form:
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
>>> for row in c:
... print row
...
(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
>>>
For more information about the SQL dialect supported by SQLite, see https://www.sqlite.org.
https://www.pysqlite.org
The pysqlite web page.
https://www.sqlite.org
The SQLite web page; the documentation describes the syntax and the available data types for the supported SQL dialect.
The documentation for the sqlite3 module.
249 - Database API Specification 2.0
PEP written by Marc-André Lemburg.
The wsgiref package
The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface between web servers and Python web applications and is described in 333. The wsgiref package is a reference implementation of the WSGI specification.
The package includes a basic HTTP server that will run a WSGI application; this server is useful for debugging but isn't intended for production use. Setting up a server takes only a few lines of code:
from wsgiref import simple_server
wsgi_app = ...
host = ''
port = 8000
httpd = simple_server.make_server(host, port, wsgi_app)
httpd.serve_forever()
https://web.archive.org/web/20160331090247/http://wsgi.readthedocs.org/en/latest/
A central web site for WSGI-related resources.
333 - Python Web Server Gateway Interface v1.0
PEP written by Phillip J. Eby.
Build and C API Changes
Changes to Python's build process and to the C API include:
-
The Python source tree was converted from CVS to Subversion, in a complex migration procedure that was supervised and flawlessly carried out by Martin von Löwis. The procedure was developed as
347. -
Coverity, a company that markets a source code analysis tool called Prevent, provided the results of their examination of the Python source code. The analysis found about 60 bugs that were quickly fixed. Many of the bugs were refcounting problems, often occurring in error-handling code. See https://scan.coverity.com for the statistics.
-
The largest change to the C API came from
353, which modifies the interpreter to use aPy_ssize_ttype definition instead ofint. See the earlier sectionpep-353for a discussion of this change. -
The design of the bytecode compiler has changed a great deal, no longer generating bytecode by traversing the parse tree. Instead the parse tree is converted to an abstract syntax tree (or AST), and it is the abstract syntax tree that's traversed to produce the bytecode.
It's possible for Python code to obtain AST objects by using the
compilebuilt-in and specifying_ast.PyCF_ONLY_ASTas the value of the flags parameter:from _ast import PyCF_ONLY_AST ast = compile("""a=0 for i in range(10): a += i """, "<string>", 'exec', PyCF_ONLY_AST) assignment = ast.body[0] for_loop = ast.body[1]No official documentation has been written for the AST code yet, but
339discusses the design. To start learning about the code, read the definition of the various AST nodes inParser/Python.asdl. A Python script reads this file and generates a set of C structure definitions inInclude/Python-ast.h. The!PyParser_ASTFromStringand!PyParser_ASTFromFile, defined inInclude/pythonrun.h, take Python source as input and return the root of an AST representing the contents. This AST can then be turned into a code object by!PyAST_Compile. For more information, read the source code, and then ask questions on python-dev.The AST code was developed under Jeremy Hylton's management, and implemented by (in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil Schemenauer, plus the participants in a number of AST sprints at conferences such as PyCon.
-
Evan Jones's patch to obmalloc, first described in a talk at PyCon DC 2005, was applied. Python 2.4 allocated small objects in 256K-sized arenas, but never freed arenas. With this patch, Python will free arenas when they're empty. The net effect is that on some platforms, when you allocate many objects, Python's memory usage may actually drop when you delete them and the memory may be returned to the operating system. (Implemented by Evan Jones, and reworked by Tim Peters.)
Note that this change means extension modules must be more careful when allocating memory. Python's API has many different functions for allocating memory that are grouped into families. For example,
PyMem_Malloc,PyMem_Realloc, andPyMem_Freeare one family that allocates raw memory, whilePyObject_Malloc,PyObject_Realloc, andPyObject_Freeare another family that's supposed to be used for creating Python objects.Previously these different families all reduced to the platform's
mallocandfreefunctions. This meant it didn't matter if you got things wrong and allocated memory with thePyMemfunction but freed it with thePyObjectfunction. With 2.5's changes to obmalloc, these families now do different things and mismatches will probably result in a segfault. You should carefully test your C extension modules with Python 2.5. -
The built-in set types now have an official C API. Call
PySet_NewandPyFrozenSet_Newto create a new set,PySet_AddandPySet_Discardto add and remove elements, andPySet_ContainsandPySet_Sizeto examine the set's state. (Contributed by Raymond Hettinger.) -
C code can now obtain information about the exact revision of the Python interpreter by calling the
Py_GetBuildInfofunction that returns a string of build information like this:"trunk:45355:45356M, Apr 13 2006, 07:42:19". (Contributed by Barry Warsaw.) -
Two new macros can be used to indicate C functions that are local to the current file so that a faster calling convention can be used.
Py_LOCALdeclares the function as returning a value of the specified type and uses a fast-calling qualifier.Py_LOCAL_INLINEdoes the same thing and also requests the function be inlined. If macro!PY_LOCAL_AGGRESSIVEis defined beforepython.his included, a set of more aggressive optimizations are enabled for the module; you should benchmark the results to find out if these optimizations actually make the code faster. (Contributed by Fredrik Lundh at the NeedForSpeed sprint.) -
PyErr_NewException(name, base, dict)can now accept a tuple of base classes as its base argument. (Contributed by Georg Brandl.) -
The
!PyErr_Warnfunction for issuing warnings is now deprecated in favour ofPyErr_WarnEx(category, message, stacklevel)which lets you specify the number of stack frames separating this function and the caller. A stacklevel of 1 is the function callingPyErr_WarnEx, 2 is the function above that, and so forth. (Added by Neal Norwitz.) -
The CPython interpreter is still written in C, but the code can now be compiled with a C++ compiler without errors. (Implemented by Anthony Baxter, Martin von Löwis, Skip Montanaro.)
-
The
!PyRange_Newfunction was removed. It was never documented, never used in the core code, and had dangerously lax error checking. In the unlikely case that your extensions were using it, you can replace it by something like the following:range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", start, stop, step);
Port-Specific Changes
- MacOS X (10.3 and higher): dynamic loading of modules now uses the
dlopenfunction instead of MacOS-specific functions. - MacOS X: an
!--enable-universalsdkswitch was added to theconfigurescript that compiles the interpreter as a universal binary able to run on both PowerPC and Intel processors. (Contributed by Ronald Oussoren;2573.) - Windows:
.dllis no longer supported as a filename extension for extension modules..pydis now the only filename extension that will be searched for.
Porting to Python 2.5
This section lists previously described changes that may require changes to your code:
- ASCII is now the default encoding for modules. It's now a syntax error if a module contains string literals with 8-bit characters but doesn't have an encoding declaration. In Python 2.4 this triggered a warning, not a syntax error.
- Previously, the
!gi_frameattribute of a generator was always a frame object. Because of the342changes described in sectionpep-342, it's now possible for!gi_frameto beNone. - A new warning,
UnicodeWarning, is triggered when you attempt to compare a Unicode string and an 8-bit string that can't be converted to Unicode using the default ASCII encoding. Previously such comparisons would raise aUnicodeDecodeErrorexception. - Library: the
csvmodule is now stricter about multi-line quoted fields. If your files contain newlines embedded within fields, the input should be split into lines in a manner which preserves the newline characters. - Library: the
localemodule'sformatfunction's would previously accept any string as long as no more than one %char specifier appeared. In Python 2.5, the argument must be exactly one %char specifier with no surrounding text. - Library: The
pickleand!cPicklemodules no longer accept a return value ofNonefrom the~object.__reduce__method; the method must return a tuple of arguments instead. The modules also no longer accept the deprecated bin keyword parameter. - Library: The
SimpleXMLRPCServer <xmlrpc.server>andDocXMLRPCServer <xmlrpc.server>classes now have a~xmlrpc.server.SimpleXMLRPCRequestHandler.rpc_pathsattribute that constrains XML-RPC operations to a limited set of URL paths; the default is to allow only'/'and'/RPC2'. Setting~xmlrpc.server.SimpleXMLRPCRequestHandler.rpc_pathstoNoneor an empty tuple disables this path checking. - C API: Many functions now use
Py_ssize_tinstead ofintto allow processing more data on 64-bit machines. Extension code may need to make the same change to avoid warnings and to support 64-bit machines. See the earlier sectionpep-353for a discussion of this change. - C API: The obmalloc changes mean that you must be careful to not mix usage of the
PyMem_*andPyObject_*families of functions. Memory allocated with one family's*_Mallocmust be freed with the corresponding family's*_Freefunction.
Acknowledgements
What's New in Python 2.6
This article explains the new features in Python 2.6, released on October 1, 2008. The release schedule is described in 361.
The major theme of Python 2.6 is preparing the migration path to Python 3.0, a major redesign of the language. Whenever possible, Python 2.6 incorporates new features and syntax from 3.0 while remaining compatible with existing code by not removing older features or syntax. When it's not possible to do that, Python 2.6 tries to do what it can, adding compatibility functions in a !future_builtins module and a !-3 switch to warn about usages that will become unsupported in 3.0.
Some significant new packages have been added to the standard library, such as the multiprocessing and json modules, but there aren't many new features that aren't related to Python 3.0 in some way.
Python 2.6 also sees a number of improvements and bugfixes throughout the source. A search through the change logs finds there were 259 patches applied and 612 bugs fixed between Python 2.5 and 2.6. Both figures are likely to be underestimates.
This article doesn't attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.6. If you want to understand the rationale for the design and implementation, refer to the PEP for a particular new feature. Whenever possible, "What's New in Python" links to the bug/patch item for each change.
Python 3.0
The development cycle for Python versions 2.6 and 3.0 was synchronized, with the alpha and beta releases for both versions being made on the same days. The development of 3.0 has influenced many features in 2.6.
Python 3.0 is a far-ranging redesign of Python that breaks compatibility with the 2.x series. This means that existing Python code will need some conversion in order to run on Python 3.0. However, not all the changes in 3.0 necessarily break compatibility. In cases where new features won't cause existing code to break, they've been backported to 2.6 and are described in this document in the appropriate place. Some of the 3.0-derived features are:
- A
~object.__complex__method for converting objects to a complex number. - Alternate syntax for catching exceptions:
except TypeError as exc. - The addition of
functools.reduceas a synonym for the built-in!reducefunction.
Python 3.0 adds several new built-in functions and changes the semantics of some existing builtins. Functions that are new in 3.0 such as bin have simply been added to Python 2.6, but existing builtins haven't been changed; instead, the !future_builtins module has versions with the new 3.0 semantics. Code written to be compatible with 3.0 can do from future_builtins import hex, map as necessary.
A new command-line switch, !-3, enables warnings about features that will be removed in Python 3.0. You can run code with this switch to see how much work will be necessary to port code to 3.0. The value of this switch is available to Python code as the boolean variable !sys.py3kwarning, and to C extension code as !Py_Py3kWarningFlag.
The 3xxx series of PEPs, which contains proposals for Python 3.0. 3000 describes the development process for Python 3.0. Start with 3100 that describes the general goals for Python 3.0, and then explore the higher-numbered PEPs that propose specific features.
Changes to the Development Process
While 2.6 was being developed, the Python development process underwent two significant changes: we switched from SourceForge's issue tracker to a customized Roundup installation, and the documentation was converted from LaTeX to reStructuredText.
New Issue Tracker: Roundup
For a long time, the Python developers had been growing increasingly annoyed by SourceForge's bug tracker. SourceForge's hosted solution doesn't permit much customization; for example, it wasn't possible to customize the life cycle of issues.
The infrastructure committee of the Python Software Foundation therefore posted a call for issue trackers, asking volunteers to set up different products and import some of the bugs and patches from SourceForge. Four different trackers were examined: Jira, Launchpad, Roundup, and Trac. The committee eventually settled on Jira and Roundup as the two candidates. Jira is a commercial product that offers no-cost hosted instances to free-software projects; Roundup is an open-source project that requires volunteers to administer it and a server to host it.
After posting a call for volunteers, a new Roundup installation was set up at https://bugs.python.org. One installation of Roundup can host multiple trackers, and this server now also hosts issue trackers for Jython and for the Python web site. It will surely find other uses in the future. Where possible, this edition of "What's New in Python" links to the bug/patch item for each change.
Hosting of the Python bug tracker is kindly provided by Upfront Systems of Stellenbosch, South Africa. Martin von Löwis put a lot of effort into importing existing bugs and patches from SourceForge; his scripts for this import operation are at https://svn.python.org/view/tracker/importer/ and may be useful to other projects wishing to move from SourceForge to Roundup.
https://bugs.python.org
The Python bug tracker.
https://bugs.jython.org:
The Jython bug tracker.
https://roundup.sourceforge.io/
Roundup downloads and documentation.
https://svn.python.org/view/tracker/importer/
Martin von Löwis's conversion scripts.
New Documentation Format: reStructuredText Using Sphinx
The Python documentation was written using LaTeX since the project started around 1989. In the 1980s and early 1990s, most documentation was printed out for later study, not viewed online. LaTeX was widely used because it provided attractive printed output while remaining straightforward to write once the basic rules of the markup were learned.
Today LaTeX is still used for writing publications destined for printing, but the landscape for programming tools has shifted. We no longer print out reams of documentation; instead, we browse through it online and HTML has become the most important format to support. Unfortunately, converting LaTeX to HTML is fairly complicated and Fred L. Drake Jr., the long-time Python documentation editor, spent a lot of time maintaining the conversion process. Occasionally people would suggest converting the documentation into SGML and later XML, but performing a good conversion is a major task and no one ever committed the time required to finish the job.
During the 2.6 development cycle, Georg Brandl put a lot of effort into building a new toolchain for processing the documentation. The resulting package is called Sphinx, and is available from https://www.sphinx-doc.org/.
Sphinx concentrates on HTML output, producing attractively styled and modern HTML; printed output is still supported through conversion to LaTeX. The input format is reStructuredText, a markup syntax supporting custom extensions and directives that is commonly used in the Python community.
Sphinx is a standalone package that can be used for writing, and almost two dozen other projects (listed on the Sphinx web site) have adopted Sphinx as their documentation tool.
Documenting Python
Describes how to write for Python's documentation.
Sphinx
Documentation and code for the Sphinx toolchain.
Docutils
The underlying reStructuredText parser and toolset.
PEP 343: The 'with' statement
The previous version, Python 2.5, added the 'with' statement as an optional feature, to be enabled by a from __future__ import with_statement directive. In 2.6 the statement no longer needs to be specially enabled; this means that !with is now always a keyword. The rest of this section is a copy of the corresponding section from the "What's New in Python 2.5" document; if you're familiar with the '!with' statement from Python 2.5, you can skip this section.
The 'with' statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I'll discuss the statement as it will commonly be used. In the next section, I'll examine the implementation details and show how to write objects for use with this statement.
The 'with' statement is a control-flow structure whose basic structure is:
with expression [as variable]:
with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has ~object.__enter__ and ~object.__exit__ methods).
The object's ~object.__enter__ is called before with-block is executed and therefore can run set-up code. It also may return a value that is bound to the name variable, if given. (Note carefully that variable is not assigned the result of expression.)
After execution of the with-block is finished, the object's ~object.__exit__ method is called, even if the block raised an exception, and can therefore run clean-up code.
Some standard Python objects now support the context management protocol and can be used with the 'with' statement. File objects are one example:
with open('/etc/passwd', 'r') as f:
for line in f:
print line
... more processing code ...
After this statement has executed, the file object in f will have been automatically closed, even if the for loop raised an exception part-way through the block.
[!NOTE] In this case, f is the same object created by
open, because~object.__enter__returns self.
The threading module's locks and condition variables also support the 'with' statement:
lock = threading.Lock()
with lock:
# Critical section of code
...
The lock is acquired before the block is executed and always released once the block is complete.
The ~decimal.localcontext function in the decimal module makes it easy to save and restore the current decimal context, which encapsulates the desired precision and rounding characteristics for computations:
from decimal import Decimal, Context, localcontext
# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()
with localcontext(Context(prec=16)):
# All code in this block uses a precision of 16 digits.
# The original context is restored on exiting the block.
print v.sqrt()
Writing Context Managers
Under the hood, the 'with' statement is fairly complicated. Most people will only use '!with' in company with existing objects and don't need to know these details, so you can skip the rest of this section if you like. Authors of new objects will need to understand the details of the underlying implementation and should keep reading.
A high-level explanation of the context management protocol is:
- The expression is evaluated and should result in an object called a "context manager". The context manager must have
~object.__enter__and~object.__exit__methods. - The context manager's
~object.__enter__method is called. The value returned is assigned to VAR. If noas VARclause is present, the value is simply discarded. - The code in BLOCK is executed.
- If BLOCK raises an exception, the context manager's
~object.__exit__method is called with three arguments, the exception details (type, value, traceback, the same values returned bysys.exc_info, which can also beNoneif no exception occurred). The method's return value controls whether an exception is re-raised: any false value re-raises the exception, andTruewill result in suppressing it. You'll only rarely want to suppress the exception, because if you do the author of the code containing the 'with' statement will never realize anything went wrong. - If BLOCK didn't raise an exception, the
~object.__exit__method is still called, but type, value, and traceback are allNone.
Let's think through an example. I won't present detailed code but will only sketch the methods necessary for a database that supports transactions.
(For people unfamiliar with database terminology: a set of changes to the database are grouped into a transaction. Transactions can be either committed, meaning that all the changes are written into the database, or rolled back, meaning that the changes are all discarded and the database is unchanged. See any database textbook for more information.)
Let's assume there's an object representing a database connection. Our goal will be to let the user write code like this:
db_connection = DatabaseConnection()
with db_connection as cursor:
cursor.execute('insert into ...')
cursor.execute('delete from ...')
# ... more operations ...
The transaction should be committed if the code in the block runs flawlessly or rolled back if there's an exception. Here's the basic interface for !DatabaseConnection that I'll assume:
class DatabaseConnection:
# Database interface
def cursor(self):
"Returns a cursor object and starts a new transaction"
def commit(self):
"Commits current transaction"
def rollback(self):
"Rolls back current transaction"
The ~object.__enter__ method is pretty easy, having only to start a new transaction. For this application the resulting cursor object would be a useful result, so the method will return it. The user can then add as cursor to their 'with' statement to bind the cursor to a variable name. :
class DatabaseConnection:
...
def __enter__(self):
# Code to start a new transaction
cursor = self.cursor()
return cursor
The ~object.__exit__ method is the most complicated because it's where most of the work has to be done. The method has to check if an exception occurred. If there was no exception, the transaction is committed. The transaction is rolled back if there was an exception.
In the code below, execution will just fall off the end of the function, returning the default value of None. None is false, so the exception will be re-raised automatically. If you wished, you could be more explicit and add a return statement at the marked location. :
class DatabaseConnection:
...
def __exit__(self, type, value, tb):
if tb is None:
# No exception, so commit
self.commit()
else:
# Exception occurred, so rollback.
self.rollback()
# return False
The contextlib module
The contextlib module provides some functions and a decorator that are useful when writing objects for use with the 'with' statement.
The decorator is called ~contextlib.contextmanager, and lets you write a single generator function instead of defining a new class. The generator should yield exactly one value. The code up to the yield will be executed as the ~object.__enter__ method, and the value yielded will be the method's return value that will get bound to the variable in the 'with' statement's !as clause, if any. The code after the !yield will be executed in the ~object.__exit__ method. Any exception raised in the block will be raised by the !yield statement.
Using this decorator, our database example from the previous section could be written as:
from contextlib import contextmanager
@contextmanager
def db_transaction(connection):
cursor = connection.cursor()
try:
yield cursor
except:
connection.rollback()
raise
else:
connection.commit()
db = DatabaseConnection()
with db_transaction(db) as cursor:
...
The contextlib module also has a nested(mgr1, mgr2, ...) function that combines a number of context managers so you don't need to write nested 'with' statements. In this example, the single '!with' statement both starts a database transaction and acquires a thread lock:
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
...
Finally, the ~contextlib.closing function returns its argument so that it can be bound to a variable, and calls the argument's .close() method at the end of the block. :
import urllib, sys
from contextlib import closing
with closing(urllib.urlopen('http://www.yahoo.com')) as f:
for line in f:
sys.stdout.write(line)
343 - The "with" statement
PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland, Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a 'with' statement, which can be helpful in learning how the statement works.
The documentation for the contextlib module.
PEP 366: Explicit Relative Imports From a Main Module
Python's -m switch allows running a module as a script. When you ran a module that was located inside a package, relative imports didn't work correctly.
The fix for Python 2.6 adds a module.__package__ attribute. When this attribute is present, relative imports will be relative to the value of this attribute instead of the ~module.__name__ attribute.
PEP 302-style importers can then set ~module.__package__ as necessary. The runpy module that implements the -m switch now does this, so relative imports will now work correctly in scripts running from inside a package.
PEP 370: Per-user site-packages Directory
When you run Python, the module search path sys.path usually includes a directory whose path ends in "site-packages". This directory is intended to hold locally installed packages available to all users using a machine or a particular site installation.
Python 2.6 introduces a convention for user-specific site directories. The directory varies depending on the platform:
- Unix and Mac OS X:
~/.local/ - Windows:
%APPDATA%/Python
Within this directory, there will be version-specific subdirectories, such as lib/python2.6/site-packages on Unix/Mac OS and Python26/site-packages on Windows.
If you don't like the default directory, it can be overridden by an environment variable. PYTHONUSERBASE sets the root directory used for all Python versions supporting this feature. On Windows, the directory for application-specific data can be changed by setting the !APPDATA environment variable. You can also modify the site.py file for your Python installation.
The feature can be disabled entirely by running Python with the -s option or setting the PYTHONNOUSERSITE environment variable.
370 - Per-user site-packages Directory
PEP written and implemented by Christian Heimes.
PEP 371: The multiprocessing Package
The new multiprocessing package lets Python programs create new processes that will perform a computation and return a result to the parent. The parent and child processes can communicate using queues and pipes, synchronize their operations using locks and semaphores, and can share simple arrays of data.
The multiprocessing module started out as an exact emulation of the threading module using processes instead of threads. That goal was discarded along the path to Python 2.6, but the general approach of the module is still similar. The fundamental class is the ~multiprocessing.Process, which is passed a callable object and a collection of arguments. The ~multiprocessing.Process.start method sets the callable running in a subprocess, after which you can call the ~multiprocessing.Process.is_alive method to check whether the subprocess is still running and the ~multiprocessing.Process.join method to wait for the process to exit.
Here's a simple example where the subprocess will calculate a factorial. The function doing the calculation is written strangely so that it takes significantly longer when the input argument is a multiple of 4.
import time
from multiprocessing import Process, Queue
def factorial(queue, N):
"Compute a factorial."
# If N is a multiple of 4, this function will take much longer.
if (N % 4) == 0:
time.sleep(.05 * N/4)
# Calculate the result
fact = 1L
for i in range(1, N+1):
fact = fact * i
# Put the result on the queue
queue.put(fact)
if __name__ == '__main__':
queue = Queue()
N = 5
p = Process(target=factorial, args=(queue, N))
p.start()
p.join()
result = queue.get()
print 'Factorial', N, '=', result
A ~queue.Queue is used to communicate the result of the factorial. The ~queue.Queue object is stored in a global variable. The child process will use the value of the variable when the child was created; because it's a ~queue.Queue, parent and child can use the object to communicate. (If the parent were to change the value of the global variable, the child's value would be unaffected, and vice versa.)
Two other classes, ~multiprocessing.pool.Pool and ~multiprocessing.Manager, provide higher-level interfaces. ~multiprocessing.pool.Pool will create a fixed number of worker processes, and requests can then be distributed to the workers by calling ~multiprocessing.pool.Pool.apply or ~multiprocessing.pool.Pool.apply_async to add a single request, and ~multiprocessing.pool.Pool.map or ~multiprocessing.pool.Pool.map_async to add a number of requests. The following code uses a ~multiprocessing.pool.Pool to spread requests across 5 worker processes and retrieve a list of results:
from multiprocessing import Pool
def factorial(N, dictionary):
"Compute a factorial."
...
p = Pool(5)
result = p.map(factorial, range(1, 1000, 10))
for v in result:
print v
This produces the following output:
1
39916800
51090942171709440000
8222838654177922817725562880000000
33452526613163807108170062053440751665152000000000
...
The other high-level interface, the ~multiprocessing.Manager class, creates a separate server process that can hold master copies of Python data structures. Other processes can then access and modify these data structures using proxy objects. The following example creates a shared dictionary by calling the dict method; the worker processes then insert values into the dictionary. (Locking is not done for you automatically, which doesn't matter in this example. ~multiprocessing.Manager's methods also include ~multiprocessing.managers.SyncManager.Lock, ~multiprocessing.managers.SyncManager.RLock, and ~multiprocessing.managers.SyncManager.Semaphore to create shared locks.)
import time
from multiprocessing import Pool, Manager
def factorial(N, dictionary):
"Compute a factorial."
# Calculate the result
fact = 1L
for i in range(1, N+1):
fact = fact * i
# Store result in dictionary
dictionary[N] = fact
if __name__ == '__main__':
p = Pool(5)
mgr = Manager()
d = mgr.dict() # Create shared dictionary
# Run tasks using the pool
for N in range(1, 1000, 10):
p.apply_async(factorial, (N, d))
# Mark pool as closed -- no more tasks can be added.
p.close()
# Wait for tasks to exit
p.join()
# Output results
for k, v in sorted(d.items()):
print k, v
This will produce the output:
1 1
11 39916800
21 51090942171709440000
31 8222838654177922817725562880000000
41 33452526613163807108170062053440751665152000000000
51 15511187532873822802242430164693032110632597200169861120000...
The documentation for the multiprocessing module.
371 - Addition of the multiprocessing package
PEP written by Jesse Noller and Richard Oudkerk; implemented by Richard Oudkerk and Jesse Noller.
PEP 3101: Advanced String Formatting
In Python 3.0, the % operator is supplemented by a more powerful string formatting method, format. Support for the str.format method has been backported to Python 2.6.
In 2.6, both 8-bit and Unicode strings have a .format() method that treats the string as a template and takes the arguments to be formatted. The formatting template uses curly brackets ({, }) as special characters:
>>> # Substitute positional argument 0 into the string.
>>> "User ID: {0}".format("root")
'User ID: root'
>>> # Use the named keyword arguments
>>> "User ID: {uid} Last seen: {last_login}".format(
... uid="root",
... last_login = "5 Mar 2008 07:20")
'User ID: root Last seen: 5 Mar 2008 07:20'
Curly brackets can be escaped by doubling them:
>>> "Empty dict: {{}}".format()
"Empty dict: {}"
Field names can be integers indicating positional arguments, such as {0}, {1}, etc. or names of keyword arguments. You can also supply compound field names that read attributes or access dictionary keys:
>>> import sys
>>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
Platform: darwin
Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
>>> import mimetypes
>>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
'Content-type: video/mp4'
Note that when using dictionary-style notation such as [.mp4], you don't need to put any quotation marks around the string; it will look up the value using .mp4 as the key. Strings beginning with a number will be converted to an integer. You can't write more complicated expressions inside a format string.
So far we've shown how to specify which field to substitute into the resulting string. The precise formatting used is also controllable by adding a colon followed by a format specifier. For example:
>>> # Field 0: left justify, pad to 15 characters
>>> # Field 1: right justify, pad to 6 characters
>>> fmt = '{0:15} ${1:>6}'
>>> fmt.format('Registration', 35)
'Registration $ 35'
>>> fmt.format('Tutorial', 50)
'Tutorial $ 50'
>>> fmt.format('Banquet', 125)
'Banquet $ 125'
Format specifiers can reference other fields through nesting:
>>> fmt = '{0:{1}}'
>>> width = 15
>>> fmt.format('Invoice #1234', width)
'Invoice #1234 '
>>> width = 35
>>> fmt.format('Invoice #1234', width)
'Invoice #1234 '
The alignment of a field within the desired width can be specified:
| Character | Effect |
|---|---|
| < (default) | Left-align |
| > | Right-align |
| ^ | Center |
| = | (For numeric types only) Pad after the sign. |
Format specifiers can also include a presentation type, which controls how the value is formatted. For example, floating-point numbers can be formatted as a general number or in exponential notation:
>>> '{0:g}'.format(3.75)
'3.75'
>>> '{0:e}'.format(3.75)
'3.750000e+00'
A variety of presentation types are available. Consult the 2.6 documentation for a complete list <formatstrings>; here's a sample:
b |
Binary. Outputs the number in base 2. |
c |
Character. Converts the integer to the corresponding Unicode character before printing. |
d |
Decimal Integer. Outputs the number in base 10. |
o |
Octal format. Outputs the number in base 8. |
x |
Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. |
e |
Exponent notation. Prints the number in scientific notation using the letter 'e' to indicate the exponent. |
g |
General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. |
n |
Number. This is the same as 'g' (for floats) or 'd' (for integers), except that it uses the current locale setting to insert the appropriate number separator characters. |
% |
Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign. |
Classes and types can define a ~object.__format__ method to control how they're formatted. It receives a single argument, the format specifier:
def __format__(self, format_spec):
if isinstance(format_spec, unicode):
return unicode(str(self))
else:
return str(self)
There's also a format builtin that will format a single value. It calls the type's ~object.__format__ method with the provided specifier:
>>> format(75.6564, '.2f')
'75.66'
formatstrings
The reference documentation for format fields.
3101 - Advanced String Formatting
PEP written by Talin. Implemented by Eric Smith.
PEP 3105: print As a Function
The print statement becomes the print function in Python 3.0. Making print a function makes it possible to replace the function by doing def print(...) or importing a new function from somewhere else.
Python 2.6 has a __future__ import that removes print as language syntax, letting you use the functional form instead. For example:
>>> from __future__ import print_function
>>> print('# of entries', len(dictionary), file=sys.stderr)
The signature of the new function is:
def print(*args, sep=' ', end='\n', file=None)
The parameters are:
- args: positional arguments whose values will be printed out.
- sep: the separator, which will be printed between arguments.
- end: the ending text, which will be printed after all of the arguments have been output.
- file: the file object to which the output will be sent.
3105 - Make print a function
PEP written by Georg Brandl.
PEP 3110: Exception-Handling Changes
One error that Python programmers occasionally make is writing the following code:
try:
...
except TypeError, ValueError: # Wrong!
...
try:
...
except (TypeError, ValueError):
...
This error happens because the use of the comma here is ambiguous: does it indicate two different nodes in the parse tree, or a single node that's a tuple?
Python 3.0 makes this unambiguous by replacing the comma with the word "as". To catch an exception and store the exception object in the variable exc, you must write:
try:
...
except TypeError as exc:
...
Python 3.0 will only support the use of "as", and therefore interprets the first example as catching two different exceptions. Python 2.6 supports both the comma and "as", so existing code will continue to work. We therefore suggest using "as" when writing new Python code that will only be executed with 2.6.
3110 - Catching Exceptions in Python 3000
PEP written and implemented by Collin Winter.
PEP 3112: Byte Literals
Python 3.0 adopts Unicode as the language's fundamental string type and denotes 8-bit literals differently, either as b'string' or using a bytes constructor. For future compatibility, Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.
The 2.6 str differs from 3.0's bytes type in various ways; most notably, the constructor is completely different. In 3.0, bytes([65, 66, 67]) is 3 elements long, containing the bytes representing ABC; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str of the list.
The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes). This will help the 2to3 converter, which can't tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.
There's also a __future__ import that causes all string literals to become Unicode strings. This means that \u escape sequences can be used to include Unicode characters:
from __future__ import unicode_literals
s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
'\u3081\u3000\u751f\u305f\u307e\u3054')
print len(s) # 12 Unicode characters
At the C level, Python 3.0 will rename the existing 8-bit string type, called !PyStringObject in Python 2.x, to PyBytesObject. Python 2.6 uses #define to support using the names PyBytesObject, PyBytes_Check, PyBytes_FromStringAndSize, and all the other functions and macros used with strings.
Instances of the bytes type are immutable just as strings are. A new bytearray type stores a mutable sequence of bytes:
>>> bytearray([65, 66, 67])
bytearray(b'ABC')
>>> b = bytearray(u'\u21ef\u3244', 'utf-8')
>>> b
bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
>>> b[0] = '\xe3'
>>> b
bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
>>> unicode(str(b), 'utf-8')
u'\u31ef \u3244'
Byte arrays support most of the methods of string types, such as ~bytearray.startswith/~bytearray.endswith, ~bytearray.find/~bytearray.rfind, and some of the methods of lists, such as ~bytearray.append, ~bytearray.pop, and ~bytearray.reverse.
>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
>>> b
bytearray(b'ABCde')
There's also a corresponding C API, with PyByteArray_FromObject, PyByteArray_FromStringAndSize, and various other functions.
3112 - Bytes literals in Python 3000
PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
PEP 3116: New I/O Library
Python's built-in file objects support a number of methods, but file-like objects don't necessarily support all of them. Objects that imitate files usually support !read and !write, but they may not support !readline, for example. Python 3.0 introduces a layered I/O library in the io module that separates buffering and text-handling features from the fundamental read and write operations.
There are three levels of abstract base classes provided by the io module:
-
~io.RawIOBasedefines raw I/O operations:~io.RawIOBase.read,~io.RawIOBase.readinto,~io.RawIOBase.write,~io.IOBase.seek,~io.IOBase.tell,~io.IOBase.truncate, and~io.IOBase.close. Most of the methods of this class will often map to a single system call. There are also~io.IOBase.readable,~io.IOBase.writable, and~io.IOBase.seekablemethods for determining what operations a given object will allow.Python 3.0 has concrete implementations of this class for files and sockets, but Python 2.6 hasn't restructured its file and socket objects in this way.
-
~io.BufferedIOBaseis an abstract base class that buffers data in memory to reduce the number of system calls used, making I/O processing more efficient. It supports all of the methods of~io.RawIOBase, and adds a~io.BufferedIOBase.rawattribute holding the underlying raw object.There are five concrete classes implementing this ABC.
~io.BufferedWriterand~io.BufferedReaderare for objects that support write-only or read-only usage that have a~io.IOBase.seekmethod for random access.~io.BufferedRandomobjects support read and write access upon the same underlying stream, and~io.BufferedRWPairis for objects such as TTYs that have both read and write operations acting upon unconnected streams of data. The~io.BytesIOclass supports reading, writing, and seeking over an in-memory buffer.single: universal newlines; What's new
-
~io.TextIOBase: Provides functions for reading and writing strings (remember, strings will be Unicode in Python 3.0), and supportinguniversal newlines.~io.TextIOBasedefines thereadlinemethod and supports iteration upon objects.There are two concrete implementations.
~io.TextIOWrapperwraps a buffered I/O object, supporting all of the methods for text I/O and adding a~io.TextIOBase.bufferattribute for access to the underlying object.~io.StringIOsimply buffers everything in memory without ever writing anything to disk.(In Python 2.6,
io.StringIOis implemented in pure Python, so it's pretty slow. You should therefore stick with the existing!StringIOmodule or!cStringIOfor now. At some point Python 3.0'siomodule will be rewritten into C for speed, and perhaps the C implementation will be backported to the 2.x releases.)
In Python 2.6, the underlying implementations haven't been restructured to build on top of the io module's classes. The module is being provided to make it easier to write code that's forward-compatible with 3.0, and to save developers the effort of writing their own implementations of buffering and text I/O.
3116 - New I/O
PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum. Code by Guido van Rossum, Georg Brandl, Walter Doerwald, Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.
PEP 3118: Revised Buffer Protocol
The buffer protocol is a C-level API that lets Python types exchange pointers into their internal representations. A memory-mapped file can be viewed as a buffer of characters, for example, and this lets another module such as re treat memory-mapped files as a string of characters to be searched.
The primary users of the buffer protocol are numeric-processing packages such as NumPy, which expose the internal representation of arrays so that callers can write data directly into an array instead of going through a slower API. This PEP updates the buffer protocol in light of experience from NumPy development, adding a number of new features such as indicating the shape of an array or locking a memory region.
The most important new C API function is PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags), which takes an object and a set of flags, and fills in the Py_buffer structure with information about the object's memory representation. Objects can use this operation to lock memory in place while an external caller could be modifying the contents, so there's a corresponding PyBuffer_Release(Py_buffer *view) to indicate that the external caller is done.
The flags argument to PyObject_GetBuffer specifies constraints upon the memory returned. Some examples are:
PyBUF_WRITABLEindicates that the memory must be writable.!PyBUF_LOCKrequests a read-only or exclusive lock on the memory.PyBUF_C_CONTIGUOUSandPyBUF_F_CONTIGUOUSrequests a C-contiguous (last dimension varies the fastest) or Fortran-contiguous (first dimension varies the fastest) array layout.
Two new argument codes for PyArg_ParseTuple, s* and z*, return locked buffer objects for a parameter.
3118 - Revising the buffer protocol
PEP written by Travis Oliphant and Carl Banks; implemented by Travis Oliphant.
PEP 3119: Abstract Base Classes
Some object-oriented languages such as Java support interfaces, declaring that a class has a given set of methods or supports a given access protocol. Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC support consists of an abc module containing a metaclass called ~abc.ABCMeta, special handling of this metaclass by the isinstance and issubclass builtins, and a collection of basic ABCs that the Python developers think will be widely useful. Future versions of Python will probably add more ABCs.
Let's say you have a particular class and wish to know whether it supports dictionary-style access. The phrase "dictionary-style" is vague, however. It probably means that accessing items with obj[1] works. Does it imply that setting items with obj[2] = value works? Or that the object will have !keys, !values, and !items methods? What about the iterative variants such as !iterkeys? !copy`and :meth:!update`? Iterating over the object with !iter?
The Python 2.6 collections module includes a number of different ABCs that represent these distinctions. Iterable indicates that a class defines ~object.__iter__, and Container means the class defines a ~object.__contains__ method and therefore supports x in y expressions. The basic dictionary interface of getting items, setting items, and !keys, !values, and !items, is defined by the MutableMapping ABC.
You can derive your own classes from a particular ABC to indicate they support that ABC's interface:
import collections
class Storage(collections.MutableMapping):
...
Alternatively, you could write the class without deriving from the desired ABC and instead register the class by calling the ABC's ~abc.ABCMeta.register method:
import collections
class Storage:
...
collections.MutableMapping.register(Storage)
For classes that you write, deriving from the ABC is probably clearer. The ~abc.ABCMeta.register method is useful when you've written a new ABC that can describe an existing type or class, or if you want to declare that some third-party class implements an ABC. For example, if you defined a !PrintableType ABC, it's legal to do:
# Register Python's types
PrintableType.register(int)
PrintableType.register(float)
PrintableType.register(str)
Classes should obey the semantics specified by an ABC, but Python can't check this; it's up to the class author to understand the ABC's requirements and to implement the code accordingly.
To check whether an object supports a particular interface, you can now write:
def func(d):
if not isinstance(d, collections.MutableMapping):
raise ValueError("Mapping object expected, not %r" % d)
Don't feel that you must now begin writing lots of checks as in the above example. Python has a strong tradition of duck-typing, where explicit type-checking is never done and code simply calls methods on an object, trusting that those methods will be there and raising an exception if they aren't. Be judicious in checking for ABCs and only do it where it's absolutely necessary.
You can write your own ABCs by using abc.ABCMeta as the metaclass in a class definition:
from abc import ABCMeta, abstractmethod
class Drawable():
__metaclass__ = ABCMeta
@abstractmethod
def draw(self, x, y, scale=1.0):
pass
def draw_doubled(self, x, y):
self.draw(x, y, scale=2.0)
class Square(Drawable):
def draw(self, x, y, scale):
...
In the !Drawable ABC above, the !draw_doubled method renders the object at twice its size and can be implemented in terms of other methods described in !Drawable. Classes implementing this ABC therefore don't need to provide their own implementation of !draw_doubled, though they can do so. An implementation of !draw is necessary, though; the ABC can't provide a useful generic implementation.
You can apply the ~abc.abstractmethod decorator to methods such as !draw that must be implemented; Python will then raise an exception for classes that don't define the method. Note that the exception is only raised when you actually try to create an instance of a subclass lacking the method:
>>> class Circle(Drawable):
... pass
...
>>> c = Circle()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Circle with abstract methods draw
>>>
Abstract data attributes can be declared using the @abstractproperty decorator:
from abc import abstractproperty
...
@abstractproperty
def readonly(self):
return self._x
Subclasses must then define a readonly property.
3119 - Introducing Abstract Base Classes
PEP written by Guido van Rossum and Talin. Implemented by Guido van Rossum. Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
PEP 3127: Integer Literal Support and Syntax
Python 3.0 changes the syntax for octal (base-8) integer literals, prefixing them with "0o" or "0O" instead of a leading zero, and adds support for binary (base-2) integer literals, signalled by a "0b" or "0B" prefix.
Python 2.6 doesn't drop support for a leading 0 signalling an octal number, but it does add support for "0o" and "0b":
>>> 0o21, 2*8 + 1
(17, 17)
>>> 0b101111
47
The oct builtin still returns numbers prefixed with a leading zero, and a new bin builtin returns the binary representation for a number:
>>> oct(42)
'052'
>>> future_builtins.oct(42)
'0o52'
>>> bin(173)
'0b10101101'
The int and !long builtins will now accept the "0o" and "0b" prefixes when base-8 or base-2 are requested, or when the base argument is zero (signalling that the base used should be determined from the string):
>>> int ('0o52', 0)
42
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0b1101', 0)
13
3127 - Integer Literal Support and Syntax
PEP written by Patrick Maupin; backported to 2.6 by Eric Smith.
PEP 3129: Class Decorators
Decorators have been extended from functions to classes. It's now legal to write:
@foo
@bar
class A:
pass
This is equivalent to:
class A:
pass
A = foo(bar(A))
3129 - Class Decorators
PEP written by Collin Winter.
PEP 3141: A Type Hierarchy for Numbers
Python 3.0 adds several abstract base classes for numeric types inspired by Scheme's numeric tower. These classes were backported to 2.6 as the numbers module.
The most general ABC is ~numbers.Number. It defines no operations at all, and only exists to allow checking if an object is a number by doing isinstance(obj, Number).
~numbers.Complex is a subclass of ~numbers.Number. Complex numbers can undergo the basic operations of addition, subtraction, multiplication, division, and exponentiation, and you can retrieve the real and imaginary parts and obtain a number's conjugate. Python's built-in complex type is an implementation of ~numbers.Complex.
~numbers.Real further derives from ~numbers.Complex, and adds operations that only work on real numbers: ~math.floor, ~math.trunc, rounding, taking the remainder mod N, floor division, and comparisons.
~numbers.Rational numbers derive from ~numbers.Real, have ~numbers.Rational.numerator and ~numbers.Rational.denominator properties, and can be converted to floats. Python 2.6 adds a simple rational-number class, ~fractions.Fraction, in the fractions module. (It's called ~fractions.Fraction instead of Rational to avoid a name clash with numbers.Rational.)
~numbers.Integral numbers derive from ~numbers.Rational, and can be shifted left and right with << and >>, combined using bitwise operations such as & and |, and can be used as array indexes and slice boundaries.
In Python 3.0, the PEP slightly redefines the existing builtins round, math.floor, math.ceil, and adds a new one, math.trunc, that's been backported to Python 2.6. math.trunc rounds toward zero, returning the closest ~numbers.Integral that's between the function's argument and zero.
3141 - A Type Hierarchy for Numbers
PEP written by Jeffrey Yasskin.
Scheme's numerical tower, from the Guile manual.
Scheme's number datatypes from the R5RS Scheme specification.
The fractions Module
To fill out the hierarchy of numeric types, the fractions module provides a rational-number class. Rational numbers store their values as a numerator and denominator forming a fraction, and can exactly represent numbers such as 2/3 that floating-point numbers can only approximate.
The ~fractions.Fraction constructor takes two ~numbers.Integral values that will be the numerator and denominator of the resulting fraction. :
>>> from fractions import Fraction
>>> a = Fraction(2, 3)
>>> b = Fraction(2, 5)
>>> float(a), float(b)
(0.66666666666666663, 0.40000000000000002)
>>> a+b
Fraction(16, 15)
>>> a/b
Fraction(5, 3)
For converting floating-point numbers to rationals, the float type now has an ~float.as_integer_ratio method that returns the numerator and denominator for a fraction that evaluates to the same floating-point value:
>>> (2.5) .as_integer_ratio()
(5, 2)
>>> (3.1415) .as_integer_ratio()
(7074029114692207L, 2251799813685248L)
>>> (1./3) .as_integer_ratio()
(6004799503160661L, 18014398509481984L)
Note that values that can only be approximated by floating-point numbers, such as 1./3, are not simplified to the number being approximated; the fraction attempts to match the floating-point value exactly.
The fractions module is based upon an implementation by Sjoerd Mullender that was in Python's Demo/classes/ directory for a long time. This implementation was significantly updated by Jeffrey Yasskin.
Other Language Changes
Some smaller changes made to the core Python language are:
-
Directories and zip archives containing a
__main__.pyfile can now be executed directly by passing their name to the interpreter. The directory or zip archive is automatically inserted as the first entry in sys.path. (Suggestion and initial patch by Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;1739468.) -
The
hasattrfunction was catching and ignoring all errors, under the assumption that they meant a~object.__getattr__method was failing somehow and the return value ofhasattrwould therefore beFalse. This logic shouldn't be applied toKeyboardInterruptandSystemExit, however; Python 2.6 will no longer discard such exceptions whenhasattrencounters them. (Fixed by Benjamin Peterson;2196.) -
When calling a function using the
**syntax to provide keyword arguments, you are no longer required to use a Python dictionary; any mapping will now work:>>> def f(**kw): ... print sorted(kw) ... >>> ud=UserDict.UserDict() >>> ud['a'] = 1 >>> ud['b'] = 'string' >>> f(**ud) ['a', 'b'](Contributed by Alexander Belopolsky;
1686487.)It's also become legal to provide keyword arguments after a
*argsargument to a function call. :>>> def f(*args, **kw): ... print args, kw ... >>> f(1,2,3, *(4,5,6), keyword=13) (1, 2, 3, 4, 5, 6) {'keyword': 13}Previously this would have been a syntax error. (Contributed by Amaury Forgeot d'Arc;
3473.) -
A new builtin,
next(iterator, [default])returns the next item from the specified iterator. If the default argument is supplied, it will be returned if iterator has been exhausted; otherwise, theStopIterationexception will be raised. (Backported in2719.) -
Tuples now have
~tuple.indexand~tuple.countmethods matching the list type's~list.indexand~list.countmethods:>>> t = (0,1,2,3,4,0,1,2) >>> t.index(3) 3 >>> t.count(0) 2(Contributed by Raymond Hettinger)
-
The built-in types now have improved support for extended slicing syntax, accepting various combinations of
(start, stop, step). Previously, the support was partial and certain corner cases wouldn't work. (Implemented by Thomas Wouters.) -
Properties now have three decorators,
~property.getter,~property.setterand~property.deleter, that are decorators providing useful shortcuts for adding a getter, setter or deleter function to an existing property. You would use them like this:class C(object): @property def x(self): return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x class D(C): @C.x.getter def x(self): return self._x * 2 @x.setter def x(self, value): self._x = value / 2 -
Several methods of the built-in set types now accept multiple iterables:
~set.intersection,~set.intersection_update,~set.union,~set.update,~set.differenceand~set.difference_update.>>> s=set('1234567890') >>> s.intersection('abc123', 'cdf246') # Intersection between all inputs set(['2']) >>> s.difference('246', '789') set(['1', '0', '3', '5'])(Contributed by Raymond Hettinger.)
-
Many floating-point features were added. The
floatfunction will now turn the stringnaninto an IEEE 754 Not A Number value, and+infand-infinto positive or negative infinity. This works on any platform with IEEE 754 semantics. (Contributed by Christian Heimes;1635.)Other functions in the
mathmodule,~math.isinfand~math.isnan, return true if their floating-point argument is infinite or Not A Number. (1640)Conversion functions were added to convert floating-point numbers into hexadecimal strings (
3008). These functions convert floats to and from a string representation without introducing rounding errors from the conversion between decimal and binary. Floats have ahexmethod that returns a string representation, and thefloat.fromhex()method converts a string back into a number:>>> a = 3.75 >>> a.hex() '0x1.e000000000000p+1' >>> float.fromhex('0x1.e000000000000p+1') 3.75 >>> b=1./3 >>> b.hex() '0x1.5555555555555p-2' -
A numerical nicety: when creating a complex number from two floats on systems that support signed zeros (-0 and +0), the
complexconstructor will now preserve the sign of the zero. (Fixed by Mark T. Dickinson;1507.) -
Classes that inherit a
~object.__hash__method from a parent class can set__hash__ = Noneto indicate that the class isn't hashable. This will makehash(obj)raise aTypeErrorand the class will not be indicated as implementing theHashableABC.You should do this when you've defined a
!__cmp__or~object.__eq__method that compares objects by their value rather than by identity. All objects have a default hash method that usesid(obj)as the hash value. There's no tidy way to remove the~object.__hash__method inherited from a parent class, so assigningNonewas implemented as an override. At the C level, extensions can settp_hashtoPyObject_HashNotImplemented. (Fixed by Nick Coghlan and Amaury Forgeot d'Arc;2235.) -
The
GeneratorExitexception now subclassesBaseExceptioninstead ofException. This means that an exception handler that doesexcept Exception:will not inadvertently catchGeneratorExit. (Contributed by Chad Austin;1537.) -
Generator objects now have a
!gi_codeattribute that refers to the original code object backing the generator. (Contributed by Collin Winter;1473257.) -
The
compilebuilt-in function now accepts keyword arguments as well as positional parameters. (Contributed by Thomas Wouters;1444529.) -
The
complexconstructor now accepts strings containing parenthesized complex numbers, meaning thatcomplex(repr(cplx))will now round-trip values. For example,complex('(3+4j)')now returns the value (3+4j). (1491866) -
The string
~str.translatemethod now acceptsNoneas the translation table parameter, which is treated as the identity transformation. This makes it easier to carry out operations that only delete characters. (Contributed by Bengt Richter and implemented by Raymond Hettinger;1193128.) -
The built-in
dirfunction now checks for a~object.__dir__method on the objects it receives. This method must return a list of strings containing the names of valid attributes for the object, and lets the object control the value thatdirproduces. Objects that have~object.__getattr__or~object.__getattribute__methods can use this to advertise pseudo-attributes they will honor. (1591665) -
Instance method objects have new attributes for the object and function comprising the method; the new synonym for
!im_selfis~method.__self__, and!im_funcis also available as~method.__func__. The old names are still supported in Python 2.6, but are gone in 3.0. -
An obscure change: when you use the
localsfunction inside aclassstatement, the resulting dictionary no longer returns free variables. (Free variables, in this case, are variables referenced in the!classstatement that aren't attributes of the class.)
Optimizations
-
The
warningsmodule has been rewritten in C. This makes it possible to invoke warnings from the parser, and may also make the interpreter's startup faster. (Contributed by Neal Norwitz and Brett Cannon;1631171.) -
Type objects now have a cache of methods that can reduce the work required to find the correct method implementation for a particular class; once cached, the interpreter doesn't need to traverse base classes to figure out the right method to call. The cache is cleared if a base class or the class itself is modified, so the cache should remain correct even in the face of Python's dynamic nature. (Original optimization implemented by Armin Rigo, updated for Python 2.6 by Kevin Jacobs;
1700288.)By default, this change is only applied to types that are included with the Python core. Extension modules may not necessarily be compatible with this cache, so they must explicitly add
Py_TPFLAGS_HAVE_VERSION_TAGto the module'stp_flagsfield to enable the method cache. (To be compatible with the method cache, the extension module's code must not directly access and modify thetp_dictmember of any of the types it implements. Most modules don't do this, but it's impossible for the Python interpreter to determine that. See1878for some discussion.) -
Function calls that use keyword arguments are significantly faster by doing a quick pointer comparison, usually saving the time of a full string comparison. (Contributed by Raymond Hettinger, after an initial implementation by Antoine Pitrou;
1819.) -
All of the functions in the
structmodule have been rewritten in C, thanks to work at the Need For Speed sprint. (Contributed by Raymond Hettinger.) -
Some of the standard built-in types now set a bit in their type objects. This speeds up checking whether an object is a subclass of one of these types. (Contributed by Neal Norwitz.)
-
Unicode strings now use faster code for detecting whitespace and line breaks; this speeds up the
~str.splitmethod by about 25% and~str.splitlinesby 35%. (Contributed by Antoine Pitrou.) Memory usage is reduced by using pymalloc for the Unicode string's data. -
The
withstatement now stores the~object.__exit__method on the stack, producing a small speedup. (Implemented by Jeffrey Yasskin.) -
To reduce memory usage, the garbage collector will now clear internal free lists when garbage-collecting the highest generation of objects. This may return memory to the operating system sooner.
Interpreter Changes
Two command-line options have been reserved for use by other Python implementations. The !-J switch has been reserved for use by Jython for Jython-specific options, such as switches that are passed to the underlying JVM. -X has been reserved for options specific to a particular implementation of Python such as CPython, Jython, or IronPython. If either option is used with Python 2.6, the interpreter will report that the option isn't currently used.
Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the sys.dont_write_bytecode variable, and Python code can change the value to modify the interpreter's behaviour. (Contributed by Neal Norwitz and Georg Brandl.)
The encoding used for standard input, output, and standard error can be specified by setting the PYTHONIOENCODING environment variable before running the interpreter. The value should be a string in the form <encoding> or <encoding>:<errorhandler>. The encoding part specifies the encoding's name, e.g. utf-8 or latin-1; the optional errorhandler part specifies what to do with characters that can't be handled by the encoding, and should be one of "error", "ignore", or "replace". (Contributed by Martin von Löwis.)
New and Improved Modules
As in every release, Python's standard library received a number of enhancements and bug fixes. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the Subversion logs for all the details.
-
The
!asyncoreand!asynchatmodules are being actively maintained again, and a number of patches and bugfixes were applied. (Maintained by Josiah Carlson; see1736190for one patch.) -
The
!bsddbmodule also has a new maintainer, Jesús Cea Avión, and the package is now available as a standalone package. The web page for the package is www.jcea.es/programacion/pybsddb.htm. The plan is to remove the package from the standard library in Python 3.0, because its pace of releases is much more frequent than Python's.The
!bsddb.dbshelvemodule now uses the highest pickling protocol available, instead of restricting itself to protocol 1. (Contributed by W. Barnes.) -
The
!cgimodule will now read variables from the query string of an HTTP POST request. This makes it possible to use form actions with URLs that include query strings such as "/cgi-bin/add.py?category=1". (Contributed by Alexandre Fiori and Nubis;1817.)The
~urllib.parse.parse_qsand~urllib.parse.parse_qslfunctions have been relocated from the!cgimodule to theurlparse <urllib.parse>module. The versions still available in the!cgimodule will triggerPendingDeprecationWarningmessages in 2.6 (600362). -
The
cmathmodule underwent extensive revision, contributed by Mark Dickinson and Christian Heimes. Five new functions were added:~cmath.polarconverts a complex number to polar form, returning the modulus and argument of the complex number.~cmath.rectdoes the opposite, turning a modulus, argument pair back into the corresponding complex number.~cmath.phasereturns the argument (also called the angle) of a complex number.~cmath.isnanreturns True if either the real or imaginary part of its argument is a NaN.~cmath.isinfreturns True if either the real or imaginary part of its argument is infinite.
The revisions also improved the numerical soundness of the
cmathmodule. For all functions, the real and imaginary parts of the results are accurate to within a few units of least precision (ulps) whenever possible. See1381for the details. The branch cuts for~cmath.asinh,~cmath.atanh, and~cmath.atanhave also been corrected.The tests for the module have been greatly expanded; nearly 2000 new test cases exercise the algebraic functions.
On IEEE 754 platforms, the
cmathmodule now handles IEEE 754 special values and floating-point exceptions in a manner consistent with Annex 'G' of the C99 standard. -
A new data type in the
collectionsmodule:namedtuple(typename, fieldnames)is a factory function that creates subclasses of the standard tuple whose fields are accessible by name as well as index. For example:>>> var_type = collections.namedtuple('variable', ... 'id name type size') >>> # Names are separated by spaces or commas. >>> # 'id, name, type, size' would also work. >>> var_type._fields ('id', 'name', 'type', 'size') >>> var = var_type(1, 'frequency', 'int', 4) >>> print var[0], var.id # Equivalent 1 1 >>> print var[2], var.type # Equivalent int int >>> var._asdict() {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'} >>> v2 = var._replace(name='amplitude') >>> v2 variable(id=1, name='amplitude', type='int', size=4)Several places in the standard library that returned tuples have been modified to return
~collections.namedtupleinstances. For example, thedecimal.Decimal.as_tuplemethod now returns a named tuple with!sign,!digits, and!exponentfields.(Contributed by Raymond Hettinger.)
-
Another change to the
collectionsmodule is that the~collections.dequetype now supports an optional maxlen parameter; if supplied, the deque's size will be restricted to no more than maxlen items. Adding more items to a full deque causes old items to be discarded.>>> from collections import deque >>> dq=deque(maxlen=3) >>> dq deque([], maxlen=3) >>> dq.append(1); dq.append(2); dq.append(3) >>> dq deque([1, 2, 3], maxlen=3) >>> dq.append(4) >>> dq deque([2, 3, 4], maxlen=3)(Contributed by Raymond Hettinger.)
-
The
Cookie <http.cookies>module's~http.cookies.Morselobjects now support an~http.cookies.Morsel.httponlyattribute. In some browsers. cookies with this attribute set cannot be accessed or manipulated by JavaScript code. (Contributed by Arvin Schnell;1638033.) -
A new window method in the
cursesmodule,~curses.window.chgat, changes the display attributes for a certain number of characters on a single line. (Contributed by Fabian Kreutz.)# Boldface text starting at y=0,x=21 # and affecting the rest of the line. stdscr.chgat(0, 21, curses.A_BOLD)The
~curses.textpad.Textboxclass in thecurses.textpadmodule now supports editing in insert mode as well as overwrite mode. Insert mode is enabled by supplying a true value for the insert_mode parameter when creating the~curses.textpad.Textboxinstance. -
The
datetimemodule's~datetime.datetime.strftimemethods now support a%fformat code that expands to the number of microseconds in the object, zero-padded on the left to six places. (Contributed by Skip Montanaro;1158.) -
The
decimalmodule was updated to version 1.66 of the General Decimal Specification. New features include some methods for some basic mathematical functions such as~decimal.Decimal.expand~decimal.Decimal.log10:>>> Decimal(1).exp() Decimal("2.718281828459045235360287471") >>> Decimal("2.7182818").ln() Decimal("0.9999999895305022877376682436") >>> Decimal(1000).log10() Decimal("3")The
~decimal.Decimal.as_tuplemethod of~decimal.Decimalobjects now returns a named tuple with!sign,!digits, and!exponentfields.(Implemented by Facundo Batista and Mark Dickinson. Named tuple support added by Raymond Hettinger.)
-
The
difflibmodule's~difflib.SequenceMatcherclass now returns named tuples representing matches, with!a,!b, and!sizeattributes. (Contributed by Raymond Hettinger.) -
An optional
timeoutparameter, specifying a timeout measured in seconds, was added to theftplib.FTPclass constructor as well as the~ftplib.FTP.connectmethod. (Added by Facundo Batista.) Also, the~ftplib.FTPclass's~ftplib.FTP.storbinaryand~ftplib.FTP.storlinesnow take an optional callback parameter that will be called with each block of data after the data has been sent. (Contributed by Phil Schwartz;1221598.) -
The
!reducebuilt-in function is also available in thefunctoolsmodule. In Python 3.0, the builtin has been dropped and~functools.reduceis only available fromfunctools; currently there are no plans to drop the builtin in the 2.x series. (Patched by Christian Heimes;1739906.) -
When possible, the
getpassmodule will now use/dev/ttyto print a prompt message and read the password, falling back to standard error and standard input. If the password may be echoed to the terminal, a warning is printed before the prompt is displayed. (Contributed by Gregory P. Smith.) -
The
glob.globfunction can now return Unicode filenames if a Unicode path was used and Unicode filenames are matched within the directory. (1001604) -
A new function in the
heapqmodule,merge(iter1, iter2, ...), takes any number of iterables returning data in sorted order, and returns a new generator that returns the contents of all the iterators, also in sorted order. For example:>>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16])) [1, 2, 3, 5, 8, 9, 16]Another new function,
heappushpop(heap, item), pushes item onto heap, then pops off and returns the smallest item. This is more efficient than making a call to~heapq.heappushand then~heapq.heappop.heapqis now implemented to only use less-than comparison, instead of the less-than-or-equal comparison it previously used. This makesheapq's usage of a type match thelist.sortmethod. (Contributed by Raymond Hettinger.) -
An optional
timeoutparameter, specifying a timeout measured in seconds, was added to thehttplib.HTTPConnection <http.client.HTTPConnection>andHTTPSConnection <http.client.HTTPSConnection>class constructors. (Added by Facundo Batista.) -
Most of the
inspectmodule's functions, such as!getmoduleinfoand!getargs, now return named tuples. In addition to behaving like tuples, the elements of the return value can also be accessed as attributes. (Contributed by Raymond Hettinger.)Some new functions in the module include
~inspect.isgenerator,~inspect.isgeneratorfunction, and~inspect.isabstract. -
The
itertoolsmodule gained several new functions.izip_longest(iter1, iter2, ...[, fillvalue])makes tuples from each of the elements; if some of the iterables are shorter than others, the missing values are set to fillvalue. For example:>>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5])) ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))product(iter1, iter2, ..., [repeat=N])returns the Cartesian product of the supplied iterables, a set of tuples containing every possible combination of the elements returned from each iterable. :>>> list(itertools.product([1,2,3], [4,5,6])) [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]The optional repeat keyword argument is used for taking the product of an iterable or a set of iterables with themselves, repeated N times. With a single iterable argument, N-tuples are returned:
>>> list(itertools.product([1,2], repeat=3)) [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]With two iterables, 2N-tuples are returned. :
>>> list(itertools.product([1,2], [3,4], repeat=2)) [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4), (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4), (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4), (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]combinations(iterable, r)returns sub-sequences of length r from the elements of iterable. :>>> list(itertools.combinations('123', 2)) [('1', '2'), ('1', '3'), ('2', '3')] >>> list(itertools.combinations('123', 3)) [('1', '2', '3')] >>> list(itertools.combinations('1234', 3)) [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'), ('2', '3', '4')]permutations(iter[, r])returns all the permutations of length r of the iterable's elements. If r is not specified, it will default to the number of elements produced by the iterable. :>>> list(itertools.permutations([1,2,3,4], 2)) [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]itertools.chain(*iterables)is an existing function initertoolsthat gained a new constructor in Python 2.6.itertools.chain.from_iterable(iterable)takes a single iterable that should return other iterables.~itertools.chainwill then return all the elements of the first iterable, then all the elements of the second, and so on. :>>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]])) [1, 2, 3, 4, 5, 6](All contributed by Raymond Hettinger.)
-
The
loggingmodule's~logging.FileHandlerclass and its subclasses~logging.handlers.WatchedFileHandler,~logging.handlers.RotatingFileHandler, and~logging.handlers.TimedRotatingFileHandlernow have an optional delay parameter to their constructors. If delay is true, opening of the log file is deferred until the first~logging.FileHandler.emitcall is made. (Contributed by Vinay Sajip.)~logging.handlers.TimedRotatingFileHandleralso has a utc constructor parameter. If the argument is true, UTC time will be used in determining when midnight occurs and in generating filenames; otherwise local time will be used. -
Several new functions were added to the
mathmodule:~math.isinfand~math.isnandetermine whether a given float is a (positive or negative) infinity or a NaN (Not a Number), respectively.~math.copysigncopies the sign bit of an IEEE 754 number, returning the absolute value of x combined with the sign bit of y. For example,math.copysign(1, -0.0)returns -1.0. (Contributed by Christian Heimes.)~math.factorialcomputes the factorial of a number. (Contributed by Raymond Hettinger;2138.)~math.fsumadds up the stream of numbers from an iterable, and is careful to avoid loss of precision through using partial sums. (Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;2819.)~math.acosh,~math.asinhand~math.atanhcompute the inverse hyperbolic functions.~math.log1preturns the natural logarithm of 1+x (base e).~math.truncrounds a number toward zero, returning the closest~numbers.Integralthat's between the function's argument and zero. Added as part of the backport of PEP 3141's type hierarchy for numbers.
-
The
mathmodule has been improved to give more consistent behaviour across platforms, especially with respect to handling of floating-point exceptions and IEEE 754 special values.Whenever possible, the module follows the recommendations of the C99 standard about 754's special values. For example,
sqrt(-1.)should now give aValueErroracross almost all platforms, whilesqrt(float('NaN'))should return a NaN on all IEEE 754 platforms. Where Annex 'F' of the C99 standard recommends signaling 'divide-by-zero' or 'invalid', Python will raiseValueError. Where Annex 'F' of the C99 standard recommends signaling 'overflow', Python will raiseOverflowError. (See711019and1640.)(Contributed by Christian Heimes and Mark Dickinson.)
-
~mmap.mmapobjects now have a~mmap.mmap.rfindmethod that searches for a substring beginning at the end of the string and searching backwards. The~mmap.mmap.findmethod also gained an end parameter giving an index at which to stop searching. (Contributed by John Lenton.) -
The
operatormodule gained a~operator.methodcallerfunction that takes a name and an optional set of arguments, returning a callable that will call the named function on any arguments passed to it. For example:>>> # Equivalent to lambda s: s.replace('old', 'new') >>> replacer = operator.methodcaller('replace', 'old', 'new') >>> replacer('old wine in old bottles') 'new wine in new bottles'(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
The
~operator.attrgetterfunction now accepts dotted names and performs the corresponding attribute lookups:>>> inst_name = operator.attrgetter( ... '__class__.__name__') >>> inst_name('') 'str' >>> inst_name(help) '_Helper'(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
-
The
osmodule now wraps several new system calls.fchmod(fd, mode)andfchown(fd, uid, gid)change the mode and ownership of an opened file, andlchmod(path, mode)changes the mode of a symlink. (Contributed by Georg Brandl and Christian Heimes.)~os.chflagsand~os.lchflagsare wrappers for the corresponding system calls (where they're available), changing the flags set on a file. Constants for the flag values are defined in thestatmodule; some possible values include~stat.UF_IMMUTABLEto signal the file may not be changed and~stat.UF_APPENDto indicate that data can only be appended to the file. (Contributed by M. Levinson.)os.closerange(low, high)efficiently closes all file descriptors from low to high, ignoring any errors and not including high itself. This function is now used by thesubprocessmodule to make starting processes faster. (Contributed by Georg Brandl;1663329.) -
The
os.environobject's!clearmethod will now unset the environment variables usingos.unsetenvin addition to clearing the object's keys. (Contributed by Martin Horcicka;1181.) -
The
os.walkfunction now has afollowlinksparameter. If set to True, it will follow symlinks pointing to directories and visit the directory's contents. For backward compatibility, the parameter's default value is false. Note that the function can fall into an infinite recursion if there's a symlink that points to a parent directory. (1273829) -
In the
os.pathmodule, the~os.path.splitextfunction has been changed to not split on leading period characters. This produces better results when operating on Unix's dot-files. For example,os.path.splitext('.ipython')now returns('.ipython', '')instead of('', '.ipython'). (1115886)A new function,
os.path.relpath(path, start='.'), returns a relative path from thestartpath, if it's supplied, or from the current working directory to the destinationpath. (Contributed by Richard Barran;1339796.)On Windows,
os.path.expandvarswill now expand environment variables given in the form "%var%", and "~user" will be expanded into the user's home directory path. (Contributed by Josiah Carlson;957650.) -
The Python debugger provided by the
pdbmodule gained a new command: "run" restarts the Python program being debugged and can optionally take new command-line arguments for the program. (Contributed by Rocky Bernstein;1393667.) -
The
pdb.post_mortemfunction, used to begin debugging a traceback, will now use the traceback returned bysys.exc_infoif no traceback is supplied. (Contributed by Facundo Batista;1106316.) -
The
pickletoolsmodule now has an~pickletools.optimizefunction that takes a string containing a pickle and removes some unused opcodes, returning a shorter pickle that contains the same data structure. (Contributed by Raymond Hettinger.) -
A
~pkgutil.get_datafunction was added to thepkgutilmodule that returns the contents of resource files included with an installed Python package. For example:>>> import pkgutil >>> print pkgutil.get_data('test', 'exception_hierarchy.txt') BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError ...(Contributed by Paul Moore;
2439.) -
The
!pyexpatmodule's!Parserobjects now allow setting their!buffer_sizeattribute to change the size of the buffer used to hold character data. (Contributed by Achim Gaedke;1137.) -
The
queuemodule now provides queue variants that retrieve entries in different orders. The~queue.PriorityQueueclass stores queued items in a heap and retrieves them in priority order, and~queue.LifoQueueretrieves the most recently added entries first, meaning that it behaves like a stack. (Contributed by Raymond Hettinger.) -
The
randommodule's~random.Randomobjects can now be pickled on a 32-bit system and unpickled on a 64-bit system, and vice versa. Unfortunately, this change also means that Python 2.6's~random.Randomobjects can't be unpickled correctly on earlier versions of Python. (Contributed by Shawn Ligocki;1727780.)The new
triangular(low, high, mode)function returns random numbers following a triangular distribution. The returned values are between low and high, not including high itself, and with mode as the most frequently occurring value in the distribution. (Contributed by Wladmir van der Laan and Raymond Hettinger;1681432.) -
Long regular expression searches carried out by the
remodule will check for signals being delivered, so time-consuming searches can now be interrupted. (Contributed by Josh Hoyt and Ralf Schmitt;846388.)The regular expression module is implemented by compiling bytecodes for a tiny regex-specific virtual machine. Untrusted code could create malicious strings of bytecode directly and cause crashes, so Python 2.6 includes a verifier for the regex bytecode. (Contributed by Guido van Rossum from work for Google App Engine;
3487.) -
The
rlcompletermodule's~rlcompleter.Completer.completemethod will now ignore exceptions triggered while evaluating a name. (Fixed by Lorenz Quack;2250.) -
The
schedmodule's~sched.schedulerinstances now have a read-onlyqueueattribute that returns the contents of the scheduler's queue, represented as a list of named tuples with the fields(time, priority, action, argument). (Contributed by Raymond Hettinger;1861.) -
The
selectmodule now has wrapper functions for the Linux!epolland BSD!kqueuesystem calls.~select.poll.modifymethod was added to the existingpollobjects;pollobj.modify(fd, eventmask)takes a file descriptor or file object and an event mask, modifying the recorded event mask for that file. (Contributed by Christian Heimes;1657.) -
The
shutil.copytreefunction now has an optional ignore argument that takes a callable object. This callable will receive each directory path and a list of the directory's contents, and returns a list of names that will be ignored, not copied.The
shutilmodule also provides an~shutil.ignore_patternsfunction for use with this new parameter.~shutil.ignore_patternstakes an arbitrary number of glob-style patterns and returns a callable that will ignore any files and directories that match any of these patterns. The following example copies a directory tree, but skips both.svndirectories and Emacs backup files, which have names ending with '~':shutil.copytree('Doc/library', '/tmp/library', ignore=shutil.ignore_patterns('*~', '.svn'))(Contributed by Tarek Ziadé;
2663.) -
Integrating signal handling with GUI handling event loops like those used by Tkinter or GTk+ has long been a problem; most software ends up polling, waking up every fraction of a second to check if any GUI events have occurred. The
signalmodule can now make this more efficient. Callingsignal.set_wakeup_fd(fd)sets a file descriptor to be used; when a signal is received, a byte is written to that file descriptor. There's also a C-level function,PySignal_SetWakeupFd, for setting the descriptor.Event loops will use this by opening a pipe to create two descriptors, one for reading and one for writing. The writable descriptor will be passed to
~signal.set_wakeup_fd, and the readable descriptor will be added to the list of descriptors monitored by the event loop via!selector!poll. On receiving a signal, a byte will be written and the main event loop will be woken up, avoiding the need to poll.(Contributed by Adam Olsen;
1583.)The
~signal.siginterruptfunction is now available from Python code, and allows changing whether signals can interrupt system calls or not. (Contributed by Ralf Schmitt.)The
~signal.setitimerand~signal.getitimerfunctions have also been added (where they're available).~signal.setitimerallows setting interval timers that will cause a signal to be delivered to the process after a specified time, measured in wall-clock time, consumed process time, or combined process+system time. (Contributed by Guilherme Polo;2240.) -
The
smtplibmodule now supports SMTP over SSL thanks to the addition of the~smtplib.SMTP_SSLclass. This class supports an interface identical to the existing~smtplib.SMTPclass. (Contributed by Monty Taylor.) Both class constructors also have an optionaltimeoutparameter that specifies a timeout for the initial connection attempt, measured in seconds. (Contributed by Facundo Batista.)An implementation of the LMTP protocol (
2033) was also added to the module. LMTP is used in place of SMTP when transferring e-mail between agents that don't manage a mail queue. (LMTP implemented by Leif Hedstrom;957003.)smtplib.SMTP.starttlsnow complies with3207and forgets any knowledge obtained from the server not obtained from the TLS negotiation itself. (Patch contributed by Bill Fenner;829951.) -
The
socketmodule now supports TIPC (https://tipc.sourceforge.net/), a high-performance non-IP-based protocol designed for use in clustered environments. TIPC addresses are 4- or 5-tuples. (Contributed by Alberto Bertogli;1646.)A new function,
~socket.create_connection, takes an address and connects to it using an optional timeout value, returning the connected socket object. This function also looks up the address's type and connects to it using IPv4 or IPv6 as appropriate. Changing your code to use~socket.create_connectioninstead ofsocket(socket.AF_INET, ...)may be all that's required to make your code work with IPv6. -
The base classes in the
SocketServer <socketserver>module now support calling a~socketserver.BaseServer.handle_timeoutmethod after a span of inactivity specified by the server's~socketserver.BaseServer.timeoutattribute. (Contributed by Michael Pomraning.) The~socketserver.BaseServer.serve_forevermethod now takes an optional poll interval measured in seconds, controlling how often the server will check for a shutdown request. (Contributed by Pedro Werneck and Jeffrey Yasskin;742598,1193577.) -
The
sqlite3module, maintained by Gerhard Häring, has been updated from version 2.3.2 in Python 2.5 to version 2.4.1. -
The
structmodule now supports the C99_Booltype, using the format character'?'. (Contributed by David Remahl.) -
The
~subprocess.Popenobjects provided by thesubprocessmodule now have~subprocess.Popen.terminate,~subprocess.Popen.kill, and~subprocess.Popen.send_signalmethods. On Windows,!send_signalonly supports the~signal.SIGTERMsignal, and all these methods are aliases for the Win32 API function!TerminateProcess. (Contributed by Christian Heimes.) -
A new variable in the
sysmodule,~sys.float_info, is an object containing information derived from thefloat.hfile about the platform's floating-point support. Attributes of this object include~sys.float_info.mant_dig(number of digits in the mantissa),~sys.float_info.epsilon(smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes;1534.)Another new variable,
~sys.dont_write_bytecode, controls whether Python writes any.pycor.pyofiles on importing a module. If this variable is true, the compiled files are not written. The variable is initially set on start-up by supplying the-Bswitch to the Python interpreter, or by setting thePYTHONDONTWRITEBYTECODEenvironment variable before running the interpreter. Python code can subsequently change the value of this variable to control whether bytecode files are written or not. (Contributed by Neal Norwitz and Georg Brandl.)Information about the command-line arguments supplied to the Python interpreter is available by reading attributes of a named tuple available as
sys.flags. For example, the~sys.flags.verboseattribute is true if Python was executed in verbose mode,~sys.flags.debugis true in debugging mode, etc. These attributes are all read-only. (Contributed by Christian Heimes.)A new function,
~sys.getsizeof, takes a Python object and returns the amount of memory used by the object, measured in bytes. Built-in objects return correct results; third-party extensions may not, but can define a!__sizeof__method to return the object's size. (Contributed by Robert Schuppenies;2898.)It's now possible to determine the current profiler and tracer functions by calling
sys.getprofileandsys.gettrace. (Contributed by Georg Brandl;1648.) -
The
tarfilemodule now supports POSIX.1-2001 (pax) tarfiles in addition to the POSIX.1-1988 (ustar) and GNU tar formats that were already supported. The default format is GNU tar; specify theformatparameter to open a file using a different format:tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)The new
encodinganderrorsparameters specify an encoding and an error handling scheme for character conversions.'strict','ignore', and'replace'are the three standard ways Python can handle errors,;'utf-8'is a special value that replaces bad characters with their UTF-8 representation. (Character conversions occur because the PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)The
tarfile.TarFile.addmethod now accepts anexcludeargument that's a function that can be used to exclude certain filenames from an archive. The function must take a filename and return true if the file should be excluded or false if it should be archived. The function is applied to both the name initially passed to~tarfile.TarFile.addand to the names of files in recursively added directories.(All changes contributed by Lars Gustäbel).
-
An optional
timeoutparameter was added to the!telnetlib.Telnetclass constructor, specifying a timeout measured in seconds. (Added by Facundo Batista.) -
The
tempfile.NamedTemporaryFileclass usually deletes the temporary file it created when the file is closed. This behaviour can now be changed by passingdelete=Falseto the constructor. (Contributed by Damien Miller;1537850.)A new class,
~tempfile.SpooledTemporaryFile, behaves like a temporary file but stores its data in memory until a maximum size is exceeded. On reaching that limit, the contents will be written to an on-disk temporary file. (Contributed by Dustin J. Mitchell.)The
~tempfile.NamedTemporaryFileand~tempfile.SpooledTemporaryFileclasses both work as context managers, so you can writewith tempfile.NamedTemporaryFile() as tmp: .... (Contributed by Alexander Belopolsky;2021.) -
The
test.test_support <test.support>module gained a number of context managers useful for writing tests.~test.support.os_helper.EnvironmentVarGuardis a context manager that temporarily changes environment variables and automatically restores them to their old values.Another context manager,
!TransientResource, can surround calls to resources that may or may not be available; it will catch and ignore a specified list of exceptions. For example, a network test may ignore certain failures when connecting to an external web site:with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT): f = urllib.urlopen('https://sf.net') ...Finally,
~test.support.warnings_helper.check_warningsresets thewarningsmodule's warning filters and returns an object that will record all warning messages triggered (3781):with test_support.check_warnings() as wrec: warnings.simplefilter("always") # ... code that triggers a warning ... assert str(wrec.message) == "function is outdated" assert len(wrec.warnings) == 1, "Multiple warnings raised"(Contributed by Brett Cannon.)
-
The
textwrapmodule can now preserve existing whitespace at the beginnings and ends of the newly created lines by specifyingdrop_whitespace=Falseas an argument:>>> S = """This sentence has a bunch of ... extra whitespace.""" >>> print textwrap.fill(S, width=15) This sentence has a bunch of extra whitespace. >>> print textwrap.fill(S, drop_whitespace=False, width=15) This sentence has a bunch of extra whitespace. >>>(Contributed by Dwayne Bailey;
1581073.) -
The
threadingmodule API is being changed to use properties such as~threading.Thread.daemoninstead of!setDaemonand!isDaemonmethods, and some methods have been renamed to use underscores instead of camel-case; for example, the!activeCountmethod is renamed to~threading.active_count. Both the 2.6 and 3.0 versions of the module support the same properties and renamed methods, but don't remove the old methods. No date has been set for the deprecation of the old APIs in Python 3.x; the old APIs won't be removed in any 2.x version. (Carried out by several people, most notably Benjamin Peterson.)The
threadingmodule's~threading.Threadobjects gained an~threading.Thread.identproperty that returns the thread's identifier, a nonzero integer. (Contributed by Gregory P. Smith;2871.) -
The
timeitmodule now accepts callables as well as strings for the statement being timed and for the setup code. Two convenience functions were added for creating~timeit.Timerinstances:repeat(stmt, setup, time, repeat, number)andtimeit(stmt, setup, time, number)create an instance and call the corresponding method. (Contributed by Erik Demaine;1533909.) -
The
tkintermodule now accepts lists and tuples for options, separating the elements by spaces before passing the resulting value to Tcl/Tk. (Contributed by Guilherme Polo;2906.) -
The
turtlemodule for turtle graphics was greatly enhanced by Gregor Lingl. New features in the module include:- Better animation of turtle movement and rotation.
- Control over turtle movement using the new
~turtle.delay,~turtle.tracer, and~turtle.speedmethods. - The ability to set new shapes for the turtle, and to define a new coordinate system.
- Turtles now have an
~turtle.undomethod that can roll back actions. - Simple support for reacting to input events such as mouse and keyboard activity, making it possible to write simple games.
- A
turtle.cfgfile can be used to customize the starting appearance of the turtle's screen. - The module's docstrings can be replaced by new docstrings that have been translated into another language.
(
1513695) -
An optional
timeoutparameter was added to theurllib.urlopen <urllib.request.urlopen>function and the!urllib.ftpwrapperclass constructor, as well as theurllib2.urlopen <urllib.request.urlopen>function. The parameter specifies a timeout measured in seconds. For example:>>> u = urllib2.urlopen("http://slow.example.com", ... timeout=3) Traceback (most recent call last): ... urllib2.URLError: <urlopen error timed out> >>>(Added by Facundo Batista.)
-
The Unicode database provided by the
unicodedatamodule has been updated to version 5.1.0. (Updated by Martin von Löwis;3811.) -
The
warningsmodule's~warnings.formatwarningand~warnings.showwarninggained an optional line argument that can be used to supply the line of source code. (Added as part of1631171, which re-implemented part of thewarningsmodule in C code.)A new function,
~warnings.catch_warnings, is a context manager intended for testing purposes that lets you temporarily modify the warning filters and then restore their original values (3781). -
The XML-RPC
~xmlrpc.server.SimpleXMLRPCServerand~xmlrpc.server.DocXMLRPCServerclasses can now be prevented from immediately opening and binding to their socket by passingFalseas the bind_and_activate constructor parameter. This can be used to modify the instance's~socketserver.BaseServer.allow_reuse_addressattribute before calling the~socketserver.BaseServer.server_bindand~socketserver.BaseServer.server_activatemethods to open the socket and begin listening for connections. (Contributed by Peter Parente;1599845.)~xmlrpc.server.SimpleXMLRPCServeralso has a!_send_traceback_headerattribute; if true, the exception and formatted traceback are returned as HTTP headers "X-Exception" and "X-Traceback". This feature is for debugging purposes only and should not be used on production servers because the tracebacks might reveal passwords or other sensitive information. (Contributed by Alan McIntyre as part of his project for Google's Summer of Code 2007.) -
The
xmlrpclib <xmlrpc.client>module no longer automatically convertsdatetime.dateanddatetime.timeto thexmlrpclib.DateTime <xmlrpc.client.DateTime>type; the conversion semantics were not necessarily correct for all applications. Code using!xmlrpclibshould convert~datetime.dateand~datetime.timeinstances. (1330538) The code can also handle dates before 1900 (contributed by Ralf Schmitt;2014) and 64-bit integers represented by using<i8>in XML-RPC responses (contributed by Riku Lindblad;2985). -
The
zipfilemodule's~zipfile.ZipFileclass now has~zipfile.ZipFile.extractand~zipfile.ZipFile.extractallmethods that will unpack a single file or all the files in the archive to the current directory, or to a specified directory:z = zipfile.ZipFile('python-251.zip') # Unpack a single file, writing it relative # to the /tmp directory. z.extract('Python/sysmodule.c', '/tmp') # Unpack all the files in the archive. z.extractall()(Contributed by Alan McIntyre;
467924.)The
~zipfile.ZipFile.open,~zipfile.ZipFile.readand~zipfile.ZipFile.extractmethods can now take either a filename or a~zipfile.ZipInfoobject. This is useful when an archive accidentally contains a duplicated filename. (Contributed by Graham Horler;1775025.)Finally,
zipfilenow supports using Unicode filenames for archived files. (Contributed by Alexey Borzenkov;1734346.)
The ast module
The ast module provides an Abstract Syntax Tree representation of Python code, and Armin Ronacher contributed a set of helper functions that perform a variety of common tasks. These will be useful for HTML templating packages, code analyzers, and similar tools that process Python code.
The ~ast.parse function takes an expression and returns an AST. The ~ast.dump function outputs a representation of a tree, suitable for debugging:
import ast
t = ast.parse("""
d = {}
for i in 'abcdefghijklm':
d[i + i] = ord(i) - ord('a') + 1
print d
""")
print ast.dump(t)
This outputs a deeply nested tree:
Module(body=[
Assign(targets=[
Name(id='d', ctx=Store())
], value=Dict(keys=[], values=[]))
For(target=Name(id='i', ctx=Store()),
iter=Str(s='abcdefghijklm'), body=[
Assign(targets=[
Subscript(value=
Name(id='d', ctx=Load()),
slice=
Index(value=
BinOp(left=Name(id='i', ctx=Load()), op=Add(),
right=Name(id='i', ctx=Load()))), ctx=Store())
], value=
BinOp(left=
BinOp(left=
Call(func=
Name(id='ord', ctx=Load()), args=[
Name(id='i', ctx=Load())
], keywords=[], starargs=None, kwargs=None),
op=Sub(), right=Call(func=
Name(id='ord', ctx=Load()), args=[
Str(s='a')
], keywords=[], starargs=None, kwargs=None)),
op=Add(), right=Num(n=1)))
], orelse=[])
Print(dest=None, values=[
Name(id='d', ctx=Load())
], nl=True)
])
The ~ast.literal_eval method takes a string or an AST representing a literal expression, parses and evaluates it, and returns the resulting value. A literal expression is a Python expression containing only strings, numbers, dictionaries, etc. but no statements or function calls. If you need to evaluate an expression but cannot accept the security risk of using an eval call, ~ast.literal_eval will handle it safely:
>>> literal = '("a", "b", {2:4, 3:8, 1:2})'
>>> print ast.literal_eval(literal)
('a', 'b', {1: 2, 2: 4, 3: 8})
>>> print ast.literal_eval('"a" + "b"')
Traceback (most recent call last):
...
ValueError: malformed string
The module also includes ~ast.NodeVisitor and ~ast.NodeTransformer classes for traversing and modifying an AST, and functions for common transformations such as changing line numbers.
The !future_builtins module
Python 3.0 makes many changes to the repertoire of built-in functions, and most of the changes can't be introduced in the Python 2.x series because they would break compatibility. The !future_builtins module provides versions of these built-in functions that can be imported when writing 3.0-compatible code.
The functions in this module currently include:
ascii(obj): equivalent torepr. In Python 3.0,reprwill return a Unicode string, whileasciiwill return a pure ASCII bytestring.filter(predicate, iterable),map(func, iterable1, ...): the 3.0 versions return iterators, unlike the 2.x builtins which return lists.hex(value),oct(value): instead of calling the!__hex__or!__oct__methods, these versions will call the~object.__index__method and convert the result to hexadecimal or octal.octwill use the new0onotation for its result.
The json module: JavaScript Object Notation
The new json module supports the encoding and decoding of Python types in JSON (Javascript Object Notation). JSON is a lightweight interchange format often used in web applications. For more information about JSON, see http://www.json.org.
json comes with support for decoding and encoding most built-in Python types. The following example encodes and decodes a dictionary:
>>> import json
>>> data = {"spam": "foo", "parrot": 42}
>>> in_json = json.dumps(data) # Encode the data
>>> in_json
'{"parrot": 42, "spam": "foo"}'
>>> json.loads(in_json) # Decode into a Python object
{"spam": "foo", "parrot": 42}
It's also possible to write your own decoders and encoders to support more types. Pretty-printing of the JSON strings is also supported.
json (originally called simplejson) was written by Bob Ippolito.
The plistlib module: A Property-List Parser
The .plist format is commonly used on Mac OS X to store basic data types (numbers, strings, lists, and dictionaries) by serializing them into an XML-based format. It resembles the XML-RPC serialization of data types.
Despite being primarily used on Mac OS X, the format has nothing Mac-specific about it and the Python implementation works on any platform that Python supports, so the plistlib module has been promoted to the standard library.
Using the module is simple:
import sys
import plistlib
import datetime as dt
# Create data structure
data_struct = dict(lastAccessed=dt.datetime.now(),
version=1,
categories=('Personal','Shared','Private'))
# Create string containing XML.
plist_str = plistlib.writePlistToString(data_struct)
new_struct = plistlib.readPlistFromString(plist_str)
print data_struct
print new_struct
# Write data structure to a file and read it back.
plistlib.writePlist(data_struct, '/tmp/customizations.plist')
new_struct = plistlib.readPlist('/tmp/customizations.plist')
# read/writePlist accepts file-like objects as well as paths.
plistlib.writePlist(data_struct, sys.stdout)
ctypes Enhancements
Thomas Heller continued to maintain and enhance the ctypes module.
ctypes now supports a ~ctypes.c_bool datatype that represents the C99 bool type. (Contributed by David Remahl; 1649190.)
The ctypes string, buffer and array types have improved support for extended slicing syntax, where various combinations of (start, stop, step) are supplied. (Implemented by Thomas Wouters.)
All ctypes data types now support ~ctypes._CData.from_buffer and ~ctypes._CData.from_buffer_copy methods that create a ctypes instance based on a provided buffer object. ~ctypes._CData.from_buffer_copy copies the contents of the object, while ~ctypes._CData.from_buffer will share the same memory area.
A new calling convention tells ctypes to clear the errno or Win32 LastError variables at the outset of each wrapped call. (Implemented by Thomas Heller; 1798.)
You can now retrieve the Unix errno variable after a function call. When creating a wrapped function, you can supply use_errno=True as a keyword parameter to the DLL function and then call the module-level methods ~ctypes.set_errno and ~ctypes.get_errno to set and retrieve the error value.
The Win32 LastError variable is similarly supported by the DLL, ~ctypes.OleDLL, and ~ctypes.WinDLL functions. You supply use_last_error=True as a keyword parameter and then call the module-level methods ~ctypes.set_last_error and ~ctypes.get_last_error.
The ~ctypes.byref function, used to retrieve a pointer to a ctypes instance, now has an optional offset parameter that is a byte count that will be added to the returned pointer.
Improved SSL Support
Bill Janssen made extensive improvements to Python 2.6's support for the Secure Sockets Layer by adding a new module, ssl, that's built atop the OpenSSL library. This new module provides more control over the protocol negotiated, the X.509 certificates used, and has better support for writing SSL servers (as opposed to clients) in Python. The existing SSL support in the socket module hasn't been removed and continues to work, though it will be removed in Python 3.0.
To use the new module, you must first create a TCP connection in the usual way and then pass it to the !ssl.wrap_socket function. It's possible to specify whether a certificate is required, and to obtain certificate info by calling the ~ssl.SSLSocket.getpeercert method.
The documentation for the ssl module.
Deprecations and Removals
-
String exceptions have been removed. Attempting to use them raises a
TypeError. -
Changes to the
Exceptioninterface as dictated by352continue to be made. For 2.6, the!messageattribute is being deprecated in favor of the~BaseException.argsattribute. -
(3.0-warning mode) Python 3.0 will feature a reorganized standard library that will drop many outdated modules and rename others. Python 2.6 running in 3.0-warning mode will warn about these modules when they are imported.
The list of deprecated modules is:
!audiodev,!bgenlocations,!buildtools,!bundlebuilder,!Canvas,!compiler,!dircache,!dl,!fpformat,!gensuitemodule,!ihooks,!imageop,!imgfile,!linuxaudiodev,!mhlib,!mimetools,!multifile,!new,!pure,!statvfs,!sunaudiodev,!test.testall, and!toaiff. -
The
!gopherlibmodule has been removed. -
The
!MimeWritermodule and!mimifymodule have been deprecated; use theemailpackage instead. -
The
!md5module has been deprecated; use thehashlibmodule instead. -
The
!posixfilemodule has been deprecated;fcntl.lockfprovides better locking. -
The
!popen2module has been deprecated; use thesubprocessmodule. -
The
!rgbimgmodule has been removed. -
The
!setsmodule has been deprecated; it's better to use the built-insetandfrozensettypes. -
The
!shamodule has been deprecated; use thehashlibmodule instead.
Build and C API Changes
Changes to Python's build process and to the C API include:
-
Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of
!memmoveand!strerror, which are in the C89 standard library. -
Python 2.6 can be built with Microsoft Visual Studio 2008 (version 9.0), and this is the new default compiler. See the
PCbuilddirectory for the build files. (Implemented by Christian Heimes.) -
On Mac OS X, Python 2.6 can be compiled as a 4-way universal build. The
configurescript can take a!--with-universal-archs=[32-bit|64-bit|all]switch, controlling whether the binaries are built for 32-bit architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both. (Contributed by Ronald Oussoren.) -
A new function added in Python 2.6.6,
!PySys_SetArgvEx, sets the value ofsys.argvand can optionally updatesys.pathto include the directory containing the script named bysys.argv[0]depending on the value of an updatepath parameter.This function was added to close a security hole for applications that embed Python. The old function,
!PySys_SetArgv, would always updatesys.path, and sometimes it would add the current directory. This meant that, if you ran an application embedding Python in a directory controlled by someone else, attackers could put a Trojan-horse module in the directory (say, a file namedos.py) that your application would then import and run.If you maintain a C/C++ application that embeds Python, check whether you're calling
!PySys_SetArgvand carefully consider whether the application should be using!PySys_SetArgvExwith updatepath set to false. Note that using this function will break compatibility with Python versions 2.6.5 and earlier; if you have to continue working with earlier versions, you can leave the call to!PySys_SetArgvalone and callPyRun_SimpleString("sys.path.pop(0)\n")afterwards to discard the firstsys.pathcomponent.Security issue reported as
2008-5983; discussed in50003, and fixed by Antoine Pitrou. -
The BerkeleyDB module now has a C API object, available as
bsddb.db.api. This object can be used by other C extensions that wish to use the!bsddbmodule for their own purposes. (Contributed by Duncan Grisby.) -
The new buffer interface, previously described in the PEP 3118 section, adds
PyObject_GetBufferandPyBuffer_Release, as well as a few other functions. -
Python's use of the C stdio library is now thread-safe, or at least as thread-safe as the underlying library is. A long-standing potential bug occurred if one thread closed a file object while another thread was reading from or writing to the object. In 2.6 file objects have a reference count, manipulated by the
!PyFile_IncUseCountand!PyFile_DecUseCountfunctions. File objects can't be closed unless the reference count is zero.!PyFile_IncUseCountshould be called while the GIL is still held, before carrying out an I/O operation using theFILE *pointer, and!PyFile_DecUseCountshould be called immediately after the GIL is re-acquired. (Contributed by Antoine Pitrou and Gregory P. Smith.) -
Importing modules simultaneously in two different threads no longer deadlocks; it will now raise an
ImportError. A new API function,!PyImport_ImportModuleNoBlock, will look for a module insys.modulesfirst, then try to import it after acquiring an import lock. If the import lock is held by another thread, anImportErroris raised. (Contributed by Christian Heimes.) -
Several functions return information about the platform's floating-point support.
PyFloat_GetMaxreturns the maximum representable floating-point value, andPyFloat_GetMinreturns the minimum positive value.PyFloat_GetInforeturns an object containing more information from thefloat.hfile, such as"mant_dig"(number of digits in the mantissa),"epsilon"(smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes;1534.) -
C functions and methods that use
PyComplex_AsCComplexwill now accept arguments that have a~object.__complex__method. In particular, the functions in thecmathmodule will now accept objects with this method. This is a backport of a Python 3.0 change. (Contributed by Mark Dickinson;1675423.) -
Python's C API now includes two functions for case-insensitive string comparisons,
PyOS_stricmp(char*, char*)andPyOS_strnicmp(char*, char*, Py_ssize_t). (Contributed by Christian Heimes;1635.) -
Many C extensions define their own little macro for adding integers and strings to the module's dictionary in the
init*function. Python 2.6 finally defines standard macros for adding values to a module,PyModule_AddStringMacroandPyModule_AddIntMacro(). (Contributed by Christian Heimes.) -
Some macros were renamed in both 3.0 and 2.6 to make it clearer that they are macros, not functions.
!Py_Size()becamePy_SIZE(),!Py_Type()becamePy_TYPE(), and!Py_Refcnt()becamePy_REFCNT(). The mixed-case macros are still available in Python 2.6 for backward compatibility. (1629) -
Distutils now places C extensions it builds in a different directory when running on a debug version of Python. (Contributed by Collin Winter;
1530959.) -
Several basic data types, such as integers and strings, maintain internal free lists of objects that can be re-used. The data structures for these free lists now follow a naming convention: the variable is always named
free_list, the counter is always namednumfree, and a macroPy<typename>_MAXFREELISTis always defined. -
A new Makefile target, "make patchcheck", prepares the Python source tree for making a patch: it fixes trailing whitespace in all modified
.pyfiles, checks whether the documentation has been changed, and reports whether theMisc/ACKSandMisc/NEWSfiles have been updated. (Contributed by Brett Cannon.)Another new target, "make profile-opt", compiles a Python binary using GCC's profile-guided optimization. It compiles Python with profiling enabled, runs the test suite to obtain a set of profiling results, and then compiles using these results for optimization. (Contributed by Gregory P. Smith.)
Port-Specific Changes: Windows
-
The support for Windows 95, 98, ME and NT4 has been dropped. Python 2.6 requires at least Windows 2000 SP4.
-
The new default compiler on Windows is Visual Studio 2008 (version 9.0). The build directories for Visual Studio 2003 (version 7.1) and 2005 (version 8.0) were moved into the PC/ directory. The new
PCbuilddirectory supports cross compilation for X64, debug builds and Profile Guided Optimization (PGO). PGO builds are roughly 10% faster than normal builds. (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and Martin von Löwis.) -
The
msvcrtmodule now supports both the normal and wide char variants of the console I/O API. The~msvcrt.getwchfunction reads a keypress and returns a Unicode value, as does the~msvcrt.getwchefunction. The~msvcrt.putwchfunction takes a Unicode character and writes it to the console. (Contributed by Christian Heimes.) -
os.path.expandvarswill now expand environment variables in the form "%var%", and "~user" will be expanded into the user's home directory path. (Contributed by Josiah Carlson;957650.) -
The
socketmodule's socket objects now have an~socket.socket.ioctlmethod that provides a limited interface to the!WSAIoctlsystem interface. -
The
_winreg <winreg>module now has a function,~winreg.ExpandEnvironmentStrings, that expands environment variable references such as%NAME%in an input string. The handle objects provided by this module now support the context protocol, so they can be used inwithstatements. (Contributed by Christian Heimes.)_winreg <winreg>also has better support for x64 systems, exposing the~winreg.DisableReflectionKey,~winreg.EnableReflectionKey, and~winreg.QueryReflectionKeyfunctions, which enable and disable registry reflection for 32-bit processes running on 64-bit systems. (1753245) -
The
!msilibmodule's!Recordobject gained!GetIntegerand!GetStringmethods that return field values as an integer or a string. (Contributed by Floris Bruynooghe;2125.)
Port-Specific Changes: Mac OS X
- When compiling a framework build of Python, you can now specify the framework name to be used by providing the
!--with-framework-name=option to theconfigurescript. - The
!macfsmodule has been removed. This in turn required the!macostools.touchedfunction to be removed because it depended on the!macfsmodule. (1490190) - Many other Mac OS modules have been deprecated and will be removed in Python 3.0:
!_builtinSuites,!aepack,!aetools,!aetypes,!applesingle,!appletrawmain,!appletrunner,!argvemulator,!Audio_mac,!autoGIL,!Carbon,!cfmfile,!CodeWarrior,!ColorPicker,!EasyDialogs,!Explorer,!Finder,!FrameWork,!findertools,!ic,!icglue,!icopen,!macerrors,!MacOS,!macfs,!macostools,!macresource,!MiniAEFrame,!Nav,!Netscape,!OSATerminology,!pimp,!PixMapWrapper,!StdSuites,!SystemEvents,!Terminal, and!terminalcommand.
Port-Specific Changes: IRIX
A number of old IRIX-specific modules were deprecated and will be removed in Python 3.0: !al and !AL, !cd, !cddb, !cdplayer, !CL and !cl, !DEVICE, !ERRNO, !FILE, !FL and !fl, !flp, !fm, !GET, !GLWS, !GL and !gl, !IN, !IOCTL, !jpeg, !panelparser, !readcd, !SV and !sv, !torgb, !videoreader, and !WAIT.
Porting to Python 2.6
This section lists previously described changes and other bugfixes that may require changes to your code:
-
Classes that aren't supposed to be hashable should set
__hash__ = Nonein their definitions to indicate the fact. -
String exceptions have been removed. Attempting to use them raises a
TypeError. -
The
!__init__method ofcollections.dequenow clears any existing contents of the deque before adding elements from the iterable. This change makes the behavior matchlist.__init__(). -
object.__init__previously accepted arbitrary arguments and keyword arguments, ignoring them. In Python 2.6, this is no longer allowed and will result in aTypeError. This will affect!__init__methods that end up calling the corresponding method onobject(perhaps through usingsuper). See1683368for discussion. -
The
~decimal.Decimalconstructor now accepts leading and trailing whitespace when passed a string. Previously it would raise an~decimal.InvalidOperationexception. On the other hand, the~decimal.Context.create_decimalmethod of~decimal.Contextobjects now explicitly disallows extra whitespace, raising a!ConversionSyntaxexception. -
Due to an implementation accident, if you passed a file path to the built-in
__import__function, it would actually import the specified file. This was never intended to work, however, and the implementation now explicitly checks for this case and raises anImportError. -
C API: the
PyImport_ImportandPyImport_ImportModulefunctions now default to absolute imports, not relative imports. This will affect C extensions that import other modules. -
C API: extension data types that shouldn't be hashable should define their
tp_hashslot toPyObject_HashNotImplemented. -
The
socketmodule exceptionsocket.errornow inherits fromIOError. Previously it wasn't a subclass of!StandardErrorbut now it is, throughIOError. (Implemented by Gregory P. Smith;1706815.) -
The
xmlrpclib <xmlrpc.client>module no longer automatically convertsdatetime.dateanddatetime.timeto thexmlrpclib.DateTime <xmlrpc.client.DateTime>type; the conversion semantics were not necessarily correct for all applications. Code using!xmlrpclibshould convert~datetime.dateand~datetime.timeinstances. (1330538) -
(3.0-warning mode) The
Exceptionclass now warns when accessed using slicing or index access; havingExceptionbehave like a tuple is being phased out. -
(3.0-warning mode) inequality comparisons between two dictionaries or two objects that don't implement comparison methods are reported as warnings.
dict1 == dict2still works, butdict1 < dict2is being phased out.Comparisons between cells, which are an implementation detail of Python's scoping rules, also cause warnings because such comparisons are forbidden entirely in 3.0.
For applications that embed Python:
- The
!PySys_SetArgvExfunction was added in Python 2.6.6, letting applications close a security hole when the existing!PySys_SetArgvfunction was used. Check whether you're calling!PySys_SetArgvand carefully consider whether the application should be using!PySys_SetArgvExwith updatepath set to false.
Acknowledgements
What's New in Python 2.7
This article explains the new features in Python 2.7. Python 2.7 was released on July 3, 2010.
Numeric handling has been improved in many ways, for both floating-point numbers and for the ~decimal.Decimal class. There are some useful additions to the standard library, such as a greatly enhanced unittest module, the argparse module for parsing command-line options, convenient ~collections.OrderedDict and ~collections.Counter classes in the collections module, and many other improvements.
Python 2.7 is planned to be the last of the 2.x releases, so we worked on making it a good release for the long term. To help with porting to Python 3, several new features from the Python 3.x series have been included in 2.7.
This article doesn't attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.7 at https://docs.python.org. If you want to understand the rationale for the design and implementation, refer to the PEP for a particular new feature or the issue on https://bugs.python.org in which a change was discussed. Whenever possible, "What's New in Python" links to the bug/patch item for each change.
The Future for Python 2.x
Python 2.7 is the last major release in the 2.x series, as the Python maintainers have shifted the focus of their new feature development efforts to the Python 3.x series. This means that while Python 2 continues to receive bug fixes, and to be updated to build correctly on new hardware and versions of supported operated systems, there will be no new full feature releases for the language or standard library.
However, while there is a large common subset between Python 2.7 and Python 3, and many of the changes involved in migrating to that common subset, or directly to Python 3, can be safely automated, some other changes (notably those associated with Unicode handling) may require careful consideration, and preferably robust automated regression test suites, to migrate effectively.
This means that Python 2.7 will remain in place for a long time, providing a stable and supported base platform for production systems that have not yet been ported to Python 3. The full expected lifecycle of the Python 2.7 series is detailed in 373.
Some key consequences of the long-term significance of 2.7 are:
- As noted above, the 2.7 release has a much longer period of maintenance when compared to earlier 2.x versions. Python 2.7 is currently expected to remain supported by the core development team (receiving security updates and other bug fixes) until at least 2020 (10 years after its initial release, compared to the more typical support period of 18--24 months).
- As the Python 2.7 standard library ages, making effective use of the Python Package Index (either directly or via a redistributor) becomes more important for Python 2 users. In addition to a wide variety of third party packages for various tasks, the available packages include backports of new modules and features from the Python 3 standard library that are compatible with Python 2, as well as various tools and libraries that can make it easier to migrate to Python 3. The Python Packaging User Guide provides guidance on downloading and installing software from the Python Package Index.
- While the preferred approach to enhancing Python 2 is now the publication of new packages on the Python Package Index, this approach doesn't necessarily work in all cases, especially those related to network security. In exceptional cases that cannot be handled adequately by publishing new or updated packages on PyPI, the Python Enhancement Proposal process may be used to make the case for adding new features directly to the Python 2 standard library. Any such additions, and the maintenance releases where they were added, will be noted in the
py27-maintenance-enhancementssection below.
For projects wishing to migrate from Python 2 to Python 3, or for library and framework developers wishing to support users on both Python 2 and Python 3, there are a variety of tools and guides available to help decide on a suitable approach and manage some of the technical details involved. The recommended starting point is the pyporting-howto HOWTO guide.
Changes to the Handling of Deprecation Warnings
For Python 2.7, a policy decision was made to silence warnings only of interest to developers by default. DeprecationWarning and its descendants are now ignored unless otherwise requested, preventing users from seeing warnings triggered by an application. This change was also made in the branch that became Python 3.2. (Discussed on stdlib-sig and carried out in 7319.)
In previous releases, DeprecationWarning messages were enabled by default, providing Python developers with a clear indication of where their code may break in a future major version of Python.
However, there are increasingly many users of Python-based applications who are not directly involved in the development of those applications. DeprecationWarning messages are irrelevant to such users, making them worry about an application that's actually working correctly and burdening application developers with responding to these concerns.
You can re-enable display of DeprecationWarning messages by running Python with the -Wdefault <-W> (short form: -Wd <-W>) switch, or by setting the PYTHONWARNINGS environment variable to "default" (or "d") before running Python. Python code can also re-enable them by calling warnings.simplefilter('default').
The unittest module also automatically reenables deprecation warnings when running tests.
Python 3.1 Features
Much as Python 2.6 incorporated features from Python 3.0, version 2.7 incorporates some of the new features in Python 3.1. The 2.x series continues to provide tools for migrating to the 3.x series.
A partial list of 3.1 features that were backported to 2.7:
- The syntax for set literals (
{1,2,3}is a mutable set). - Dictionary and set comprehensions (
{i: i*2 for i in range(3)}). - Multiple context managers in a single
withstatement. - A new version of the
iolibrary, rewritten in C for performance. - The ordered-dictionary type described in
pep-0372. - The new
","format specifier described inpep-0378. - The
memoryviewobject. - A small subset of the
importlibmodule, described below. - The
reprof a floatxis shorter in many cases: it's now based on the shortest decimal string that's guaranteed to round back tox. As in previous versions of Python, it's guaranteed thatfloat(repr(x))recoversx. - Float-to-string and string-to-float conversions are correctly rounded. The
roundfunction is also now correctly rounded. - The
PyCapsuletype, used to provide a C API for extension modules. - The
PyLong_AsLongAndOverflowC API function.
Other new Python3-mode warnings include:
!operator.isCallableand!operator.sequenceIncludes, which are not supported in 3.x, now trigger warnings.- The
!-3switch now automatically enables the!-Qwarnswitch that causes warnings about using classic division with integers and long integers.
PEP 372: Adding an Ordered Dictionary to collections
Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors have written alternative implementations that remember the order that the keys were originally inserted. Based on the experiences from those implementations, 2.7 introduces a new ~collections.OrderedDict class in the collections module.
The ~collections.OrderedDict API provides the same interface as regular dictionaries but iterates over keys and values in a guaranteed order depending on when a key was first inserted:
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
... ('second', 2),
... ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
If a new entry overwrites an existing entry, the original insertion position is left unchanged:
>>> d['second'] = 4
>>> d.items()
[('first', 1), ('second', 4), ('third', 3)]
Deleting an entry and reinserting it will move it to the end:
>>> del d['second']
>>> d['second'] = 5
>>> d.items()
[('first', 1), ('third', 3), ('second', 5)]
The ~collections.OrderedDict.popitem method has an optional last argument that defaults to True. If last is true, the most recently added key is returned and removed; if it's false, the oldest key is selected:
>>> od = OrderedDict([(x,0) for x in range(20)])
>>> od.popitem()
(19, 0)
>>> od.popitem()
(18, 0)
>>> od.popitem(last=False)
(0, 0)
>>> od.popitem(last=False)
(1, 0)
Comparing two ordered dictionaries checks both the keys and values, and requires that the insertion order was the same:
>>> od1 = OrderedDict([('first', 1),
... ('second', 2),
... ('third', 3)])
>>> od2 = OrderedDict([('third', 3),
... ('first', 1),
... ('second', 2)])
>>> od1 == od2
False
>>> # Move 'third' key to the end
>>> del od2['third']; od2['third'] = 3
>>> od1 == od2
True
Comparing an ~collections.OrderedDict with a regular dictionary ignores the insertion order and just compares the keys and values.
How does the ~collections.OrderedDict work? It maintains a doubly linked list of keys, appending new keys to the list as they're inserted. A secondary dictionary maps keys to their corresponding list node, so deletion doesn't have to traverse the entire linked list and therefore remains O(1).
The standard library now supports use of ordered dictionaries in several modules.
- The
ConfigParser <configparser>module uses them by default, meaning that configuration files can now be read, modified, and then written back in their original order. - The
~collections.somenamedtuple._asdictmethod forcollections.namedtuplenow returns an ordered dictionary with the values appearing in the same order as the underlying tuple indices. - The
jsonmodule's~json.JSONDecoderclass constructor was extended with an object_pairs_hook parameter to allowOrderedDictinstances to be built by the decoder. Support was also added for third-party tools like PyYAML.
372 - Adding an ordered dictionary to collections
PEP written by Armin Ronacher and Raymond Hettinger; implemented by Raymond Hettinger.
PEP 378: Format Specifier for Thousands Separator
To make program output more readable, it can be useful to add separators to large numbers, rendering them as 18,446,744,073,709,551,616 instead of 18446744073709551616.
The fully general solution for doing this is the locale module, which can use different separators ("," in North America, "." in Europe) and different grouping sizes, but locale is complicated to use and unsuitable for multi-threaded applications where different threads are producing output for different locales.
Therefore, a simple comma-grouping mechanism has been added to the mini-language used by the str.format method. When formatting a floating-point number, simply include a comma between the width and the precision:
>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
When formatting an integer, include the comma after the width:
>>> '{:20,d}'.format(18446744073709551616) '18,446,744,073,709,551,616'
This mechanism is not adaptable at all; commas are always used as the separator and the grouping is always into three-digit groups. The comma-formatting mechanism isn't as general as the locale module, but it's easier to use.
378 - Format Specifier for Thousands Separator
PEP written by Raymond Hettinger; implemented by Eric Smith.
PEP 389: The argparse Module for Parsing Command Lines
The argparse module for parsing command-line arguments was added as a more powerful replacement for the optparse module.
This means Python now supports three different modules for parsing command-line arguments: getopt, optparse, and argparse. The getopt module closely resembles the C library's !getopt function, so it remains useful if you're writing a Python prototype that will eventually be rewritten in C. optparse becomes redundant, but there are no plans to remove it because there are many scripts still using it, and there's no automated way to update these scripts. (Making the argparse API consistent with optparse's interface was discussed but rejected as too messy and difficult.)
In short, if you're writing a new script and don't need to worry about compatibility with earlier versions of Python, use argparse instead of optparse.
Here's an example:
import argparse
parser = argparse.ArgumentParser(description='Command-line example.')
# Add optional switches
parser.add_argument('-v', action='store_true', dest='is_verbose',
help='produce verbose output')
parser.add_argument('-o', action='store', dest='output',
metavar='FILE',
help='direct output to FILE instead of stdout')
parser.add_argument('-C', action='store', type=int, dest='context',
metavar='NUM', default=0,
help='display NUM lines of added context')
# Allow any number of additional arguments.
parser.add_argument(nargs='*', action='store', dest='inputs',
help='input filenames (default is stdin)')
args = parser.parse_args()
print args.__dict__
Unless you override it, !-h and !--help switches are automatically added, and produce neatly formatted output:
-> ./python.exe argparse-example.py --help
usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Command-line example.
positional arguments:
inputs input filenames (default is stdin)
optional arguments:
-h, --help show this help message and exit
-v produce verbose output
-o FILE direct output to FILE instead of stdout
-C NUM display NUM lines of added context
As with optparse, the command-line switches and arguments are returned as an object with attributes named by the dest parameters:
-> ./python.exe argparse-example.py -v
{'output': None,
'is_verbose': True,
'context': 0,
'inputs': []}
-> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
{'output': '/tmp/output',
'is_verbose': True,
'context': 4,
'inputs': ['file1', 'file2']}
argparse has much fancier validation than optparse; you can specify an exact number of arguments as an integer, 0 or more arguments by passing '*', 1 or more by passing '+', or an optional argument with '?'. A top-level parser can contain sub-parsers to define subcommands that have different sets of switches, as in svn commit, svn checkout, etc. You can specify an argument's type as ~argparse.FileType, which will automatically open files for you and understands that '-' means standard input or output.
argparse documentation
The documentation page of the argparse module.
upgrading-optparse-code
Part of the Python documentation, describing how to convert code that uses optparse.
389 - argparse - New Command Line Parsing Module
PEP written and implemented by Steven Bethard.
PEP 391: Dictionary-Based Configuration For Logging
The logging module is very flexible; applications can define a tree of logging subsystems, and each logger in this tree can filter out certain messages, format them differently, and direct messages to a varying number of handlers.
All this flexibility can require a lot of configuration. You can write Python statements to create objects and set their properties, but a complex set-up requires verbose but boring code. logging also supports a ~logging.config.fileConfig function that parses a file, but the file format doesn't support configuring filters, and it's messier to generate programmatically.
Python 2.7 adds a ~logging.config.dictConfig function that uses a dictionary to configure logging. There are many ways to produce a dictionary from different sources: construct one with code; parse a file containing JSON; or use a YAML parsing library if one is installed. For more information see logging-config-api.
The following example configures two loggers, the root logger and a logger named "network". Messages sent to the root logger will be sent to the system log using the syslog protocol, and messages to the "network" logger will be written to a network.log file that will be rotated once the log reaches 1MB.
import logging
import logging.config
configdict = {
'version': 1, # Configuration schema in use; must be 1 for now
'formatters': {
'standard': {
'format': ('%(asctime)s %(name)-15s '
'%(levelname)-8s %(message)s')}},
'handlers': {'netlog': {'backupCount': 10,
'class': 'logging.handlers.RotatingFileHandler',
'filename': '/logs/network.log',
'formatter': 'standard',
'level': 'INFO',
'maxBytes': 1000000},
'syslog': {'class': 'logging.handlers.SysLogHandler',
'formatter': 'standard',
'level': 'ERROR'}},
# Specify all the subordinate loggers
'loggers': {
'network': {
'handlers': ['netlog']
}
},
# Specify properties of the root logger
'root': {
'handlers': ['syslog']
},
}
# Set up configuration
logging.config.dictConfig(configdict)
# As an example, log two error messages
logger = logging.getLogger('/')
logger.error('Database not found')
netlogger = logging.getLogger('network')
netlogger.error('Connection failed')
Three smaller enhancements to the logging module, all implemented by Vinay Sajip, are:
- The
~logging.handlers.SysLogHandlerclass now supports syslogging over TCP. The constructor has a socktype parameter giving the type of socket to use, eithersocket.SOCK_DGRAMfor UDP orsocket.SOCK_STREAMfor TCP. The default protocol remains UDP. ~logging.Loggerinstances gained a~logging.Logger.getChildmethod that retrieves a descendant logger using a relative path. For example, once you retrieve a logger by doinglog = getLogger('app'), callinglog.getChild('network.listen')is equivalent togetLogger('app.network.listen').- The
~logging.LoggerAdapterclass gained an~logging.Logger.isEnabledFormethod that takes a level and returns whether the underlying logger would process a message of that level of importance.
391 - Dictionary-Based Configuration For Logging
PEP written and implemented by Vinay Sajip.
PEP 3106: Dictionary Views
The dictionary methods ~dict.keys, ~dict.values, and ~dict.items are different in Python 3.x. They return an object called a view instead of a fully materialized list.
It's not possible to change the return values of ~dict.keys, ~dict.values, and ~dict.items in Python 2.7 because too much code would break. Instead the 3.x versions were added under the new names !viewkeys, !viewvalues, and !viewitems.
>>> d = dict((i*10, chr(65+i)) for i in range(26))
>>> d
{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
>>> d.viewkeys()
dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
Views can be iterated over, but the key and item views also behave like sets. The & operator performs intersection, and | performs a union:
>>> d1 = dict((i*10, chr(65+i)) for i in range(26))
>>> d2 = dict((i**.5, i) for i in range(1000))
>>> d1.viewkeys() & d2.viewkeys()
set([0.0, 10.0, 20.0, 30.0])
>>> d1.viewkeys() | range(0, 30)
set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
The view keeps track of the dictionary and its contents change as the dictionary is modified:
>>> vk = d.viewkeys()
>>> vk
dict_keys([0, 130, 10, ..., 250])
>>> d[260] = '&'
>>> vk
dict_keys([0, 130, 260, 10, ..., 250])
However, note that you can't add or remove keys while you're iterating over the view:
>>> for k in vk:
... d[k*2] = k
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
You can use the view methods in Python 2.x code, and the 2to3 converter will change them to the standard ~dict.keys, ~dict.values, and ~dict.items methods.
3106 - Revamping dict.keys(), .values() and .items()
PEP written by Guido van Rossum. Backported to 2.7 by Alexandre Vassalotti; 1967.
PEP 3137: The memoryview Object
The memoryview object provides a view of another object's memory content that matches the bytes type's interface.
>>> import string >>> m = memoryview(string.letters) >>> m <memory at 0x37f850> >>> len(m) # Returns length of underlying object 52 >>> m[0], m[25], m[26] # Indexing returns one byte ('a', 'z', 'A') >>> m2 = m[0:26] # Slicing returns another memoryview >>> m2 <memory at 0x37f080>
The content of the view can be converted to a string of bytes or a list of integers:
>>> m2.tobytes() 'abcdefghijklmnopqrstuvwxyz' >>> m2.tolist() [97, 98, 99, 100, 101, 102, 103, ... 121, 122] >>>
memoryview objects allow modifying the underlying object if it's a mutable object.
>>> m2[0] = 75 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot modify read-only memory >>> b = bytearray(string.letters) # Creating a mutable object >>> b bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') >>> mb = memoryview(b) >>> mb[0] = '*' # Assign to view, changing the bytearray. >>> b[0:5] # The bytearray has been changed. bytearray(b'*bcde') >>>
3137 - Immutable Bytes and Mutable Buffer
PEP written by Guido van Rossum. Implemented by Travis Oliphant, Antoine Pitrou and others. Backported to 2.7 by Antoine Pitrou; 2396.
Other Language Changes
Some smaller changes made to the core Python language are:
-
The syntax for set literals has been backported from Python 3.x. Curly brackets are used to surround the contents of the resulting mutable set; set literals are distinguished from dictionaries by not containing colons and values.
{}continues to represent an empty dictionary; useset()for an empty set.>>> {1, 2, 3, 4, 5} set([1, 2, 3, 4, 5]) >>> set() # empty set set([]) >>> {} # empty dict {}
Backported by Alexandre Vassalotti;
2335. -
Dictionary and set comprehensions are another feature backported from 3.x, generalizing list/generator comprehensions to use the literal syntax for sets and dictionaries.
>>> {x: x*x for x in range(6)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} >>> {('a'*x) for x in range(6)} set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
Backported by Alexandre Vassalotti;
2333. -
The
withstatement can now use multiple context managers in one statement. Context managers are processed from left to right and each one is treated as beginning a new!withstatement. This means that:with A() as a, B() as b: ... suite of statements ...is equivalent to:
with A() as a: with B() as b: ... suite of statements ...The
!contextlib.nestedfunction provides a very similar function, so it's no longer necessary and has been deprecated.(Proposed in https://codereview.appspot.com/53094; implemented by Georg Brandl.)
-
Conversions between floating-point numbers and strings are now correctly rounded on most platforms. These conversions occur in many different places:
stron floats and complex numbers; thefloatandcomplexconstructors; numeric formatting; serializing and deserializing floats and complex numbers using themarshal,pickleandjsonmodules; parsing of float and imaginary literals in Python code; and~decimal.Decimal-to-float conversion.Related to this, the
reprof a floating-point number x now returns a result based on the shortest decimal string that's guaranteed to round back to x under correct rounding (with round-half-to-even rounding mode). Previously it gave a string based on rounding x to 17 decimal digits.The rounding library responsible for this improvement works on Windows and on Unix platforms using the gcc, icc, or suncc compilers. There may be a small number of platforms where correct operation of this code cannot be guaranteed, so the code is not used on such systems. You can find out which code is being used by checking
sys.float_repr_style, which will beshortif the new code is in use andlegacyif it isn't.Implemented by Eric Smith and Mark Dickinson, using David Gay's
dtoa.clibrary;7117. -
Conversions from long integers and regular integers to floating point now round differently, returning the floating-point number closest to the number. This doesn't matter for small integers that can be converted exactly, but for large numbers that will unavoidably lose precision, Python 2.7 now approximates more closely. For example, Python 2.6 computed the following:
>>> n = 295147905179352891391 >>> float(n) 2.9514790517935283e+20 >>> n - long(float(n)) 65535LPython 2.7's floating-point result is larger, but much closer to the true value:
>>> n = 295147905179352891391 >>> float(n) 2.9514790517935289e+20 >>> n - long(float(n)) -1L(Implemented by Mark Dickinson;
3166.)Integer division is also more accurate in its rounding behaviours. (Also implemented by Mark Dickinson;
1811.) -
Implicit coercion for complex numbers has been removed; the interpreter will no longer ever attempt to call a
!__coerce__method on complex objects. (Removed by Meador Inge and Mark Dickinson;5211.) -
The
str.formatmethod now supports automatic numbering of the replacement fields. This makes usingstr.formatmore closely resemble using%sformatting:>>> '{}:{}:{}'.format(2009, 04, 'Sunday') '2009:4:Sunday' >>> '{}:{}:{day}'.format(2009, 4, day='Sunday') '2009:4:Sunday'The auto-numbering takes the fields from left to right, so the first
{...}specifier will use the first argument tostr.format, the next specifier will use the next argument, and so on. You can't mix auto-numbering and explicit numbering -- either number all of your specifier fields or none of them -- but you can mix auto-numbering and named fields, as in the second example above. (Contributed by Eric Smith;5237.)Complex numbers now correctly support usage with
format, and default to being right-aligned. Specifying a precision or comma-separation applies to both the real and imaginary parts of the number, but a specified field width and alignment is applied to the whole of the resulting1.5+3joutput. (Contributed by Eric Smith;1588and7988.)The 'F' format code now always formats its output using uppercase characters, so it will now produce 'INF' and 'NAN'. (Contributed by Eric Smith;
3382.)A low-level change: the
object.__format__method now triggers aPendingDeprecationWarningif it's passed a format string, because the!__format__method forobjectconverts the object to a string representation and formats that. Previously the method silently applied the format string to the string representation, but that could hide mistakes in Python code. If you're supplying formatting information such as an alignment or precision, presumably you're expecting the formatting to be applied in some object-specific way. (Fixed by Eric Smith;7994.) -
The
intand!longtypes gained abit_lengthmethod that returns the number of bits necessary to represent its argument in binary:>>> n = 37 >>> bin(n) '0b100101' >>> n.bit_length() 6 >>> n = 2**123-1 >>> n.bit_length() 123 >>> (n+1).bit_length() 124(Contributed by Fredrik Johansson and Victor Stinner;
3439.) -
The
importstatement will no longer try an absolute import if a relative import (e.g.from .os import sep) fails. This fixes a bug, but could possibly break certain!importstatements that were only working by accident. (Fixed by Meador Inge;7902.) -
It's now possible for a subclass of the built-in
!unicodetype to override the!__unicode__method. (Implemented by Victor Stinner;1583863.) -
The
bytearraytype's~bytearray.translatemethod now acceptsNoneas its first argument. (Fixed by Georg Brandl;4759.) -
When using
classmethodandstaticmethodto wrap methods as class or static methods, the wrapper object now exposes the wrapped function as their~method.__func__attribute. (Contributed by Amaury Forgeot d'Arc, after a suggestion by George Sakkis;5982.) -
When a restricted set of attributes were set using
__slots__, deleting an unset attribute would not raiseAttributeErroras you would expect. Fixed by Benjamin Peterson;7604.) -
Two new encodings are now supported: "cp720", used primarily for Arabic text; and "cp858", a variant of CP 850 that adds the euro symbol. (CP720 contributed by Alexander Belchenko and Amaury Forgeot d'Arc in
1616979; CP858 contributed by Tim Hatch in8016.) -
The
!fileobject will now set the!filenameattribute on theIOErrorexception when trying to open a directory on POSIX platforms (noted by Jan Kaliszewski;4764), and now explicitly checks for and forbids writing to read-only file objects instead of trusting the C library to catch and report the error (fixed by Stefan Krah;5677). -
The Python tokenizer now translates line endings itself, so the
compilebuilt-in function now accepts code using any line-ending convention. Additionally, it no longer requires that the code end in a newline. -
Extra parentheses in function definitions are illegal in Python 3.x, meaning that you get a syntax error from
def f((x)): pass. In Python3-warning mode, Python 2.7 will now warn about this odd usage. (Noted by James Lingard;7362.) -
It's now possible to create weak references to old-style class objects. New-style classes were always weak-referenceable. (Fixed by Antoine Pitrou;
8268.) -
When a module object is garbage-collected, the module's dictionary is now only cleared if no one else is holding a reference to the dictionary (
7140).
Interpreter Changes
A new environment variable, PYTHONWARNINGS, allows controlling warnings. It should be set to a string containing warning settings, equivalent to those used with the -W switch, separated by commas. (Contributed by Brian Curtin; 7301.)
For example, the following setting will print warnings every time they occur, but turn warnings from the Cookie <http.cookies> module into an error. (The exact syntax for setting an environment variable varies across operating systems and shells.)
export PYTHONWARNINGS=all,error:::Cookie:0
Optimizations
Several performance enhancements have been added:
-
A new opcode was added to perform the initial setup for
withstatements, looking up the~object.__enter__and~object.__exit__methods. (Contributed by Benjamin Peterson.) -
The garbage collector now performs better for one common usage pattern: when many objects are being allocated without deallocating any of them. This would previously take quadratic time for garbage collection, but now the number of full garbage collections is reduced as the number of objects on the heap grows. The new logic only performs a full garbage collection pass when the middle generation has been collected 10 times and when the number of survivor objects from the middle generation exceeds 10% of the number of objects in the oldest generation. (Suggested by Martin von Löwis and implemented by Antoine Pitrou;
4074.) -
The garbage collector tries to avoid tracking simple containers which can't be part of a cycle. In Python 2.7, this is now true for tuples and dicts containing atomic types (such as ints, strings, etc.). Transitively, a dict containing tuples of atomic types won't be tracked either. This helps reduce the cost of each garbage collection by decreasing the number of objects to be considered and traversed by the collector. (Contributed by Antoine Pitrou;
4688.) -
Long integers are now stored internally either in base
2**15or in base2**30, the base being determined at build time. Previously, they were always stored in base2**15. Using base2**30gives significant performance improvements on 64-bit machines, but benchmark results on 32-bit machines have been mixed. Therefore, the default is to use base2**30on 64-bit machines and base2**15on 32-bit machines; on Unix, there's a new configure option!--enable-big-digitsthat can be used to override this default.Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there's a new structseq
!sys.long_infothat provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:>>> import sys >>> sys.long_info sys.long_info(bits_per_digit=30, sizeof_digit=4)(Contributed by Mark Dickinson;
4258.)Another set of changes made long objects a few bytes smaller: 2 bytes smaller on 32-bit systems and 6 bytes on 64-bit. (Contributed by Mark Dickinson;
5260.) -
The division algorithm for long integers has been made faster by tightening the inner loop, doing shifts instead of multiplications, and fixing an unnecessary extra iteration. Various benchmarks show speedups of between 50% and 150% for long integer divisions and modulo operations. (Contributed by Mark Dickinson;
5512.) Bitwise operations are also significantly faster (initial patch by Gregory Smith;1087418). -
The implementation of
%checks for the left-side operand being a Python string and special-cases it; this results in a 1--3% performance increase for applications that frequently use%with strings, such as templating libraries. (Implemented by Collin Winter;5176.) -
List comprehensions with an
ifcondition are compiled into faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey Yasskin;4715.) -
Converting an integer or long integer to a decimal string was made faster by special-casing base 10 instead of using a generalized conversion function that supports arbitrary bases. (Patch by Gawain Bolton;
6713.) -
The
!split,!replace,!rindex,!rpartition, and!rsplitmethods of string-like types (strings, Unicode strings, andbytearrayobjects) now use a fast reverse-search algorithm instead of a character-by-character scan. This is sometimes faster by a factor of 10. (Added by Florent Xicluna;7462and7622.) -
The
pickleand!cPicklemodules now automatically intern the strings used for attribute names, reducing memory usage of the objects resulting from unpickling. (Contributed by Jake McGuire;5084.) -
The
!cPicklemodule now special-cases dictionaries, nearly halving the time required to pickle them. (Contributed by Collin Winter;5670.)
New and Improved Modules
As in every release, Python's standard library received a number of enhancements and bug fixes. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the Subversion logs for all the details.
-
The
bdbmodule's base debugging class~bdb.Bdbgained a feature for skipping modules. The constructor now takes an iterable containing glob-style patterns such asdjango.*; the debugger will not step into stack frames from a module that matches one of these patterns. (Contributed by Maru Newby after a suggestion by Senthil Kumaran;5142.) -
The
binasciimodule now supports the buffer API, so it can be used withmemoryviewinstances and other similar buffer objects. (Backported from 3.x by Florent Xicluna;7703.) -
Updated module: the
!bsddbmodule has been updated from 4.7.2devel9 to version 4.8.4 of the pybsddb package. The new version features better Python 3.x compatibility, various bug fixes, and adds several new BerkeleyDB flags and methods. (Updated by Jesús Cea Avión;8156. The pybsddb changelog can be read at https://hg.jcea.es/pybsddb/file/tip/ChangeLog.) -
The
bz2module's~bz2.BZ2Filenow supports the context management protocol, so you can writewith bz2.BZ2File(...) as f:. (Contributed by Hagen Fürstenau;3860.) -
New class: the
~collections.Counterclass in thecollectionsmodule is useful for tallying data.~collections.Counterinstances behave mostly like dictionaries but return zero for missing keys instead of raising aKeyError:>>> from collections import Counter >>> c = Counter() >>> for letter in 'here is a sample of english text': ... c[letter] += 1 ... >>> c # doctest: +SKIP Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2, 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1, 'p': 1, 'r': 1, 'x': 1}) >>> c['e'] 5 >>> c['z'] 0
There are three additional
~collections.Countermethods.~collections.Counter.most_commonreturns the N most common elements and their counts.~collections.Counter.elementsreturns an iterator over the contained elements, repeating each element as many times as its count.~collections.Counter.subtracttakes an iterable and subtracts one for each element instead of adding; if the argument is a dictionary or anotherCounter, the counts are subtracted. :>>> c.most_common(5) [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)] >>> c.elements() -> 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ', 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i', 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's', 's', 's', 'r', 't', 't', 'x' >>> c['e'] 5 >>> c.subtract('very heavy on the letter e') >>> c['e'] # Count is now lower -1Contributed by Raymond Hettinger;
1696199.New class:
~collections.OrderedDictis described in the earlier sectionpep-0372.New method: The
~collections.dequedata type now has a~collections.deque.countmethod that returns the number of contained elements equal to the supplied argument x, and a~collections.deque.reversemethod that reverses the elements of the deque in-place.~collections.dequealso exposes its maximum length as the read-only~collections.deque.maxlenattribute. (Both features added by Raymond Hettinger.)The
~collections.namedtupleclass now has an optional rename parameter. If rename is true, field names that are invalid because they've been repeated or aren't legal Python identifiers will be renamed to legal names that are derived from the field's position within the list of fields:>>> from collections import namedtuple >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True) >>> T._fields ('field1', '_1', '_2', 'field2')
(Added by Raymond Hettinger;
1818.)Finally, the
~collections.abc.Mappingabstract base class now returnsNotImplementedif a mapping is compared to another type that isn't aMapping. (Fixed by Daniel Stutzbach;8729.) -
Constructors for the parsing classes in the
ConfigParser <configparser>module now take an allow_no_value parameter, defaulting to false; if true, options without values will be allowed. For example:>>> import ConfigParser, StringIO >>> sample_config = """ ... [mysqld] ... user = mysql ... pid-file = /var/run/mysqld/mysqld.pid ... skip-bdb ... """ >>> config = ConfigParser.RawConfigParser(allow_no_value=True) >>> config.readfp(StringIO.StringIO(sample_config)) >>> config.get('mysqld', 'user') 'mysql' >>> print config.get('mysqld', 'skip-bdb') None >>> print config.get('mysqld', 'unknown') Traceback (most recent call last): ... NoOptionError: No option 'unknown' in section: 'mysqld'(Contributed by Mats Kindahl;
7005.) -
Deprecated function:
!contextlib.nested, which allows handling more than one context manager with a singlewithstatement, has been deprecated, because the!withstatement now supports multiple context managers. -
The
cookielib <http.cookiejar>module now ignores cookies that have an invalid version field, one that doesn't contain an integer value. (Fixed by John J. Lee;3924.) -
The
copymodule's~copy.deepcopyfunction will now correctly copy bound instance methods. (Implemented by Robert Collins;1515.) -
The
ctypesmodule now always convertsNoneto a CNULLpointer for arguments declared as pointers. (Changed by Thomas Heller;4606.) The underlying libffi library has been updated to version 3.0.9, containing various fixes for different platforms. (Updated by Matthias Klose;8142.) -
New method: the
datetimemodule's~datetime.timedeltaclass gained a~datetime.timedelta.total_secondsmethod that returns the number of seconds in the duration. (Contributed by Brian Quinlan;5788.) -
New method: the
~decimal.Decimalclass gained a~decimal.Decimal.from_floatclass method that performs an exact conversion of a floating-point number to a!Decimal. This exact conversion strives for the closest decimal approximation to the floating-point representation's value; the resulting decimal value will therefore still include the inaccuracy, if any. For example,Decimal.from_float(0.1)returnsDecimal('0.1000000000000000055511151231257827021181583404541015625'). (Implemented by Raymond Hettinger;4796.)Comparing instances of
~decimal.Decimalwith floating-point numbers now produces sensible results based on the numeric values of the operands. Previously such comparisons would fall back to Python's default rules for comparing objects, which produced arbitrary results based on their type. Note that you still cannot combine!Decimaland floating point in other operations such as addition, since you should be explicitly choosing how to convert between float and!Decimal. (Fixed by Mark Dickinson;2531.)The constructor for
~decimal.Decimalnow accepts floating-point numbers (added by Raymond Hettinger;8257) and non-European Unicode characters such as Arabic-Indic digits (contributed by Mark Dickinson;6595).Most of the methods of the
~decimal.Contextclass now accept integers as well as~decimal.Decimalinstances; the only exceptions are the~decimal.Context.canonicaland~decimal.Context.is_canonicalmethods. (Patch by Juan José Conti;7633.)When using
~decimal.Decimalinstances with a string's~str.formatmethod, the default alignment was previously left-alignment. This has been changed to right-alignment, which is more sensible for numeric types. (Changed by Mark Dickinson;6857.)Comparisons involving a signaling NaN value (or
sNAN) now signal~decimal.InvalidOperationinstead of silently returning a true or false value depending on the comparison operator. Quiet NaN values (orNaN) are now hashable. (Fixed by Mark Dickinson;7279.) -
The
difflibmodule now produces output that is more compatible with moderndiff/patchtools through one small change, using a tab character instead of spaces as a separator in the header giving the filename. (Fixed by Anatoly Techtonik;7585.) -
The Distutils
sdistcommand now always regenerates theMANIFESTfile, since even if theMANIFEST.inorsetup.pyfiles haven't been modified, the user might have created some new files that should be included. (Fixed by Tarek Ziadé;8688.) -
The
doctestmodule's~doctest.IGNORE_EXCEPTION_DETAILflag will now ignore the name of the module containing the exception being tested. (Patch by Lennart Regebro;7490.) -
The
emailmodule's~email.message.Messageclass will now accept a Unicode-valued payload, automatically converting the payload to the encoding specified by!output_charset. (Added by R. David Murray;1368247.) -
The
~fractions.Fractionclass now accepts a single float or~decimal.Decimalinstance, or two rational numbers, as arguments to its constructor. (Implemented by Mark Dickinson; rationals added in5812, and float/decimal in8294.)Ordering comparisons (
<,<=,>,>=) between fractions and complex numbers now raise aTypeError. This fixes an oversight, making the~fractions.Fractionmatch the other numeric types. -
New class:
~ftplib.FTP_TLSin theftplibmodule provides secure FTP connections using TLS encapsulation of authentication as well as subsequent control and data transfers. (Contributed by Giampaolo Rodola;2054.)The
~ftplib.FTP.storbinarymethod for binary uploads can now restart uploads thanks to an added rest parameter (patch by Pablo Mouzo;6845.) -
New class decorator:
~functools.total_orderingin thefunctoolsmodule takes a class that defines an~object.__eq__method and one of~object.__lt__,~object.__le__,~object.__gt__, or~object.__ge__, and generates the missing comparison methods. Since the!__cmp__method is being deprecated in Python 3.x, this decorator makes it easier to define ordered classes. (Added by Raymond Hettinger;5479.)New function:
~functools.cmp_to_keywill take an old-style comparison function that expects two arguments and return a new callable that can be used as the key parameter to functions such assorted,minandmax, etc. The primary intended use is to help with making code compatible with Python 3.x. (Added by Raymond Hettinger.) -
New function: the
gcmodule's~gc.is_trackedreturns true if a given instance is tracked by the garbage collector, false otherwise. (Contributed by Antoine Pitrou;4688.) -
The
gzipmodule's~gzip.GzipFilenow supports the context management protocol, so you can writewith gzip.GzipFile(...) as f:(contributed by Hagen Fürstenau;3860), and it now implements theio.BufferedIOBaseABC, so you can wrap it withio.BufferedReaderfor faster processing (contributed by Nir Aides;7471). It's also now possible to override the modification time recorded in a gzipped file by providing an optional timestamp to the constructor. (Contributed by Jacques Frechet;4272.)Files in gzip format can be padded with trailing zero bytes; the
gzipmodule will now consume these trailing bytes. (Fixed by Tadek Pietraszek and Brian Curtin;2846.) -
New attribute: the
hashlibmodule now has an!algorithmsattribute containing a tuple naming the supported algorithms. In Python 2.7,hashlib.algorithmscontains('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'). (Contributed by Carl Chenet;7418.) -
The default
~http.client.HTTPResponseclass used by thehttplib <http>module now supports buffering, resulting in much faster reading of HTTP responses. (Contributed by Kristján Valur Jónsson;4879.)The
~http.client.HTTPConnectionand~http.client.HTTPSConnectionclasses now support a source_address parameter, a(host, port)2-tuple giving the source address that will be used for the connection. (Contributed by Eldon Ziegler;3972.) -
The
!ihooksmodule now supports relative imports. Note that!ihooksis an older module for customizing imports, superseded by the!imputilmodule added in Python 2.0. (Relative import support added by Neil Schemenauer.) -
The
imaplibmodule now supports IPv6 addresses. (Contributed by Derek Morr;1655.) -
New function: the
inspectmodule's~inspect.getcallargstakes a callable and its positional and keyword arguments, and figures out which of the callable's parameters will receive each argument, returning a dictionary mapping argument names to their values. For example:>>> from inspect import getcallargs >>> def f(a, b=1, *pos, **named): ... pass ... >>> getcallargs(f, 1, 2, 3) {'a': 1, 'b': 2, 'pos': (3,), 'named': {}} >>> getcallargs(f, a=2, x=4) {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}} >>> getcallargs(f) Traceback (most recent call last): ... TypeError: f() takes at least 1 argument (0 given)Contributed by George Sakkis;
3135. -
Updated module: The
iolibrary has been upgraded to the version shipped with Python 3.1. For 3.1, the I/O library was entirely rewritten in C and is 2 to 20 times faster depending on the task being performed. The original Python version was renamed to the!_pyiomodule.One minor resulting change: the
io.TextIOBaseclass now has an~io.TextIOBase.errorsattribute giving the error setting used for encoding and decoding errors (one of'strict','replace','ignore').The
io.FileIOclass now raises anOSErrorwhen passed an invalid file descriptor. (Implemented by Benjamin Peterson;4991.) The~io.IOBase.truncatemethod now preserves the file position; previously it would change the file position to the end of the new file. (Fixed by Pascal Chambon;6939.) -
New function:
itertools.compress(data, selectors)takes two iterators. Elements of data are returned if the corresponding value in selectors is true:itertools.compress('ABCDEF', [1,0,1,0,1,1]) => A, C, E, FNew function:
itertools.combinations_with_replacement(iter, r)returns all the possible r-length combinations of elements from the iterable iter. Unlike~itertools.combinations, individual elements can be repeated in the generated combinations:itertools.combinations_with_replacement('abc', 2) => ('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')Note that elements are treated as unique depending on their position in the input, not their actual values.
The
itertools.countfunction now has a step argument that allows incrementing by values other than 1.~itertools.countalso now allows keyword arguments, and using non-integer values such as floats or~decimal.Decimalinstances. (Implemented by Raymond Hettinger;5032.)itertools.combinationsanditertools.productpreviously raisedValueErrorfor values of r larger than the input iterable. This was deemed a specification error, so they now return an empty iterator. (Fixed by Raymond Hettinger;4816.) -
Updated module: The
jsonmodule was upgraded to version 2.0.9 of the simplejson package, which includes a C extension that makes encoding and decoding faster. (Contributed by Bob Ippolito;4136.)To support the new
collections.OrderedDicttype,json.loadnow has an optional object_pairs_hook parameter that will be called with any object literal that decodes to a list of pairs. (Contributed by Raymond Hettinger;5381.) -
The
mailboxmodule's~mailbox.Maildirclass now records the timestamp on the directories it reads, and only re-reads them if the modification time has subsequently changed. This improves performance by avoiding unneeded directory scans. (Fixed by A.M. Kuchling and Antoine Pitrou;1607951,6896.) -
New functions: the
mathmodule gained~math.erfand~math.erfcfor the error function and the complementary error function,~math.expm1which computese**x - 1with more precision than using~math.expand subtracting 1,~math.gammafor the Gamma function, and~math.lgammafor the natural log of the Gamma function. (Contributed by Mark Dickinson and nirinA raseliarison;3366.) -
The
multiprocessingmodule's!Manager*classes can now be passed a callable that will be called whenever a subprocess is started, along with a set of arguments that will be passed to the callable. (Contributed by lekma;5585.)The
~multiprocessing.pool.Poolclass, which controls a pool of worker processes, now has an optional maxtasksperchild parameter. Worker processes will perform the specified number of tasks and then exit, causing the!Poolto start a new worker. This is useful if tasks may leak memory or other resources, or if some tasks will cause the worker to become very large. (Contributed by Charles Cazabon;6963.) -
The
!nntplibmodule now supports IPv6 addresses. (Contributed by Derek Morr;1664.) -
New functions: the
osmodule wraps the following POSIX system calls:~os.getresgidand~os.getresuid, which return the real, effective, and saved GIDs and UIDs;~os.setresgidand~os.setresuid, which set real, effective, and saved GIDs and UIDs to new values;~os.initgroups, which initialize the group access list for the current process. (GID/UID functions contributed by Travis H.;6508. Support for initgroups added by Jean-Paul Calderone;7333.)The
os.forkfunction now re-initializes the import lock in the child process; this fixes problems on Solaris when~os.forkis called from a thread. (Fixed by Zsolt Cserna;7242.) -
In the
os.pathmodule, the~os.path.normpathand~os.path.abspathfunctions now preserve Unicode; if their input path is a Unicode string, the return value is also a Unicode string. (~os.path.normpathfixed by Matt Giuca in5827;~os.path.abspathfixed by Ezio Melotti in3426.) -
The
pydocmodule now has help for the various symbols that Python uses. You can now dohelp('<<')orhelp('@'), for example. (Contributed by David Laban;4739.) -
The
remodule's~re.split,~re.sub, and~re.subnnow accept an optional flags argument, for consistency with the other functions in the module. (Added by Gregory P. Smith.) -
New function:
~runpy.run_pathin therunpymodule will execute the code at a provided path argument. path can be the path of a Python source file (example.py), a compiled bytecode file (example.pyc), a directory (./package/), or a zip archive (example.zip). If a directory or zip path is provided, it will be added to the front ofsys.pathand the module__main__will be imported. It's expected that the directory or zip contains a__main__.py; if it doesn't, some other__main__.pymight be imported from a location later insys.path. This makes more of the machinery ofrunpyavailable to scripts that want to mimic the way Python's command line processes an explicit path name. (Added by Nick Coghlan;6816.) -
New function: in the
shutilmodule,~shutil.make_archivetakes a filename, archive type (zip or tar-format), and a directory path, and creates an archive containing the directory's contents. (Added by Tarek Ziadé.)shutil's~shutil.copyfileand~shutil.copytreefunctions now raise a~shutil.SpecialFileErrorexception when asked to copy a named pipe. Previously the code would treat named pipes like a regular file by opening them for reading, and this would block indefinitely. (Fixed by Antoine Pitrou;3002.) -
The
signalmodule no longer re-installs the signal handler unless this is truly necessary, which fixes a bug that could make it impossible to catch the EINTR signal robustly. (Fixed by Charles-Francois Natali;8354.) -
New functions: in the
sitemodule, three new functions return various site- and user-specific paths.~site.getsitepackagesreturns a list containing all global site-packages directories,~site.getusersitepackagesreturns the path of the user's site-packages directory, and~site.getuserbasereturns the value of the~site.USER_BASEenvironment variable, giving the path to a directory that can be used to store data. (Contributed by Tarek Ziadé;6693.)The
sitemodule now reports exceptions occurring when thesitecustomizemodule is imported, and will no longer catch and swallow theKeyboardInterruptexception. (Fixed by Victor Stinner;3137.) -
The
~socket.create_connectionfunction gained a source_address parameter, a(host, port)2-tuple giving the source address that will be used for the connection. (Contributed by Eldon Ziegler;3972.)The
~socket.socket.recv_intoand~socket.socket.recvfrom_intomethods will now write into objects that support the buffer API, most usefully thebytearrayandmemoryviewobjects. (Implemented by Antoine Pitrou;8104.) -
The
SocketServer <socketserver>module's~socketserver.TCPServerclass now supports socket timeouts and disabling the Nagle algorithm. The!disable_nagle_algorithmclass attribute defaults toFalse; if overridden to be true, new request connections will have the TCP_NODELAY option set to prevent buffering many small sends into a single TCP packet. The~socketserver.BaseServer.timeoutclass attribute can hold a timeout in seconds that will be applied to the request socket; if no request is received within that time,~socketserver.BaseServer.handle_timeoutwill be called and~socketserver.BaseServer.handle_requestwill return. (Contributed by Kristján Valur Jónsson;6192and6267.) -
Updated module: the
sqlite3module has been updated to version 2.6.0 of the pysqlite package. Version 2.6.0 includes a number of bugfixes, and adds the ability to load SQLite extensions from shared libraries. Call theenable_load_extension(True)method to enable extensions, and then call~sqlite3.Connection.load_extensionto load a particular shared library. (Updated by Gerhard Häring.) -
The
sslmodule's~ssl.SSLSocketobjects now support the buffer API, which fixed a test suite failure (fix by Antoine Pitrou;7133) and automatically set OpenSSL's!SSL_MODE_AUTO_RETRY, which will prevent an error code being returned from!recvoperations that trigger an SSL renegotiation (fix by Antoine Pitrou;8222).The
~ssl.SSLContext.wrap_socketconstructor function now takes a ciphers argument that's a string listing the encryption algorithms to be allowed; the format of the string is described in the OpenSSL documentation. (Added by Antoine Pitrou;8322.)Another change makes the extension load all of OpenSSL's ciphers and digest algorithms so that they're all available. Some SSL certificates couldn't be verified, reporting an "unknown algorithm" error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
8484.)The version of OpenSSL being used is now available as the module attributes
ssl.OPENSSL_VERSION(a string),ssl.OPENSSL_VERSION_INFO(a 5-tuple), andssl.OPENSSL_VERSION_NUMBER(an integer). (Added by Antoine Pitrou;8321.) -
The
structmodule will no longer silently ignore overflow errors when a value is too large for a particular integer format code (one ofbBhHiIlLqQ); it now always raises astruct.errorexception. (Changed by Mark Dickinson;1523.) The~struct.packfunction will also attempt to use~object.__index__to convert and pack non-integers before trying the~object.__int__method or reporting an error. (Changed by Mark Dickinson;8300.) -
New function: the
subprocessmodule's~subprocess.check_outputruns a command with a specified set of arguments and returns the command's output as a string when the command runs without error, or raises a~subprocess.CalledProcessErrorexception otherwise.>>> subprocess.check_output(['df', '-h', '.']) 'Filesystem Size Used Avail Capacity Mounted on\n /dev/disk0s2 52G 49G 3.0G 94% /\n' >>> subprocess.check_output(['df', '-h', '/bogus']) ... subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1(Contributed by Gregory P. Smith.)
The
subprocessmodule will now retry its internal system calls on receiving an~errno.EINTRsignal. (Reported by several people; final patch by Gregory P. Smith in1068268.) -
New function:
~symtable.Symbol.is_declared_globalin thesymtablemodule returns true for variables that are explicitly declared to be global, false for ones that are implicitly global. (Contributed by Jeremy Hylton.) -
The
syslogmodule will now use the value ofsys.argv[0]as the identifier instead of the previous default value of'python'. (Changed by Sean Reifschneider;8451.) -
The
sys.version_infovalue is now a named tuple, with attributes named!major,!minor,!micro,!releaselevel, and!serial. (Contributed by Ross Light;4285.)sys.getwindowsversionalso returns a named tuple, with attributes named!major,!minor,!build,!platform,!service_pack,!service_pack_major,!service_pack_minor,!suite_mask, and!product_type. (Contributed by Brian Curtin;7766.) -
The
tarfilemodule's default error handling has changed, to no longer suppress fatal errors. The default error level was previously 0, which meant that errors would only result in a message being written to the debug log, but because the debug log is not activated by default, these errors go unnoticed. The default error level is now 1, which raises an exception if there's an error. (Changed by Lars Gustäbel;7357.)tarfilenow supports filtering the~tarfile.TarInfoobjects being added to a tar file. When you call~tarfile.TarFile.add, you may supply an optional filter argument that's a callable. The filter callable will be passed the~tarfile.TarInfofor every file being added, and can modify and return it. If the callable returnsNone, the file will be excluded from the resulting archive. This is more powerful than the existing exclude argument, which has therefore been deprecated. (Added by Lars Gustäbel;6856.) The~tarfile.TarFileclass also now supports the context management protocol. (Added by Lars Gustäbel;7232.) -
The
~threading.Event.waitmethod of thethreading.Eventclass now returns the internal flag on exit. This means the method will usually return true because~threading.Event.waitis supposed to block until the internal flag becomes true. The return value will only be false if a timeout was provided and the operation timed out. (Contributed by Tim Lesher;1674032.) -
The Unicode database provided by the
unicodedatamodule is now used internally to determine which characters are numeric, whitespace, or represent line breaks. The database also includes information from theUnihan.txtdata file (patch by Anders Chrigström and Amaury Forgeot d'Arc;1571184) and has been updated to version 5.2.0 (updated by Florent Xicluna;8024). -
The
urlparse <urllib.parse>module's~urllib.parse.urlsplitnow handles unknown URL schemes in a fashion compliant with3986: if the URL is of the form"<something>://...", the text before the://is treated as the scheme, even if it's a made-up scheme that the module doesn't know about. This change may break code that worked around the old behaviour. For example, Python 2.6.4 or 2.5 will return the following:>>> import urlparse >>> urlparse.urlsplit('invented://host/filename?query') ('invented', '', '//host/filename?query', '', '')
Python 2.7 (and Python 2.6.5) will return:
>>> import urlparse >>> urlparse.urlsplit('invented://host/filename?query') ('invented', 'host', '/filename?query', '', '')
(Python 2.7 actually produces slightly different output, since it returns a named tuple instead of a standard tuple.)
The
urlparse <urllib.parse>module also supports IPv6 literal addresses as defined by2732(contributed by Senthil Kumaran;2987).>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo') ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]', path='/foo', params='', query='', fragment='')
-
New class: the
~weakref.WeakSetclass in theweakrefmodule is a set that only holds weak references to its elements; elements will be removed once there are no references pointing to them. (Originally implemented in Python 3.x by Raymond Hettinger, and backported to 2.7 by Michael Foord.) -
The
xml.etree.ElementTreelibrary, no longer escapes ampersands and angle brackets when outputting an XML processing instruction (which looks like<?xml-stylesheet href="#style1"?>) or comment (which looks like<!-- comment -->). (Patch by Neil Muller;2746.) -
The XML-RPC client and server, provided by the
xmlrpclib <xmlrpc.client>andSimpleXMLRPCServer <xmlrpc.server>modules, have improved performance by supporting HTTP/1.1 keep-alive and by optionally using gzip encoding to compress the XML being exchanged. The gzip compression is controlled by the!encode_thresholdattribute of~xmlrpc.server.SimpleXMLRPCRequestHandler, which contains a size in bytes; responses larger than this will be compressed. (Contributed by Kristján Valur Jónsson;6267.) -
The
zipfilemodule's~zipfile.ZipFilenow supports the context management protocol, so you can writewith zipfile.ZipFile(...) as f:. (Contributed by Brian Curtin;5511.)zipfilenow also supports archiving empty directories and extracts them correctly. (Fixed by Kuba Wieczorek;4710.) Reading files out of an archive is faster, and interleavingread() <io.BufferedIOBase.read>andreadline() <io.IOBase.readline>now works correctly. (Contributed by Nir Aides;7610.)The
~zipfile.is_zipfilefunction now accepts a file object, in addition to the path names accepted in earlier versions. (Contributed by Gabriel Genellina;4756.)The
~zipfile.ZipFile.writestrmethod now has an optional compress_type parameter that lets you override the default compression method specified in the~zipfile.ZipFileconstructor. (Contributed by Ronald Oussoren;6003.)
New module: importlib
Python 3.1 includes the importlib package, a re-implementation of the logic underlying Python's import statement. importlib is useful for implementers of Python interpreters and to users who wish to write new importers that can participate in the import process. Python 2.7 doesn't contain the complete importlib package, but instead has a tiny subset that contains a single function, ~importlib.import_module.
import_module(name, package=None) imports a module. name is a string containing the module or package's name. It's possible to do relative imports by providing a string that begins with a . character, such as ..utils.errors. For relative imports, the package argument must be provided and is the name of the package that will be used as the anchor for the relative import. ~importlib.import_module both inserts the imported module into sys.modules and returns the module object.
Here are some examples:
>>> from importlib import import_module
>>> anydbm = import_module('anydbm') # Standard absolute import
>>> anydbm
<module 'anydbm' from '/p/python/Lib/anydbm.py'>
>>> # Relative import
>>> file_util = import_module('..file_util', 'distutils.command')
>>> file_util
<module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
importlib was implemented by Brett Cannon and introduced in Python 3.1.
New module: sysconfig
The sysconfig module has been pulled out of the Distutils package, becoming a new top-level module in its own right. sysconfig provides functions for getting information about Python's build process: compiler switches, installation paths, the platform name, and whether Python is running from its source directory.
Some of the functions in the module are:
~sysconfig.get_config_varreturns variables from Python's Makefile and thepyconfig.hfile.~sysconfig.get_config_varsreturns a dictionary containing all of the configuration variables.~sysconfig.get_pathreturns the configured path for a particular type of module: the standard library, site-specific modules, platform-specific modules, etc.~sysconfig.is_python_buildreturns true if you're running a binary from a Python source tree, and false otherwise.
Consult the sysconfig documentation for more details and for a complete list of functions.
The Distutils package and sysconfig are now maintained by Tarek Ziadé, who has also started a Distutils2 package (source repository at https://hg.python.org/distutils2/) for developing a next-generation version of Distutils.
ttk: Themed Widgets for Tk
Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk widgets but have a more customizable appearance and can therefore more closely resemble the native platform's widgets. This widget set was originally called Tile, but was renamed to Ttk (for "themed Tk") on being added to Tcl/Tck release 8.5.
To learn more, read the ~tkinter.ttk module documentation. You may also wish to read the Tcl/Tk manual page describing the Ttk theme engine, available at https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.html. Some screenshots of the Python/Ttk code in use are at https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki.
The tkinter.ttk module was written by Guilherme Polo and added in 2983. An alternate version called Tile.py, written by Martin Franklin and maintained by Kevin Walzer, was proposed for inclusion in 2618, but the authors argued that Guilherme Polo's work was more comprehensive.
Updated module: unittest
The unittest module was greatly enhanced; many new features were added. Most of these features were implemented by Michael Foord, unless otherwise noted. The enhanced version of the module is downloadable separately for use with Python versions 2.4 to 2.6, packaged as the !unittest2 package, from unittest2.
When used from the command line, the module can automatically discover tests. It's not as fancy as py.test or nose, but provides a simple way to run tests kept within a set of package directories. For example, the following command will search the test/ subdirectory for any importable test files named test*.py:
python -m unittest discover -s test
Consult the unittest module documentation for more details. (Developed in 6001.)
The ~unittest.main function supports some other new options:
-
-b <unittest -b>or!--bufferwill buffer the standard output and standard error streams during each test. If the test passes, any resulting output will be discarded; on failure, the buffered output will be displayed. -
-c <unittest -c>or!--catchwill cause the control-C interrupt to be handled more gracefully. Instead of interrupting the test process immediately, the currently running test will be completed and then the partial results up to the interruption will be reported. If you're impatient, a second press of control-C will cause an immediate interruption.This control-C handler tries to avoid causing problems when the code being tested or the tests being run have defined a signal handler of their own, by noticing that a signal handler was already set and calling it. If this doesn't work for you, there's a
~unittest.removeHandlerdecorator that can be used to mark tests that should have the control-C handling disabled. -
-f <unittest -f>or!--failfastmakes test execution stop immediately when a test fails instead of continuing to execute further tests. (Suggested by Cliff Dyer and implemented by Michael Foord;8074.)
The progress messages now show 'x' for expected failures and 'u' for unexpected successes when run in verbose mode. (Contributed by Benjamin Peterson.)
Test cases can raise the ~unittest.SkipTest exception to skip a test (1034053).
The error messages for ~unittest.TestCase.assertEqual, ~unittest.TestCase.assertTrue, and ~unittest.TestCase.assertFalse failures now provide more information. If you set the ~unittest.TestCase.longMessage attribute of your ~unittest.TestCase classes to true, both the standard error message and any additional message you provide will be printed for failures. (Added by Michael Foord; 5663.)
The ~unittest.TestCase.assertRaises method now returns a context handler when called without providing a callable object to run. For example, you can write this:
with self.assertRaises(KeyError):
{}['foo']
(Implemented by Antoine Pitrou; 4444.)
Module- and class-level setup and teardown fixtures are now supported. Modules can contain ~unittest.setUpModule and ~unittest.tearDownModule functions. Classes can have ~unittest.TestCase.setUpClass and ~unittest.TestCase.tearDownClass methods that must be defined as class methods (using @classmethod or equivalent). These functions and methods are invoked when the test runner switches to a test case in a different module or class.
The methods ~unittest.TestCase.addCleanup and ~unittest.TestCase.doCleanups were added. ~unittest.TestCase.addCleanup lets you add cleanup functions that will be called unconditionally (after ~unittest.TestCase.setUp if ~unittest.TestCase.setUp fails, otherwise after ~unittest.TestCase.tearDown). This allows for much simpler resource allocation and deallocation during tests (5679).
A number of new methods were added that provide more specialized tests. Many of these methods were written by Google engineers for use in their test suites; Gregory P. Smith, Michael Foord, and GvR worked on merging them into Python's version of unittest.
~unittest.TestCase.assertIsNoneand~unittest.TestCase.assertIsNotNonetake one expression and verify that the result is or is notNone.~unittest.TestCase.assertIsand~unittest.TestCase.assertIsNottake two values and check whether the two values evaluate to the same object or not. (Added by Michael Foord;2578.)~unittest.TestCase.assertIsInstanceand~unittest.TestCase.assertNotIsInstancecheck whether the resulting object is an instance of a particular class, or of one of a tuple of classes. (Added by Georg Brandl;7031.)~unittest.TestCase.assertGreater,~unittest.TestCase.assertGreaterEqual,~unittest.TestCase.assertLess, and~unittest.TestCase.assertLessEqualcompare two quantities.~unittest.TestCase.assertMultiLineEqualcompares two strings, and if they're not equal, displays a helpful comparison that highlights the differences in the two strings. This comparison is now used by default when Unicode strings are compared with~unittest.TestCase.assertEqual.assertRegexpMatches() <unittest.TestCase.assertRegex>andassertNotRegexpMatches() <unittest.TestCase.assertNotRegex>checks whether the first argument is a string matching or not matching the regular expression provided as the second argument (8038).assertRaisesRegexp() <unittest.TestCase.assertRaisesRegex>checks whether a particular exception is raised, and then also checks that the string representation of the exception matches the provided regular expression.~unittest.TestCase.assertInand~unittest.TestCase.assertNotIntests whether first is or is not in second.assertItemsEqual() <unittest.TestCase.assertCountEqual>tests whether two provided sequences contain the same elements.~unittest.TestCase.assertSetEqualcompares whether two sets are equal, and only reports the differences between the sets in case of error.- Similarly,
~unittest.TestCase.assertListEqualand~unittest.TestCase.assertTupleEqualcompare the specified types and explain any differences without necessarily printing their full values; these methods are now used by default when comparing lists and tuples using~unittest.TestCase.assertEqual. More generally,~unittest.TestCase.assertSequenceEqualcompares two sequences and can optionally check whether both sequences are of a particular type. ~unittest.TestCase.assertDictEqualcompares two dictionaries and reports the differences; it's now used by default when you compare two dictionaries using~unittest.TestCase.assertEqual.!assertDictContainsSubsetchecks whether all of the key/value pairs in first are found in second.~unittest.TestCase.assertAlmostEqualand~unittest.TestCase.assertNotAlmostEqualtest whether first and second are approximately equal. This method can either round their difference to an optionally specified number of places (the default is 7) and compare it to zero, or require the difference to be smaller than a supplied delta value.~unittest.TestLoader.loadTestsFromNameproperly honors the~unittest.TestLoader.suiteClassattribute of the~unittest.TestLoader. (Fixed by Mark Roddy;6866.)- A new hook lets you extend the
~unittest.TestCase.assertEqualmethod to handle new data types. The~unittest.TestCase.addTypeEqualityFuncmethod takes a type object and a function. The function will be used when both of the objects being compared are of the specified type. This function should compare the two objects and raise an exception if they don't match; it's a good idea for the function to provide additional information about why the two objects aren't matching, much as the new sequence comparison methods do.
unittest.main now takes an optional exit argument. If false, ~unittest.main doesn't call sys.exit, allowing ~unittest.main to be used from the interactive interpreter. (Contributed by J. Pablo Fernández; 3379.)
~unittest.TestResult has new ~unittest.TestResult.startTestRun and ~unittest.TestResult.stopTestRun methods that are called immediately before and after a test run. (Contributed by Robert Collins; 5728.)
With all these changes, the unittest.py was becoming awkwardly large, so the module was turned into a package and the code split into several files (by Benjamin Peterson). This doesn't affect how the module is imported or used.
https://web.archive.org/web/20210619163128/http://www.voidspace.org.uk/python/articles/unittest2.shtml
Describes the new features, how to use them, and the rationale for various design decisions. (By Michael Foord.)
Updated module: ElementTree 1.3
The version of the ElementTree library included with Python was updated to version 1.3. Some of the new features are:
-
The various parsing functions now take a parser keyword argument giving an
~xml.etree.ElementTree.XMLParserinstance that will be used. This makes it possible to override the file's internal encoding:p = ET.XMLParser(encoding='utf-8') t = ET.XML("""<root/>""", parser=p)Errors in parsing XML now raise a
~xml.etree.ElementTree.ParseErrorexception, whose instances have a!positionattribute containing a (line, column) tuple giving the location of the problem. -
ElementTree's code for converting trees to a string has been significantly reworked, making it roughly twice as fast in many cases. The
ElementTree.write() <xml.etree.ElementTree.ElementTree.write>and!Element.writemethods now have a method parameter that can be "xml" (the default), "html", or "text". HTML mode will output empty elements as<empty></empty>instead of<empty/>, and text mode will skip over elements and only output the text chunks. If you set the~xml.etree.ElementTree.Element.tagattribute of an element toNonebut leave its children in place, the element will be omitted when the tree is written out, so you don't need to do more extensive rearrangement to remove a single element.Namespace handling has also been improved. All
xmlns:<whatever>declarations are now output on the root element, not scattered throughout the resulting XML. You can set the default namespace for a tree by setting the!default_namespaceattribute and can register new prefixes with~xml.etree.ElementTree.register_namespace. In XML mode, you can use the true/false xml_declaration parameter to suppress the XML declaration. -
New
~xml.etree.ElementTree.Elementmethod:~xml.etree.ElementTree.Element.extendappends the items from a sequence to the element's children. Elements themselves behave like sequences, so it's easy to move children from one element to another:from xml.etree import ElementTree as ET t = ET.XML("""<list> <item>1</item> <item>2</item> <item>3</item> </list>""") new = ET.XML('<root/>') new.extend(t) # Outputs <root><item>1</item>...</root> print ET.tostring(new) -
New
~xml.etree.ElementTree.Elementmethod:~xml.etree.ElementTree.Element.iteryields the children of the element as a generator. It's also possible to writefor child in elem:to loop over an element's children. The existing method!getiteratoris now deprecated, as is!getchildrenwhich constructs and returns a list of children. -
New
~xml.etree.ElementTree.Elementmethod:~xml.etree.ElementTree.Element.itertextyields all chunks of text that are descendants of the element. For example:t = ET.XML("""<list> <item>1</item> <item>2</item> <item>3</item> </list>""") # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n'] print list(t.itertext()) -
Deprecated: using an element as a Boolean (i.e.,
if elem:) would return true if the element had any children, or false if there were no children. This behaviour is confusing --Noneis false, but so is a childless element? -- so it will now trigger aFutureWarning. In your code, you should be explicit: writelen(elem) != 0if you're interested in the number of children, orelem is not None.
Fredrik Lundh develops ElementTree and produced the 1.3 version; you can read his article describing 1.3 at https://web.archive.org/web/20200703234532/http://effbot.org/zone/elementtree-13-intro.htm. Florent Xicluna updated the version included with Python, after discussions on python-dev and in 6472.)
Build and C API Changes
Changes to Python's build process and to the C API include:
-
The latest release of the GNU Debugger, GDB 7, can be scripted using Python. When you begin debugging an executable program P, GDB will look for a file named
P-gdb.pyand automatically read it. Dave Malcolm contributed apython-gdb.pythat adds a number of commands useful when debugging Python itself. For example,py-upandpy-downgo up or down one Python stack frame, which usually corresponds to several C stack frames.py-printprints the value of a Python variable, andpy-btprints the Python stack trace. (Added as a result of8032.) -
If you use the
.gdbinitfile provided with Python, the "pyo" macro in the 2.7 version now works correctly when the thread being debugged doesn't hold the GIL; the macro now acquires it before printing. (Contributed by Victor Stinner;3632.) -
Py_AddPendingCallis now thread-safe, letting any worker thread submit notifications to the main Python thread. This is particularly useful for asynchronous IO operations. (Contributed by Kristján Valur Jónsson;4293.) -
New function:
PyCode_NewEmptycreates an empty code object; only the filename, function name, and first line number are required. This is useful for extension modules that are attempting to construct a more useful traceback stack. Previously such extensions needed to call!PyCode_New, which had many more arguments. (Added by Jeffrey Yasskin.) -
New function:
PyErr_NewExceptionWithDoccreates a new exception class, just as the existingPyErr_NewExceptiondoes, but takes an extrachar *argument containing the docstring for the new exception class. (Added by 'lekma' on the Python bug tracker;7033.) -
New function:
PyFrame_GetLineNumbertakes a frame object and returns the line number that the frame is currently executing. Previously code would need to get the index of the bytecode instruction currently executing, and then look up the line number corresponding to that address. (Added by Jeffrey Yasskin.) -
New functions:
PyLong_AsLongAndOverflowandPyLong_AsLongLongAndOverflowapproximates a Python long integer as a Clongorlong long. If the number is too large to fit into the output type, an overflow flag is set and returned to the caller. (Contributed by Case Van Horsen;7528and7767.) -
New function: stemming from the rewrite of string-to-float conversion, a new
PyOS_string_to_doublefunction was added. The old!PyOS_ascii_strtodand!PyOS_ascii_atoffunctions are now deprecated. -
New function:
!PySys_SetArgvExsets the value ofsys.argvand can optionally updatesys.pathto include the directory containing the script named bysys.argv[0]depending on the value of an updatepath parameter.This function was added to close a security hole for applications that embed Python. The old function,
!PySys_SetArgv, would always updatesys.path, and sometimes it would add the current directory. This meant that, if you ran an application embedding Python in a directory controlled by someone else, attackers could put a Trojan-horse module in the directory (say, a file namedos.py) that your application would then import and run.If you maintain a C/C++ application that embeds Python, check whether you're calling
!PySys_SetArgvand carefully consider whether the application should be using!PySys_SetArgvExwith updatepath set to false.Security issue reported as
2008-5983; discussed in5753, and fixed by Antoine Pitrou. -
New macros: the Python header files now define the following macros:
Py_ISALNUM,Py_ISALPHA,Py_ISDIGIT,Py_ISLOWER,Py_ISSPACE,Py_ISUPPER,Py_ISXDIGIT,Py_TOLOWER, andPy_TOUPPER. All of these functions are analogous to the C standard macros for classifying characters, but ignore the current locale setting, because in several places Python needs to analyze characters in a locale-independent way. (Added by Eric Smith;5793.) -
Removed function:
!PyEval_CallObjectis now only available as a macro. A function version was being kept around to preserve ABI linking compatibility, but that was in 1997; it can certainly be deleted by now. (Removed by Antoine Pitrou;8276.) -
New format codes: the
!PyString_FromFormat,!PyString_FromFormatV, andPyErr_Formatfunctions now accept%lldand%lluformat codes for displaying C'slong longtypes. (Contributed by Mark Dickinson;7228.) -
The complicated interaction between threads and process forking has been changed. Previously, the child process created by
os.forkmight fail because the child is created with only a single thread running, the thread performing theos.fork. If other threads were holding a lock, such as Python's import lock, when the fork was performed, the lock would still be marked as "held" in the new process. But in the child process nothing would ever release the lock, since the other threads weren't replicated, and the child process would no longer be able to perform imports.Python 2.7 acquires the import lock before performing an
os.fork, and will also clean up any locks created using thethreadingmodule. C extension modules that have internal locks, or that callfork()themselves, will not benefit from this clean-up.(Fixed by Thomas Wouters;
1590864.) -
The
Py_Finalizefunction now calls the internal!threading._shutdownfunction; this prevents some exceptions from being raised when an interpreter shuts down. (Patch by Adam Olsen;1722344.) -
When using the
PyMemberDefstructure to define attributes of a type, Python will no longer let you try to delete or set a!T_STRING_INPLACEattribute. -
Global symbols defined by the
ctypesmodule are now prefixed withPy, or with_ctypes. (Implemented by Thomas Heller;3102.) -
New configure option: the
!--with-system-expatswitch allows building thepyexpat <xml.parsers.expat>module to use the system Expat library. (Contributed by Arfrever Frehtes Taifersar Arahesis;7609.) -
New configure option: the
!--with-valgrindoption will now disable the pymalloc allocator, which is difficult for the Valgrind memory-error detector to analyze correctly. Valgrind will therefore be better at detecting memory leaks and overruns. (Contributed by James Henstridge;2422.) -
New configure option: you can now supply an empty string to
!--with-dbmliborder=in order to disable all of the various DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;6491.) -
The
configurescript now checks for floating-point rounding bugs on certain 32-bit Intel chips and defines a!X87_DOUBLE_ROUNDINGpreprocessor definition. No code currently uses this definition, but it's available if anyone wishes to use it. (Added by Mark Dickinson;2937.)configurealso now sets a!LDCXXSHAREDMakefile variable for supporting C++ linking. (Contributed by Arfrever Frehtes Taifersar Arahesis;1222585.) -
The build process now creates the necessary files for pkg-config support. (Contributed by Clinton Roy;
3585.) -
The build process now supports Subversion 1.7. (Contributed by Arfrever Frehtes Taifersar Arahesis;
6094.)
Capsules
Python 3.1 adds a new C datatype, PyCapsule, for providing a C API to an extension module. A capsule is essentially the holder of a C void * pointer, and is made available as a module attribute; for example, the socket module's API is exposed as socket.CAPI, and unicodedata exposes ucnhash_CAPI. Other extensions can import the module, access its dictionary to get the capsule object, and then get the void * pointer, which will usually point to an array of pointers to the module's various API functions.
There is an existing data type already used for this, !PyCObject, but it doesn't provide type safety. Evil code written in pure Python could cause a segmentation fault by taking a !PyCObject from module A and somehow substituting it for the !PyCObject in module B. Capsules know their own name, and getting the pointer requires providing the name:
void *vtable;
if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
PyErr_SetString(PyExc_ValueError, "argument type invalid");
return NULL;
}
vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
You are assured that vtable points to whatever you're expecting. If a different capsule was passed in, PyCapsule_IsValid would detect the mismatched name and return false. Refer to using-capsules for more information on using these objects.
Python 2.7 now uses capsules internally to provide various extension-module APIs, but the !PyCObject_AsVoidPtr was modified to handle capsules, preserving compile-time compatibility with the !PyCObject interface. Use of !PyCObject_AsVoidPtr will signal a PendingDeprecationWarning, which is silent by default.
Implemented in Python 3.1 and backported to 2.7 by Larry Hastings; discussed in 5630.
Port-Specific Changes: Windows
- The
msvcrtmodule now contains some constants from thecrtassem.hheader file:~msvcrt.CRT_ASSEMBLY_VERSION,~msvcrt.VC_ASSEMBLY_PUBLICKEYTOKEN, and~msvcrt.LIBRARIES_ASSEMBLY_NAME_PREFIX. (Contributed by David Cournapeau;4365.) - The
_winreg <winreg>module for accessing the registry now implements the~winreg.CreateKeyExand~winreg.DeleteKeyExfunctions, extended versions of previously supported functions that take several extra arguments. The~winreg.DisableReflectionKey,~winreg.EnableReflectionKey, and~winreg.QueryReflectionKeywere also tested and documented. (Implemented by Brian Curtin:7347.) - The new
!_beginthreadexAPI is used to start threads, and the native thread-local storage functions are now used. (Contributed by Kristján Valur Jónsson;3582.) - The
os.killfunction now works on Windows. The signal value can be the constants~signal.CTRL_C_EVENT,~signal.CTRL_BREAK_EVENT, or any integer. The first two constants will sendControl-CandControl-Breakkeystroke events to subprocesses; any other value will use the!TerminateProcessAPI. (Contributed by Miki Tebeka;1220212.) - The
os.listdirfunction now correctly fails for an empty path. (Fixed by Hirokazu Yamamoto;5913.) - The
mimetypesmodule will now read the MIME database from the Windows registry when initializing. (Patch by Gabriel Genellina;4969.)
Port-Specific Changes: Mac OS X
-
The path
/Library/Python/2.7/site-packagesis now appended tosys.path, in order to share added packages between the system installation and a user-installed copy of the same version. (Changed by Ronald Oussoren;4865.)2.7.13
As of 2.7.13, this change was removed.
/Library/Python/2.7/site-packages, the site-packages directory used by the Apple-supplied system Python 2.7 is no longer appended tosys.pathfor user-installed Pythons such as from the python.org installers. As of macOS 10.12, Apple changed how the system site-packages directory is configured, which could cause installation of pip components, like setuptools, to fail. Packages installed for the system Python will no longer be shared with user-installed Pythons. (28440)
Port-Specific Changes: FreeBSD
- FreeBSD 7.1's
!SO_SETFIBconstant, used with the~socket.socketmethods~socket.socket.getsockopt/~socket.socket.setsockoptto select an alternate routing table, is now available in thesocketmodule. (Added by Kyle VanderBeek;8235.)
Other Changes and Fixes
- Two benchmark scripts,
iobenchandccbench, were added to theToolsdirectory.iobenchmeasures the speed of the built-in file I/O objects returned byopenwhile performing various operations, andccbenchis a concurrency benchmark that tries to measure computing throughput, thread switching latency, and IO processing bandwidth when performing several tasks using a varying number of threads. - The
Tools/i18n/msgfmt.pyscript now understands plural forms in.pofiles. (Fixed by Martin von Löwis;5464.) - When importing a module from a
.pycor.pyofile with an existing.pycounterpart, the~codeobject.co_filenameattributes of the resulting code objects are overwritten when the original filename is obsolete. This can happen if the file has been renamed, moved, or is accessed through different paths. (Patch by Ziga Seilnacht and Jean-Paul Calderone;1180193.) - The
regrtest.pyscript now takes a!--randseed=switch that takes an integer that will be used as the random seed for the!-roption that executes tests in random order. The!-roption also reports the seed that was used (Added by Collin Winter.) - Another
regrtest.pyswitch is!-j, which takes an integer specifying how many tests run in parallel. This allows reducing the total runtime on multi-core machines. This option is compatible with several other options, including the!-Rswitch which is known to produce long runtimes. (Added by Antoine Pitrou,6152.) This can also be used with a new!-Fswitch that runs selected tests in a loop until they fail. (Added by Antoine Pitrou;7312.) - When executed as a script, the
py_compile.pymodule now accepts'-'as an argument, which will read standard input for the list of filenames to be compiled. (Contributed by Piotr Ożarowski;8233.)
Porting to Python 2.7
This section lists previously described changes and other bugfixes that may require changes to your code:
- The
rangefunction processes its arguments more consistently; it will now call~object.__int__on non-float, non-integer arguments that are supplied to it. (Fixed by Alexander Belopolsky;1533.) - The string
formatmethod changed the default precision used for floating-point and complex numbers from 6 decimal places to 12, which matches the precision used bystr. (Changed by Eric Smith;5920.) - Because of an optimization for the
withstatement, the special methods~object.__enter__and~object.__exit__must belong to the object's type, and cannot be directly attached to the object's instance. This affects new-style classes (derived fromobject) and C extension types. (6101.) - Due to a bug in Python 2.6, the exc_value parameter to
~object.__exit__methods was often the string representation of the exception, not an instance. This was fixed in 2.7, so exc_value will be an instance as expected. (Fixed by Florent Xicluna;7853.) - When a restricted set of attributes were set using
__slots__, deleting an unset attribute would not raiseAttributeErroras you would expect. Fixed by Benjamin Peterson;7604.)
In the standard library:
-
Operations with
~datetime.datetimeinstances that resulted in a year falling outside the supported range didn't always raiseOverflowError. Such errors are now checked more carefully and will now raise the exception. (Reported by Mark Leander, patch by Anand B. Pillai and Alexander Belopolsky;7150.) -
When using
~decimal.Decimalinstances with a string'sformatmethod, the default alignment was previously left-alignment. This has been changed to right-alignment, which might change the output of your programs. (Changed by Mark Dickinson;6857.)Comparisons involving a signaling NaN value (or
sNAN) now signal~decimal.InvalidOperationinstead of silently returning a true or false value depending on the comparison operator. Quiet NaN values (orNaN) are now hashable. (Fixed by Mark Dickinson;7279.) -
The
xml.etree.ElementTreelibrary no longer escapes ampersands and angle brackets when outputting an XML processing instruction (which looks like<?xml-stylesheet href="#style1"?>) or comment (which looks like<!-- comment -->). (Patch by Neil Muller;2746.) -
The
!readlinemethod of~io.StringIOobjects now does nothing when a negative length is requested, as other file-like objects do. (7348). -
The
syslogmodule will now use the value ofsys.argv[0]as the identifier instead of the previous default value of'python'. (Changed by Sean Reifschneider;8451.) -
The
tarfilemodule's default error handling has changed, to no longer suppress fatal errors. The default error level was previously 0, which meant that errors would only result in a message being written to the debug log, but because the debug log is not activated by default, these errors go unnoticed. The default error level is now 1, which raises an exception if there's an error. (Changed by Lars Gustäbel;7357.) -
The
urlparse <urllib.parse>module's~urllib.parse.urlsplitnow handles unknown URL schemes in a fashion compliant with3986: if the URL is of the form"<something>://...", the text before the://is treated as the scheme, even if it's a made-up scheme that the module doesn't know about. This change may break code that worked around the old behaviour. For example, Python 2.6.4 or 2.5 will return the following:>>> import urlparse >>> urlparse.urlsplit('invented://host/filename?query') ('invented', '', '//host/filename?query', '', '')
Python 2.7 (and Python 2.6.5) will return:
>>> import urlparse >>> urlparse.urlsplit('invented://host/filename?query') ('invented', 'host', '/filename?query', '', '')
(Python 2.7 actually produces slightly different output, since it returns a named tuple instead of a standard tuple.)
For C extensions:
- C extensions that use integer format codes with the
PyArg_Parse*family of functions will now raise aTypeErrorexception instead of triggering aDeprecationWarning(5080). - Use the new
PyOS_string_to_doublefunction instead of the old!PyOS_ascii_strtodand!PyOS_ascii_atoffunctions, which are now deprecated.
For applications that embed Python:
- The
!PySys_SetArgvExfunction was added, letting applications close a security hole when the existing!PySys_SetArgvfunction was used. Check whether you're calling!PySys_SetArgvand carefully consider whether the application should be using!PySys_SetArgvExwith updatepath set to false.
New Features Added to Python 2.7 Maintenance Releases
New features may be added to Python 2.7 maintenance releases when the situation genuinely calls for it. Any such additions must go through the Python Enhancement Proposal process, and make a compelling case for why they can't be adequately addressed by either adding the new feature solely to Python 3, or else by publishing it on the Python Package Index.
In addition to the specific proposals listed below, there is a general exemption allowing new -3 warnings to be added in any Python 2.7 maintenance release.
Two new environment variables for debug mode
In debug mode, the [xxx refs] statistic is not written by default, the !PYTHONSHOWREFCOUNT environment variable now must also be set. (Contributed by Victor Stinner; 31733.)
When Python is compiled with COUNT_ALLOC defined, allocation counts are no longer dumped by default anymore: the !PYTHONSHOWALLOCCOUNT environment variable must now also be set. Moreover, allocation counts are now dumped into stderr, rather than stdout. (Contributed by Victor Stinner; 31692.)
2.7.15
PEP 434: IDLE Enhancement Exception for All Branches
434 describes a general exemption for changes made to the IDLE development environment shipped along with Python. This exemption makes it possible for the IDLE developers to provide a more consistent user experience across all supported versions of Python 2 and 3.
For details of any IDLE changes, refer to the NEWS file for the specific release.
PEP 466: Network Security Enhancements for Python 2.7
466 describes a number of network security enhancement proposals that have been approved for inclusion in Python 2.7 maintenance releases, with the first of those changes appearing in the Python 2.7.7 release.
hmac.compare_digestwas backported from Python 3 to make a timing attack resistant comparison operation available to Python 2 applications. (Contributed by Alex Gaynor;21306.)- OpenSSL 1.0.1g was upgraded in the official Windows installers published on python.org. (Contributed by Zachary Ware;
21462.)
hashlib.pbkdf2_hmacwas backported from Python 3 to make a hashing algorithm suitable for secure password storage broadly available to Python 2 applications. (Contributed by Alex Gaynor;21304.)- OpenSSL 1.0.1h was upgraded for the official Windows installers published on python.org. (Contributed by Zachary Ware in
21671for2014-0224.)
-
Most of Python 3.4's
sslmodule was backported. This meanssslnow supports Server Name Indication, TLS1.x settings, access to the platform certificate store, the~ssl.SSLContextclass, and other features. (Contributed by Alex Gaynor and David Reid;21308.)Refer to the "Version added: 2.7.9" notes in the module documentation for specific details.
-
os.urandomwas changed to cache a file descriptor to/dev/urandominstead of reopening/dev/urandomon every call. (Contributed by Alex Gaynor;21305.) -
hashlib.algorithms_guaranteedandhashlib.algorithms_availablewere backported from Python 3 to make it easier for Python 2 applications to select the strongest available hash algorithm. (Contributed by Alex Gaynor in21307)
PEP 477: Backport ensurepip (PEP 453) to Python 2.7
477 approves the inclusion of the 453 ensurepip module and the improved documentation that was enabled by it in the Python 2.7 maintenance releases, appearing first in the Python 2.7.9 release.
Bootstrapping pip By Default
The new ensurepip module (defined in 453) provides a standard cross-platform mechanism to bootstrap the pip installer into Python installations. The version of pip included with Python 2.7.9 is pip 1.5.6, and future 2.7.x maintenance releases will update the bundled version to the latest version of pip that is available at the time of creating the release candidate.
By default, the commands pip, pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.
For CPython source builds on POSIX systems <building-python-on-unix>, the make install and make altinstall commands do not bootstrap pip by default. This behaviour can be controlled through configure options, and overridden through Makefile options.
On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip.
As discussed in the PEP <0477#disabling-ensurepip-by-downstream-distributors>, platform packagers may choose not to install these commands by default, as long as, when invoked, they provide clear and simple directions on how to install them on that platform (usually using the system package manager).
Documentation Changes
As part of this change, the installing-index and distributing-index sections of the documentation have been completely redesigned as short getting started and FAQ documents. Most packaging documentation has now been moved out to the Python Packaging Authority maintained Python Packaging User Guide and the documentation of the individual projects.
However, as this migration is currently still incomplete, the legacy versions of those guides remaining available as install-index and setuptools-index.
453 -- Explicit bootstrapping of pip in Python installations
PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.
PEP 476: Enabling certificate verification by default for stdlib http clients
476 updated httplib <http> and modules which use it, such as urllib2 <urllib.request> and xmlrpclib <xmlrpc.client>, to now verify that the server presents a certificate which is signed by a Certificate Authority in the platform trust store and whose hostname matches the hostname being requested by default, significantly improving security for many applications. This change was made in the Python 2.7.9 release.
For applications which require the old previous behavior, they can pass an alternate context:
import urllib2
import ssl
# This disables all verification
context = ssl._create_unverified_context()
# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")
urllib2.urlopen("https://invalid-cert", context=context)
PEP 493: HTTPS verification migration tools for Python 2.7
493 provides additional migration tools to support a more incremental infrastructure upgrade process for environments containing applications and services relying on the historically permissive processing of server certificates when establishing client HTTPS connections. These additions were made in the Python 2.7.12 release.
These tools are intended for use in cases where affected applications and services can't be modified to explicitly pass a more permissive SSL context when establishing the connection.
For applications and services which can't be modified at all, the new PYTHONHTTPSVERIFY environment variable may be set to 0 to revert an entire Python process back to the default permissive behaviour of Python 2.7.8 and earlier.
For cases where the connection establishment code can't be modified, but the overall application can be, the new !ssl._https_verify_certificates function can be used to adjust the default behaviour at runtime.
New make regen-all build target
To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.
Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).
More selective regeneration targets are also defined - see Makefile.pre.in for details.
(Contributed by Victor Stinner in 23404.)
2.7.14
Removal of make touch build target
The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.
It has been replaced by the new make regen-all target.
(Contributed by Victor Stinner in 23404.)
2.7.14
Acknowledgements
What's New In Python 3.0
This article explains the new features in Python 3.0, compared to 2.6. Python 3.0, also known as "Python 3000" or "Py3K", is the first ever intentionally backwards incompatible Python release. Python 3.0 was released on December 3, 2008. There are more changes than in a typical release, and more that are important for all Python users. Nevertheless, after digesting the changes, you'll find that Python really hasn't changed all that much -- by and large, we're mostly fixing well-known annoyances and warts, and removing a lot of old cruft.
This article doesn't attempt to provide a complete specification of all new features, but instead tries to give a convenient overview. For full details, you should refer to the documentation for Python 3.0, and/or the many PEPs referenced in the text. If you want to understand the complete implementation and design rationale for a particular feature, PEPs usually have more details than the regular documentation; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented.
Due to time constraints this document is not as complete as it should have been. As always for a new release, the Misc/NEWS file in the source distribution contains a wealth of detailed information about every small thing that was changed.
Common Stumbling Blocks
This section lists those few changes that are most likely to trip you up if you're used to Python 2.5.
Print Is A Function
The print statement has been replaced with a print function, with keyword arguments to replace most of the special syntax of the old print statement (3105). Examples:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
You can also customize the separator between items, e.g.:
print("There are <", 2**32, "> possibilities!", sep="")
which produces:
There are <4294967296> possibilities!
Note:
- The
printfunction doesn't support the "softspace" feature of the oldprintstatement. For example, in Python 2.x,print "A\n", "B"would write"A\nB\n"; but in Python 3.0,print("A\n", "B")writes"A\n B\n". - Initially, you'll be finding yourself typing the old
print xa lot in interactive mode. Time to retrain your fingers to typeprint(x)instead! - When using the
2to3source-to-source conversion tool, allprintstatements are automatically converted toprintfunction calls, so this is mostly a non-issue for larger projects.
Views And Iterators Instead Of Lists
Some well-known APIs no longer return lists:
-
dictmethodsdict.keys,dict.itemsanddict.valuesreturn "views" instead of lists. For example, this no longer works:k = d.keys(); k.sort(). Usek = sorted(d)instead (this works in Python 2.5 too and is just as efficient). -
Also, the
!dict.iterkeys,!dict.iteritemsand!dict.itervaluesmethods are no longer supported. -
mapandfilterreturn iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrapmapinlist, e.g.list(map(...)), but a better fix is often to use a list comprehension (especially when the original code useslambda), or rewriting the code so it doesn't need a list at all. Particularly tricky ismapinvoked for the side effects of the function; the correct transformation is to use a regularforloop (since creating a list would just be wasteful).If the input sequences are not of equal length,
mapwill stop at the termination of the shortest of the sequences. For full compatibility withmapfrom Python 2.x, also wrap the sequences initertools.zip_longest, e.g.map(func, *sequences)becomeslist(map(func, itertools.zip_longest(*sequences))). -
rangenow behaves like!xrangeused to behave, except it works with values of arbitrary size. The latter no longer exists. -
zipnow returns an iterator.
Ordering Comparisons
Python 3.0 has simplified the rules for ordering comparisons:
- The ordering comparison operators (
<,<=,>=,>) raise a TypeError exception when the operands don't have a meaningful natural ordering. Thus, expressions like1 < '',0 > Noneorlen <= lenare no longer valid, and e.g.None < NoneraisesTypeErrorinstead of returningFalse. A corollary is that sorting a heterogeneous list no longer makes sense -- all the elements must be comparable to each other. Note that this does not apply to the==and!=operators: objects of different incomparable types always compare unequal to each other. sortedandlist.sortno longer accept the cmp argument providing a comparison function. Use the key argument instead. N.B. the key and reverse arguments are now "keyword-only".- The
!cmpfunction should be treated as gone, and the!__cmp__special method is no longer supported. Use~object.__lt__for sorting,~object.__eq__with~object.__hash__, and other rich comparisons as needed. (If you really need the!cmpfunctionality, you could use the expression(a > b) - (a < b)as the equivalent forcmp(a, b).)
Integers
237: Essentially,!longrenamed toint. That is, there is only one built-in integral type, namedint; but it behaves mostly like the old!longtype.238: An expression like1/2returns a float. Use1//2to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)- The
!sys.maxintconstant was removed, since there is no longer a limit to the value of integers. However,sys.maxsizecan be used as an integer larger than any practical list or string index. It conforms to the implementation's "natural" integer size and is typically the same as!sys.maxintin previous releases on the same platform (assuming the same build options). - The
reprof a long integer doesn't include the trailingLanymore, so code that unconditionally strips that character will chop off the last digit instead. (Usestrinstead.) - Octal literals are no longer of the form
0720; use0o720instead.
Text Vs. Data Instead Of Unicode Vs. 8-bit
Everything you thought you knew about binary data and Unicode has changed.
- Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is
str, the type used to hold data isbytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raisesTypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would getUnicodeDecodeErrorif it contained non-ASCII values. This value-specific behavior has caused numerous sad faces over the years. - As a consequence of this change in philosophy, pretty much all code that uses Unicode, encodings or binary data most likely has to change. The change is for the better, as in the 2.x world there were numerous bugs having to do with mixing encoded and unencoded text. To be prepared in Python 2.x, start using
!unicodefor all unencoded text, andstrfor binary or encoded data only. Then the2to3tool will do most of the work for you. - You can no longer use
u"..."literals for Unicode text. However, you must useb"..."literals for binary data. - As the
strandbytestypes cannot be mixed, you must always explicitly convert between them. Usestr.encodeto go fromstrtobytes, andbytes.decodeto go frombytestostr. You can also usebytes(s, encoding=...)andstr(b, encoding=...), respectively. - Like
str, thebytestype is immutable. There is a separate mutable type to hold buffered binary data,bytearray. Nearly all APIs that acceptbytesalso acceptbytearray. The mutable API is based oncollections.MutableSequence <collections.abc.MutableSequence>. - All backslashes in raw string literals are interpreted literally. This means that
'\U'and'\u'escapes in raw strings are not treated specially. For example,r'\u20ac'is a string of 6 characters in Python 3.0, whereas in 2.6,ur'\u20ac'was the single "euro" character. (Of course, this change only affects raw string literals; the euro character is'\u20ac'in Python 3.0.) - The built-in
!basestringabstract type was removed. Usestrinstead. Thestrandbytestypes don't have functionality enough in common to warrant a shared base class. The2to3tool (see below) replaces every occurrence of!basestringwithstr. - Files opened as text files (still the default mode for
open) always use an encoding to map between strings (in memory) and bytes (on disk). Binary files (opened with abin the mode argument) always use bytes in memory. This means that if a file is opened using an incorrect mode or encoding, I/O will likely fail loudly, instead of silently producing incorrect data. It also means that even Unix users will have to specify the correct mode (text or binary) when opening a file. There is a platform-dependent default encoding, which on Unixy platforms can be set with theLANGenvironment variable (and sometimes also with some other platform-specific locale-related environment variables). In many cases, but not all, the system default is UTF-8; you should never count on this default. Any application reading or writing more than pure ASCII text should probably have a way to override the encoding. There is no longer any need for using the encoding-aware streams in thecodecsmodule. - The initial values of
sys.stdin,sys.stdoutandsys.stderrare now unicode-only text files (i.e., they are instances ofio.TextIOBase). To read and write bytes data with these streams, you need to use theirio.TextIOBase.bufferattribute. - Filenames are passed to and returned from APIs as (Unicode) strings. This can present platform-specific problems because on some platforms filenames are arbitrary byte strings. (On the other hand, on Windows filenames are natively stored as Unicode.) As a work-around, most APIs (e.g.
openand many functions in theosmodule) that take filenames acceptbytesobjects as well as strings, and a few APIs have a way to ask for abytesreturn value. Thus,os.listdirreturns a list ofbytesinstances if the argument is abytesinstance, andos.getcwdbreturns the current working directory as abytesinstance. Note that whenos.listdirreturns a list of strings, filenames that cannot be decoded properly are omitted rather than raisingUnicodeError. - Some system APIs like
os.environandsys.argvcan also present problems when the bytes made available by the system is not interpretable using the default encoding. Setting theLANGvariable and rerunning the program is probably the best approach. 3138: Thereprof a string no longer escapes non-ASCII characters. It still escapes control characters and code points with non-printable status in the Unicode standard, however.3120: The default source encoding is now UTF-8.3131: Non-ASCII letters are now allowed in identifiers. (However, the standard library remains ASCII-only with the exception of contributor names in comments.)- The
!StringIOand!cStringIOmodules are gone. Instead, import theiomodule and useio.StringIOorio.BytesIOfor text and data respectively. - See also the
unicode-howto, which was updated for Python 3.0.
Overview Of Syntax Changes
This section gives a brief overview of every syntactic change in Python 3.0.
New Syntax
-
3107: Function argument and return value annotations. This provides a standardized way of annotating a function's parameters and return value. There are no semantics attached to such annotations except that they can be introspected at runtime using the~object.__annotations__attribute. The intent is to encourage experimentation through metaclasses, decorators or frameworks. -
3102: Keyword-only arguments. Named parameters occurring after*argsin the parameter list must be specified using keyword syntax in the call. You can also use a bare*in the parameter list to indicate that you don't accept a variable-length argument list, but you do have keyword-only arguments. -
Keyword arguments are allowed after the list of base classes in a class definition. This is used by the new convention for specifying a metaclass (see next section), but can be used for other purposes as well, as long as the metaclass supports it.
-
3104:nonlocalstatement. Usingnonlocal xyou can now assign directly to a variable in an outer (but non-global) scope.!nonlocalis a new reserved word. -
3132: Extended Iterable Unpacking. You can now write things likea, b, *rest = some_sequence. And even*rest, a = stuff. Therestobject is always a (possibly empty) list; the right-hand side may be any iterable. Example:(a, *rest, b) = range(5)This sets a to
0, b to4, and rest to[1, 2, 3]. -
Dictionary comprehensions:
{k: v for k, v in stuff}means the same thing asdict(stuff)but is more flexible. (This is274vindicated. :-) -
Set literals, e.g.
{1, 2}. Note that{}is an empty dictionary; useset()for an empty set. Set comprehensions are also supported; e.g.,{x for x in stuff}means the same thing asset(stuff)but is more flexible. -
New octal literals, e.g.
0o720(already in 2.6). The old octal literals (0720) are gone. -
New binary literals, e.g.
0b1010(already in 2.6), and there is a new corresponding built-in function,bin. -
Bytes literals are introduced with a leading
borB, and there is a new corresponding built-in function,bytes.
Changed Syntax
-
3109and3134: newraisestatement syntax:raise [{expr} [from {expr}]]. See below. -
!asandwithare now reserved words. (Since 2.6, actually.) -
True,False, andNoneare reserved words. (2.6 partially enforced the restrictions onNonealready.) -
Change from
exceptexc, var to!exceptexc!asvar. See3110. -
3115: New Metaclass Syntax. Instead of:class C: __metaclass__ = M ...you must now use:
class C(metaclass=M): ...The module-global
!__metaclass__variable is no longer supported. (It was a crutch to make it easier to default to new-style classes without deriving every class fromobject.) -
List comprehensions no longer support the syntactic form
[... for {var} in {item1}, {item2}, ...]. Use[... for {var} in ({item1}, {item2}, ...)]instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside alistconstructor, and in particular the loop control variables are no longer leaked into the surrounding scope. -
The ellipsis (
...) can be used as an atomic expression anywhere. (Previously it was only allowed in slices.) Also, it must now be spelled as.... (Previously it could also be spelled as. . ., by a mere accident of the grammar.)
Removed Syntax
3113: Tuple parameter unpacking removed. You can no longer writedef foo(a, (b, c)): .... Usedef foo(a, b_c): b, c = b_cinstead.- Removed backticks (use
reprinstead). - Removed
<>(use!=instead). - Removed keyword:
execis no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) Also note thatexecno longer takes a stream argument; instead ofexec(f)you can useexec(f.read()). - Integer literals no longer support a trailing
lorL. - String literals no longer support a leading
uorU. - The
frommoduleimport*syntax is only allowed at the module level, no longer inside functions. - The only acceptable syntax for relative imports is
from .[{module}] import {name}. Allimportforms not starting with.are interpreted as absolute imports. (328) - Classic classes are gone.
Changes Already Present In Python 2.6
Since many users presumably make the jump straight from Python 2.5 to Python 3.0, this section reminds the reader of new features that were originally designed for Python 3.0 but that were back-ported to Python 2.6. The corresponding sections in whats-new-in-2.6 should be consulted for longer descriptions.
pep-0343. Thewithstatement is now a standard feature and no longer needs to be imported from the__future__. Also check outnew-26-context-managersandnew-module-contextlib.pep-0366. This enhances the usefulness of the-moption when the referenced module lives in a package.pep-0370.pep-0371.pep-3101. Note: the 2.6 description mentions theformatmethod for both 8-bit and Unicode strings. In 3.0, only thestrtype (text strings with Unicode support) supports this method; thebytestype does not. The plan is to eventually make this the only API for string formatting, and to start deprecating the%operator in Python 3.1.pep-3105. This is now a standard feature and no longer needs to be imported from__future__. More details were given above.pep-3110. Theexceptexc!asvar syntax is now standard and!exceptexc, var is no longer supported. (Of course, the!asvar part is still optional.)pep-3112. Theb"..."string literal notation (and its variants likeb'...',b"""...""", andbr"...") now produces a literal of typebytes.pep-3116. Theiomodule is now the standard way of doing file I/O. The built-inopenfunction is now an alias forio.openand has additional keyword arguments encoding, errors, newline and closefd. Also note that an invalid mode argument now raisesValueError, notIOError. The binary file object underlying a text file object can be accessed as!f.buffer(but beware that the text object maintains a buffer of itself in order to speed up the encoding and decoding operations).pep-3118. The old builtin!bufferis now really gone; the new builtinmemoryviewprovides (mostly) similar functionality.pep-3119. Theabcmodule and the ABCs defined in thecollectionsmodule plays a somewhat more prominent role in the language now, and built-in collection types likedictandlistconform to thecollections.MutableMapping <collections.abc.MutableMapping>andcollections.MutableSequence <collections.abc.MutableSequence>ABCs, respectively.pep-3127. As mentioned above, the new octal literal notation is the only one supported, and binary literals have been added.pep-3129.pep-3141. Thenumbersmodule is another new use of ABCs, defining Python's "numeric tower". Also note the newfractionsmodule which implementsnumbers.Rational.
Library Changes
Due to time constraints, this document does not exhaustively cover the very extensive changes to the standard library. 3108 is the reference for the major changes to the library. Here's a capsule review:
-
Many old modules were removed. Some, like
!gopherlib(no longer used) and!md5(replaced byhashlib), were already deprecated by4. Others were removed as a result of the removal of support for various platforms such as Irix, BeOS and Mac OS 9 (see11). Some modules were also selected for removal in Python 3.0 due to lack of use or because a better replacement exists. See3108for an exhaustive list. -
The
!bsddb3package was removed because its presence in the core standard library has proved over time to be a particular burden for the core developers due to testing instability and Berkeley DB's release schedule. However, the package is alive and well, externally maintained at https://www.jcea.es/programacion/pybsddb.htm. -
Some modules were renamed because their old name disobeyed
8, or for various other reasons. Here's the list:Old Name New Name winreg winreg ConfigParser configparser copy_reg copyreg Queue queue SocketServer socketserver markupbase markupbase repr reprlib test.test_support test.support -
A common pattern in Python 2.x is to have one version of a module implemented in pure Python, with an optional accelerated version implemented as a C extension; for example,
pickleand!cPickle. This places the burden of importing the accelerated version and falling back on the pure Python version on each user of these modules. In Python 3.0, the accelerated versions are considered implementation details of the pure Python versions. Users should always import the standard version, which attempts to import the accelerated version and falls back to the pure Python version. Thepickle/!cPicklepair received this treatment. Theprofilemodule is on the list for 3.1. The!StringIOmodule has been turned into a class in theiomodule. -
Some related modules have been grouped into packages, and usually the submodule names have been simplified. The resulting new packages are:
dbm(!anydbm,!dbhash,!dbm,!dumbdbm,!gdbm,!whichdb).html(!HTMLParser,!htmlentitydefs).http(!httplib,!BaseHTTPServer,!CGIHTTPServer,!SimpleHTTPServer,!Cookie,!cookielib).tkinter(allTkinter-related modules exceptturtle). The target audience ofturtledoesn't really care abouttkinter. Also note that as of Python 2.6, the functionality ofturtlehas been greatly enhanced.urllib(!urllib,!urllib2,!urlparse,!robotparse).xmlrpc(!xmlrpclib,!DocXMLRPCServer,!SimpleXMLRPCServer).
Some other changes to standard library modules, not covered by 3108:
- Killed
!sets. Use the built-insetclass. - Cleanup of the
sysmodule: removed!sys.exitfunc,!sys.exc_clear,!sys.exc_type,!sys.exc_value,!sys.exc_traceback. (Note thatsys.last_typeetc. remain.) - Cleanup of the
array.arraytype: the!readand!writemethods are gone; use~array.array.fromfileand~array.array.tofileinstead. Also, the'c'typecode for array is gone -- use either'b'for bytes or'u'for Unicode characters. - Cleanup of the
operatormodule: removed!sequenceIncludesand!isCallable. - Cleanup of the
!threadmodule:!acquire_lockand!release_lockare gone; use~threading.Lock.acquireand~threading.Lock.releaseinstead. - Cleanup of the
randommodule: removed the!jumpaheadAPI. - The
!newmodule is gone. - The functions
!os.tmpnam,!os.tempnamand!os.tmpfilehave been removed in favor of thetempfilemodule. - The
tokenizemodule has been changed to work with bytes. The main entry point is nowtokenize.tokenize, instead of generate_tokens. !string.lettersand its friends (!string.lowercaseand!string.uppercase) are gone. Usestring.ascii_lettersetc. instead. (The reason for the removal is that!string.lettersand friends had locale-specific behavior, which is a bad idea for such attractively named global "constants".)- Renamed module
!__builtin__tobuiltins(removing the underscores, adding an 's'). The!__builtins__variable found in most global namespaces is unchanged. To modify a builtin, you should usebuiltins, not!__builtins__!
3101: A New Approach To String Formatting
- A new system for built-in string formatting operations replaces the
%string formatting operator. (However, the%operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read3101for the full scoop.
Changes To Exceptions
The APIs for raising and catching exception have been cleaned up and new powerful features added:
-
352: All exceptions must be derived (directly or indirectly) fromBaseException. This is the root of the exception hierarchy. This is not new as a recommendation, but the requirement to inherit fromBaseExceptionis new. (Python 2.6 still allowed classic classes to be raised, and placed no restriction on what you can catch.) As a consequence, string exceptions are finally truly and utterly dead. -
Almost all exceptions should actually derive from
Exception;BaseExceptionshould only be used as a base class for exceptions that should only be handled at the top level, such asSystemExitorKeyboardInterrupt. The recommended idiom for handling all exceptions except for this latter category is to useexceptException. -
!StandardErrorwas removed. -
Exceptions no longer behave as sequences. Use the
~BaseException.argsattribute instead. -
3109: Raising exceptions. You must now useraise {Exception}({args})instead ofraise {Exception}, {args}. Additionally, you can no longer explicitly specify a traceback; instead, if you have to do this, you can assign directly to the~BaseException.__traceback__attribute (see below). -
3110: Catching exceptions. You must now useexcept {SomeException} as {variable}instead ofexcept {SomeException}, {variable}. Moreover, the variable is explicitly deleted when theexceptblock is left. -
3134: Exception chaining. There are two cases: implicit chaining and explicit chaining. Implicit chaining happens when an exception is raised in anexceptorfinallyhandler block. This usually happens due to a bug in the handler block; we call this a secondary exception. In this case, the original exception (that was being handled) is saved as the~BaseException.__context__attribute of the secondary exception. Explicit chaining is invoked with this syntax:raise SecondaryException() from primary_exception(where primary_exception is any expression that produces an exception object, probably an exception that was previously caught). In this case, the primary exception is stored on the
~BaseException.__cause__attribute of the secondary exception. The traceback printed when an unhandled exception occurs walks the chain of!__cause__and~BaseException.__context__attributes and prints a separate traceback for each component of the chain, with the primary exception at the top. (Java users may recognize this behavior.) -
3134: Exception objects now store their traceback as the~BaseException.__traceback__attribute. This means that an exception object now contains all the information pertaining to an exception, and there are fewer reasons to usesys.exc_info(though the latter is not removed). -
A few exception messages are improved when Windows fails to load an extension module. For example,
error code 193is now%1 is not a valid Win32 application. Strings now deal with non-English locales.
Miscellaneous Other Changes
Operators And Special Methods
!=now returns the opposite of==, unless==returnsNotImplemented.- The concept of "unbound methods" has been removed from the language. When referencing a method as a class attribute, you now get a plain function object.
!__getslice__,!__setslice__and!__delslice__were killed. The syntaxa[i:j]now translates toa.__getitem__(slice(i, j))(or~object.__setitem__or~object.__delitem__, when used as an assignment or deletion target, respectively).3114: the standardnextmethod has been renamed to~iterator.__next__.- The
!__oct__and!__hex__special methods are removed --octandhexuse~object.__index__now to convert the argument to an integer. - Removed support for
!__members__and!__methods__. - The function attributes named
!func_Xhave been renamed to use the!__X__form, freeing up these names in the function attribute namespace for user-defined attributes. To wit,!func_closure,!func_code,!func_defaults,!func_dict,!func_doc,!func_globals,!func_namewere renamed to~function.__closure__,~function.__code__,~function.__defaults__,~function.__dict__,~function.__doc__,~function.__globals__,~function.__name__, respectively. !__nonzero__is now~object.__bool__.
Builtins
3135: Newsuper. You can now invokesuperwithout arguments and (assuming this is in a regular instance method defined inside aclassstatement) the right class and instance will automatically be chosen. With arguments, the behavior ofsuperis unchanged.3111:!raw_inputwas renamed toinput. That is, the newinputfunction reads a line fromsys.stdinand returns it with the trailing newline stripped. It raisesEOFErrorif the input is terminated prematurely. To get the old behavior ofinput, useeval(input()).- A new built-in function
nextwas added to call the~iterator.__next__method on an object. - The
roundfunction rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example,round(2.5)now returns2rather than3.)round(x[, n])now delegates tox.__round__([n])instead of always returning a float. It generally returns an integer when called with a single argument and a value of the same type asxwhen called with two arguments. - Moved
!interntosys.intern. - Removed:
!apply. Instead ofapply(f, args)usef(*args). - Removed
callable. Instead ofcallable(f)you can useisinstance(f, collections.Callable). The!operator.isCallablefunction is also gone. - Removed
!coerce. This function no longer serves a purpose now that classic classes are gone. - Removed
!execfile. Instead ofexecfile(fn)useexec(open(fn).read()). - Removed the
!filetype. Useopen. There are now several different kinds of streams that open can return in theiomodule. - Removed
!reduce. Usefunctools.reduceif you really need it; however, 99 percent of the time an explicitforloop is more readable. - Removed
!reload. Use!imp.reload. - Removed.
!dict.has_key-- use theinoperator instead.
Build and C API Changes
Due to time constraints, here is a very incomplete list of changes to the C API.
- Support for several platforms was dropped, including but not limited to Mac OS 9, BeOS, RISCOS, Irix, and Tru64.
3118: New Buffer API.3121: Extension Module Initialization & Finalization.3123: MakingPyObject_HEADconform to standard C.- No more C API support for restricted execution.
!PyNumber_Coerce,!PyNumber_CoerceEx,!PyMember_Get, and!PyMember_SetC APIs are removed.- New C API
!PyImport_ImportModuleNoBlock, works likePyImport_ImportModulebut won't block on the import lock (returning an error instead). - Renamed the boolean conversion C-level slot and method:
nb_nonzerois nownb_bool. - Removed
!METH_OLDARGSand!WITH_CYCLE_GCfrom the C API.
Performance
The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There's room for improvement, but it will happen after 3.0 is released!
Porting To Python 3.0
For porting existing Python 2.5 or 2.6 source code to Python 3.0, the best strategy is the following:
- (Prerequisite:) Start with excellent test coverage.
- Port to Python 2.6. This should be no more work than the average port from Python 2.x to Python 2.(x+1). Make sure all your tests pass.
- (Still using 2.6:) Turn on the
!-3command line switch. This enables warnings about features that will be removed (or change) in 3.0. Run your test suite again, and fix code that you get warnings about until there are no warnings left, and all your tests still pass. - Run the
2to3source-to-source translator over your source code tree. Run the result of the translation under Python 3.0. Manually fix up any remaining issues, fixing problems until all tests pass again.
It is not recommended to try to write source code that runs unchanged under both Python 2.6 and 3.0; you'd have to use a very contorted coding style, e.g. avoiding print statements, metaclasses, and much more. If you are maintaining a library that needs to support both Python 2.6 and Python 3.0, the best approach is to modify step 3 above by editing the 2.6 version of the source code and running the 2to3 translator again, rather than editing the 3.0 version of the source code.
For porting C extensions to Python 3.0, please see cporting-howto.
What's New In Python 3.1
This article explains the new features in Python 3.1, compared to 3.0. Python 3.1 was released on June 27, 2009.
PEP 372: Ordered Dictionaries
Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors have written alternative implementations that remember the order that the keys were originally inserted. Based on the experiences from those implementations, a new collections.OrderedDict class has been introduced.
The OrderedDict API is substantially the same as regular dictionaries but will iterate over keys and values in a guaranteed order depending on when a key was first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
The standard library now supports use of ordered dictionaries in several modules. The configparser module uses them by default. This lets configuration files be read, modified, and then written back in their original order. The _asdict() method for collections.namedtuple now returns an ordered dictionary with the values appearing in the same order as the underlying tuple indices. The json module is being built-out with an object_pairs_hook to allow OrderedDicts to be built by the decoder. Support was also added for third-party tools like PyYAML.
372 - Ordered Dictionaries
PEP written by Armin Ronacher and Raymond Hettinger. Implementation written by Raymond Hettinger.
Since an ordered dictionary remembers its insertion order, it can be used in conjunction with sorting to make a sorted dictionary:
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.
PEP 378: Format Specifier for Thousands Separator
The built-in format function and the str.format method use a mini-language that now includes a simple, non-locale aware way to format a number with a thousands separator. That provides a way to humanize a program's output, improving its professional appearance and readability:
>>> format(1234567, ',d')
'1,234,567'
>>> format(1234567.89, ',.2f')
'1,234,567.89'
>>> format(12345.6 + 8901234.12j, ',f')
'12,345.600000+8,901,234.120000j'
>>> format(Decimal('1234567.89'), ',f')
'1,234,567.89'
The supported types are int, float, complex and decimal.Decimal.
Discussions are underway about how to specify alternative separators like dots, spaces, apostrophes, or underscores. Locale-aware applications should use the existing n format specifier which already has some support for thousands separators.
378 - Format Specifier for Thousands Separator
PEP written by Raymond Hettinger and implemented by Eric Smith and Mark Dickinson.
Other Language Changes
Some smaller changes made to the core Python language are:
-
Directories and zip archives containing a
__main__.pyfile can now be executed directly by passing their name to the interpreter. The directory/zipfile is automatically inserted as the first entry in sys.path. (Suggestion and initial patch by Andy Chu; revised patch by Phillip J. Eby and Nick Coghlan;1739468.) -
The
inttype gained abit_lengthmethod that returns the number of bits necessary to represent its argument in binary:>>> n = 37 >>> bin(37) '0b100101' >>> n.bit_length() 6 >>> n = 2**123-1 >>> n.bit_length() 123 >>> (n+1).bit_length() 124(Contributed by Fredrik Johansson, Victor Stinner, Raymond Hettinger, and Mark Dickinson;
3439.) -
The fields in
formatstrings can now be automatically numbered:>>> 'Sir {} of {}'.format('Gallahad', 'Camelot') 'Sir Gallahad of Camelot'Formerly, the string would have required numbered fields such as:
'Sir {0} of {1}'.(Contributed by Eric Smith;
5237.) -
The
!string.maketransfunction is deprecated and is replaced by new static methods,bytes.maketransandbytearray.maketrans. This change solves the confusion around which types were supported by thestringmodule. Now,str,bytes, andbytearrayeach have their own maketrans and translate methods with intermediate translation tables of the appropriate type.(Contributed by Georg Brandl;
5675.) -
The syntax of the
withstatement now allows multiple context managers in a single statement:>>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile: ... for line in infile: ... if '<critical>' in line: ... outfile.write(line)With the new syntax, the
!contextlib.nestedfunction is no longer needed and is now deprecated.(Contributed by Georg Brandl and Mattias Brändström; appspot issue 53094.)
-
round(x, n)now returns an integer if x is an integer. Previously it returned a float:>>> round(1123, -2) 1100(Contributed by Mark Dickinson;
4707.) -
Python now uses David Gay's algorithm for finding the shortest floating-point representation that doesn't change its value. This should help mitigate some of the confusion surrounding binary floating-point numbers.
The significance is easily seen with a number like
1.1which does not have an exact equivalent in binary floating point. Since there is no exact equivalent, an expression likefloat('1.1')evaluates to the nearest representable value which is0x1.199999999999ap+0in hex or1.100000000000000088817841970012523233890533447265625in decimal. That nearest value was and still is used in subsequent floating-point calculations.What is new is how the number gets displayed. Formerly, Python used a simple approach. The value of
repr(1.1)was computed asformat(1.1, '.17g')which evaluated to'1.1000000000000001'. The advantage of using 17 digits was that it relied on IEEE-754 guarantees to assure thateval(repr(1.1))would round-trip exactly to its original value. The disadvantage is that many people found the output to be confusing (mistaking intrinsic limitations of binary floating-point representation as being a problem with Python itself).The new algorithm for
repr(1.1)is smarter and returns'1.1'. Effectively, it searches all equivalent string representations (ones that get stored with the same underlying float value) and returns the shortest representation.The new algorithm tends to emit cleaner representations when possible, but it does not change the underlying values. So, it is still the case that
1.1 + 2.2 != 3.3even though the representations may suggest otherwise.The new algorithm depends on certain features in the underlying floating-point implementation. If the required features are not found, the old algorithm will continue to be used. Also, the text pickle protocols assure cross-platform portability by using the old algorithm.
(Contributed by Eric Smith and Mark Dickinson;
1580)
New, Improved, and Deprecated Modules
-
Added a
collections.Counterclass to support convenient counting of unique items in a sequence or iterable:>>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']) Counter({'blue': 3, 'red': 2, 'green': 1})(Contributed by Raymond Hettinger;
1696199.) -
Added a new module,
tkinter.ttkfor access to the Tk themed widget set. The basic idea of ttk is to separate, to the extent possible, the code implementing a widget's behavior from the code implementing its appearance.(Contributed by Guilherme Polo;
2983.) -
The
gzip.GzipFileandbz2.BZ2Fileclasses now support the context management protocol:>>> # Automatically close file after writing >>> with gzip.GzipFile(filename, "wb") as f: ... f.write(b"xxx")(Contributed by Antoine Pitrou.)
-
The
decimalmodule now supports methods for creating a decimal object from a binaryfloat. The conversion is exact but can sometimes be surprising:>>> Decimal.from_float(1.1) Decimal('1.100000000000000088817841970012523233890533447265625')The long decimal result shows the actual binary fraction being stored for 1.1. The fraction has many digits because 1.1 cannot be exactly represented in binary.
(Contributed by Raymond Hettinger and Mark Dickinson.)
-
The
itertoolsmodule grew two new functions. Theitertools.combinations_with_replacementfunction is one of four for generating combinatorics including permutations and Cartesian products. Theitertools.compressfunction mimics its namesake from APL. Also, the existingitertools.countfunction now has an optional step argument and can accept any type of counting sequence includingfractions.Fractionanddecimal.Decimal:>>> [p+q for p,q in combinations_with_replacement('LOVE', 2)] ['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE'] >>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0])) [2, 3, 5, 7] >>> c = count(start=Fraction(1,2), step=Fraction(1,6)) >>> [next(c), next(c), next(c), next(c)] [Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)](Contributed by Raymond Hettinger.)
-
collections.namedtuplenow supports a keyword argument rename which lets invalid fieldnames be automatically converted to positional names in the form 0, 1, etc. This is useful when the field names are being created by an external source such as a CSV header, SQL field list, or user input:>>> query = input() SELECT region, dept, count(*) FROM main GROUPBY region, dept >>> cursor.execute(query) >>> query_fields = [desc[0] for desc in cursor.description] >>> UserQuery = namedtuple('UserQuery', query_fields, rename=True) >>> pprint.pprint([UserQuery(*row) for row in cursor]) [UserQuery(region='South', dept='Shipping', _2=185), UserQuery(region='North', dept='Accounting', _2=37), UserQuery(region='West', dept='Sales', _2=419)](Contributed by Raymond Hettinger;
1818.) -
The
re.sub,re.subnandre.splitfunctions now accept a flags parameter.(Contributed by Gregory Smith.)
-
The
loggingmodule now implements a simplelogging.NullHandlerclass for applications that are not using logging but are calling library code that does. Setting-up a null handler will suppress spurious warnings such as "No handlers could be found for logger foo":>>> h = logging.NullHandler() >>> logging.getLogger("foo").addHandler(h)(Contributed by Vinay Sajip;
4384). -
The
runpymodule which supports the-mcommand line switch now supports the execution of packages by looking for and executing a__main__submodule when a package name is supplied.(Contributed by Andi Vajda;
4195.) -
The
pdbmodule can now access and display source code loaded viazipimport(or any other conformant302loader).(Contributed by Alexander Belopolsky;
4201.) -
functools.partialobjects can now be pickled.
(Suggested by Antoine Pitrou and Jesse Noller. Implemented by Jack Diederich;
5228.)
-
Add
pydochelp topics for symbols so thathelp('@')works as expected in the interactive environment.(Contributed by David Laban;
4739.) -
The
unittestmodule now supports skipping individual tests or classes of tests. And it supports marking a test as an expected failure, a test that is known to be broken, but shouldn't be counted as a failure on a TestResult:class TestGizmo(unittest.TestCase): @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_gizmo_on_windows(self): ... @unittest.expectedFailure def test_gimzo_without_required_library(self): ...Also, tests for exceptions have been builtout to work with context managers using the
withstatement:def test_division_by_zero(self): with self.assertRaises(ZeroDivisionError): x / 0In addition, several new assertion methods were added including
~unittest.TestCase.assertSetEqual,~unittest.TestCase.assertDictEqual,!assertDictContainsSubset,~unittest.TestCase.assertListEqual,~unittest.TestCase.assertTupleEqual,~unittest.TestCase.assertSequenceEqual,assertRaisesRegexp() <unittest.TestCase.assertRaisesRegex>,~unittest.TestCase.assertIsNone, and~unittest.TestCase.assertIsNotNone.(Contributed by Benjamin Peterson and Antoine Pitrou.)
-
The
iomodule has three new constants for the~io.IOBase.seekmethod:~os.SEEK_SET,~os.SEEK_CUR, and~os.SEEK_END. -
The
sys.version_infotuple is now a named tuple:>>> sys.version_info sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)(Contributed by Ross Light;
4285.) -
The
!nntplibandimaplibmodules now support IPv6.(Contributed by Derek Morr;
1655and1664.) -
The
picklemodule has been adapted for better interoperability with Python 2.x when used with protocol 2 or lower. The reorganization of the standard library changed the formal reference for many objects. For example,__builtin__.setin Python 2 is calledbuiltins.setin Python3. This change confounded efforts to share data between different versions of Python. But now when protocol 2 or lower is selected, the pickler will automatically use the old Python 2 names for both loading and dumping. This remapping is turned-on by default but can be disabled with the fix_imports option:
>>> s = {1, 2, 3} >>> pickle.dumps(s, protocol=0) b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.' >>> pickle.dumps(s, protocol=0, fix_imports=False) b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'An unfortunate but unavoidable side-effect of this change is that protocol 2 pickles produced by Python 3.1 won't be readable with Python 3.0. The latest pickle protocol, protocol 3, should be used when migrating data between Python 3.x implementations, as it doesn't attempt to remain compatible with Python 2.x.
(Contributed by Alexandre Vassalotti and Antoine Pitrou,
6137.) -
A new module,
importlibwas added. It provides a complete, portable, pure Python reference implementation of theimportstatement and its counterpart, the__import__function. It represents a substantial step forward in documenting and defining the actions that take place during imports.(Contributed by Brett Cannon.)
Optimizations
Major performance enhancements have been added:
-
The new I/O library (as defined in
3116) was mostly written in Python and quickly proved to be a problematic bottleneck in Python 3.0. In Python 3.1, the I/O library has been entirely rewritten in C and is 2 to 20 times faster depending on the task at hand. The pure Python version is still available for experimentation purposes through the_pyiomodule.(Contributed by Amaury Forgeot d'Arc and Antoine Pitrou.)
-
Added a heuristic so that tuples and dicts containing only untrackable objects are not tracked by the garbage collector. This can reduce the size of collections and therefore the garbage collection overhead on long-running programs, depending on their particular use of datatypes.
(Contributed by Antoine Pitrou,
4688.) -
Enabling a configure option named
--with-computed-gotoson compilers that support it (notably: gcc, SunPro, icc), the bytecode evaluation loop is compiled with a new dispatch mechanism which gives speedups of up to 20%, depending on the system, the compiler, and the benchmark.(Contributed by Antoine Pitrou along with a number of other participants,
4753). -
The decoding of UTF-8, UTF-16 and LATIN-1 is now two to four times faster.
(Contributed by Antoine Pitrou and Amaury Forgeot d'Arc,
4868.) -
The
jsonmodule now has a C extension to substantially improve its performance. In addition, the API was modified so that json works only withstr, not withbytes. That change makes the module closely match the JSON specification which is defined in terms of Unicode.(Contributed by Bob Ippolito and converted to Py3.1 by Antoine Pitrou and Benjamin Peterson;
4136.) -
Unpickling now interns the attribute names of pickled objects. This saves memory and allows pickles to be smaller.
(Contributed by Jake McGuire and Antoine Pitrou;
5084.)
IDLE
Build and C API Changes
Changes to Python's build process and to the C API include:
-
Integers are now stored internally either in base
2**15or in base2**30, the base being determined at build time. Previously, they were always stored in base2**15. Using base2**30gives significant performance improvements on 64-bit machines, but benchmark results on 32-bit machines have been mixed. Therefore, the default is to use base2**30on 64-bit machines and base2**15on 32-bit machines; on Unix, there's a new configure option--enable-big-digitsthat can be used to override this default.Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there's a new
sys.int_infothat provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:>>> import sys >>> sys.int_info sys.int_info(bits_per_digit=30, sizeof_digit=4)(Contributed by Mark Dickinson;
4258.) -
The
PyLong_AsUnsignedLongLong()function now handles a negative pylong by raisingOverflowErrorinstead ofTypeError.(Contributed by Mark Dickinson and Lisandro Dalcrin;
5175.) -
Deprecated
!PyNumber_Int. UsePyNumber_Longinstead.(Contributed by Mark Dickinson;
4910.) -
Added a new
PyOS_string_to_doublefunction to replace the deprecated functions!PyOS_ascii_strtodand!PyOS_ascii_atof.(Contributed by Mark Dickinson;
5914.) -
Added
PyCapsuleas a replacement for the!PyCObjectAPI. The principal difference is that the new type has a well defined interface for passing typing safety information and a less complicated signature for calling a destructor. The old type had a problematic API and is now deprecated.(Contributed by Larry Hastings;
5630.)
Porting to Python 3.1
This section lists previously described changes and other bugfixes that may require changes to your code:
-
The new floating-point string representations can break existing doctests. For example:
def e(): '''Compute the base of natural logarithms. >>> e() 2.7182818284590451 ''' return sum(1/math.factorial(x) for x in reversed(range(30))) doctest.testmod() ********************************************************************** Failed example: e() Expected: 2.7182818284590451 Got: 2.718281828459045 ********************************************************************** -
The automatic name remapping in the pickle module for protocol 2 or lower can make Python 3.1 pickles unreadable in Python 3.0. One solution is to use protocol 3. Another solution is to set the fix_imports option to
False. See the discussion above for more details.
What's New In Python 3.10
Editor
Pablo Galindo Salgado
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the git log when researching a change.
This article explains the new features in Python 3.10, compared to 3.9. Python 3.10 was released on October 4, 2021. For full details, see the changelog <changelog>.
Summary -- Release highlights
New syntax features:
634, Structural Pattern Matching: Specification635, Structural Pattern Matching: Motivation and Rationale636, Structural Pattern Matching: Tutorial12782, Parenthesized context managers are now officially allowed.
New features in the standard library:
618, Add Optional Length-Checking To zip.
Interpreter improvements:
626, Precise line numbers for debugging and other tools.
New typing features:
604, Allow writing union types as X | Y612, Parameter Specification Variables613, Explicit Type Aliases647, User-Defined Type Guards
Important deprecations, removals or restrictions:
644, Require OpenSSL 1.1.1 or newer632, Deprecate distutils module.623, Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.624, Remove Py_UNICODE encoder APIs597, Add optional EncodingWarning
New Features
Parenthesized context managers
Using enclosing parentheses for continuation across multiple lines in context managers is now supported. This allows formatting a long collection of context managers in multiple lines in a similar way as it was previously possible with import statements. For instance, all these examples are now valid:
with (CtxManager() as example):
...
with (
CtxManager1(),
CtxManager2()
):
...
with (CtxManager1() as example,
CtxManager2()):
...
with (CtxManager1(),
CtxManager2() as example):
...
with (
CtxManager1() as example1,
CtxManager2() as example2
):
...
it is also possible to use a trailing comma at the end of the enclosed group:
with (
CtxManager1() as example1,
CtxManager2() as example2,
CtxManager3() as example3,
):
...
This new syntax uses the non LL(1) capacities of the new parser. Check 617 for more details.
(Contributed by Guido van Rossum, Pablo Galindo and Lysandros Nikolaou in 12782 and 40334.)
Better error messages
SyntaxErrors
When parsing code that contains unclosed parentheses or brackets the interpreter now includes the location of the unclosed bracket of parentheses instead of displaying SyntaxError: unexpected EOF while parsing or pointing to some incorrect location. For instance, consider the following code (notice the unclosed '{'):
expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()
Previous versions of the interpreter reported confusing places as the location of the syntax error:
File "example.py", line 3
some_other_code = foo()
^
SyntaxError: invalid syntax
but in Python 3.10 a more informative error is emitted:
File "example.py", line 1
expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
^
SyntaxError: '{' was never closed
In a similar way, errors involving unclosed string literals (single and triple quoted) now point to the start of the string instead of reporting EOF/EOL.
These improvements are inspired by previous work in the PyPy interpreter.
(Contributed by Pablo Galindo in 42864 and Batuhan Taskaya in 40176.)
SyntaxError exceptions raised by the interpreter will now highlight the full error range of the expression that constitutes the syntax error itself, instead of just where the problem is detected. In this way, instead of displaying (before Python 3.10):
>>> foo(x, z for z in range(10), t, w)
File "<stdin>", line 1
foo(x, z for z in range(10), t, w)
^
SyntaxError: Generator expression must be parenthesized
now Python 3.10 will display the exception as:
>>> foo(x, z for z in range(10), t, w)
File "<stdin>", line 1
foo(x, z for z in range(10), t, w)
^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized
This improvement was contributed by Pablo Galindo in 43914.
A considerable amount of new specialized messages for SyntaxError exceptions have been incorporated. Some of the most notable ones are as follows:
-
Missing
:before blocks:>>> if rocket.position > event_horizon File "<stdin>", line 1 if rocket.position > event_horizon ^ SyntaxError: expected ':'(Contributed by Pablo Galindo in
42997.) -
Unparenthesised tuples in comprehensions targets:
>>> {x,y for x,y in zip('abcd', '1234')} File "<stdin>", line 1 {x,y for x,y in zip('abcd', '1234')} ^ SyntaxError: did you forget parentheses around the comprehension target?(Contributed by Pablo Galindo in
43017.) -
Missing commas in collection literals and between expressions:
>>> items = { ... x: 1, ... y: 2 ... z: 3, File "<stdin>", line 3 y: 2 ^ SyntaxError: invalid syntax. Perhaps you forgot a comma?(Contributed by Pablo Galindo in
43822.) -
Multiple Exception types without parentheses:
>>> try: ... build_dyson_sphere() ... except NotEnoughScienceError, NotEnoughResourcesError: File "<stdin>", line 3 except NotEnoughScienceError, NotEnoughResourcesError: ^ SyntaxError: multiple exception types must be parenthesized(Contributed by Pablo Galindo in
43149.) -
Missing
:and values in dictionary literals:>>> values = { ... x: 1, ... y: 2, ... z: ... } File "<stdin>", line 4 z: ^ SyntaxError: expression expected after dictionary key and ':' >>> values = {x:1, y:2, z w:3} File "<stdin>", line 1 values = {x:1, y:2, z w:3} ^ SyntaxError: ':' expected after dictionary key(Contributed by Pablo Galindo in
43823.) -
tryblocks withoutexceptorfinallyblocks:>>> try: ... x = 2 ... something = 3 File "<stdin>", line 3 something = 3 ^^^^^^^^^ SyntaxError: expected 'except' or 'finally' block(Contributed by Pablo Galindo in
44305.) -
Usage of
=instead of==in comparisons:>>> if rocket.position = event_horizon: File "<stdin>", line 1 if rocket.position = event_horizon: ^ SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?(Contributed by Pablo Galindo in
43797.) -
Usage of
*in f-strings:>>> f"Black holes {*all_black_holes} and revelations" File "<stdin>", line 1 (*all_black_holes) ^ SyntaxError: f-string: cannot use starred expression here(Contributed by Pablo Galindo in
41064.)
IndentationErrors
Many IndentationError exceptions now have more context regarding what kind of block was expecting an indentation, including the location of the statement:
>>> def foo():
... if lel:
... x = 2
File "<stdin>", line 3
x = 2
^
IndentationError: expected an indented block after 'if' statement in line 2
AttributeErrors
When printing AttributeError, !PyErr_Display will offer suggestions of similar attribute names in the object that the exception was raised from:
>>> collections.namedtoplo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?
(Contributed by Pablo Galindo in 38530.)
[!WARNING] Notice this won't work if
!PyErr_Displayis not called to display the error which can happen if some other custom error display function is used. This is a common scenario in some REPLs like IPython.
NameErrors
When printing NameError raised by the interpreter, !PyErr_Display will offer suggestions of similar variable names in the function that the exception was raised from:
>>> schwarzschild_black_hole = None
>>> schwarschild_black_hole
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?
(Contributed by Pablo Galindo in 38530.)
[!WARNING] Notice this won't work if
!PyErr_Displayis not called to display the error, which can happen if some other custom error display function is used. This is a common scenario in some REPLs like IPython.
PEP 626: Precise line numbers for debugging and other tools
PEP 626 brings more precise and reliable line numbers for debugging, profiling and coverage tools. Tracing events, with the correct line number, are generated for all lines of code executed and only for lines of code that are executed.
The ~frame.f_lineno attribute of frame objects will always contain the expected line number.
The !codeobject.co_lnotab attribute of code objects <code-objects> is deprecated and will be removed in 3.12. Code that needs to convert from offset to line number should use the new ~codeobject.co_lines method instead.
PEP 634: Structural Pattern Matching
Structural pattern matching has been added in the form of a match statement and case statements of patterns with associated actions. Patterns consist of sequences, mappings, primitive data types as well as class instances. Pattern matching enables programs to extract information from complex data types, branch on the structure of data, and apply specific actions based on different forms of data.
Syntax and operations
The generic syntax of pattern matching is:
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. Specifically, pattern matching operates by:
- using data with type and shape (the
subject) - evaluating the
subjectin thematchstatement - comparing the subject with each pattern in a
casestatement from top to bottom until a match is confirmed. - executing the action associated with the pattern of the confirmed match
- If an exact match is not confirmed, the last case, a wildcard
_, if provided, will be used as the matching case. If an exact match is not confirmed and a wildcard case does not exist, the entire match block is a no-op.
Declarative approach
Readers may be aware of pattern matching through the simple example of matching a subject (data object) to a literal (pattern) with the switch statement found in C, Java or JavaScript (and many other languages). Often the switch statement is used for comparison of an object/expression with case statements containing literals.
More powerful examples of pattern matching can be found in languages such as Scala and Elixir. With structural pattern matching, the approach is "declarative" and explicitly states the conditions (the patterns) for data to match.
While an "imperative" series of instructions using nested "if" statements could be used to accomplish something similar to structural pattern matching, it is less clear than the "declarative" approach. Instead the "declarative" approach states the conditions to meet for a match and is more readable through its explicit patterns. While structural pattern matching can be used in its simplest form comparing a variable to a literal in a case statement, its true value for Python lies in its handling of the subject's type and shape.
Simple pattern: match to a literal
Let's look at this example as pattern matching in its simplest form: a value, the subject, being matched to several literals, the patterns. In the example below, status is the subject of the match statement. The patterns are each of the case statements, where literals represent request status codes. The associated action to the case is executed after a match:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
If the above function is passed a status of 418, "I'm a teapot" is returned. If the above function is passed a status of 500, the case statement with _ will match as a wildcard, and "Something's wrong with the internet" is returned. Note the last block: the variable name, _, acts as a wildcard and insures the subject will always match. The use of _ is optional.
You can combine several literals in a single pattern using | ("or"):
case 401 | 403 | 404:
return "Not allowed"
Behavior without the wildcard
If we modify the above example by removing the last case block, the example becomes:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
Without the use of _ in a case statement, a match may not exist. If no match exists, the behavior is a no-op. For example, if status of 500 is passed, a no-op occurs.
Patterns with a literal and variable
Patterns can look like unpacking assignments, and a pattern may be used to bind variables. In this example, a data point can be unpacked to its x-coordinate and y-coordinate:
# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
The first pattern has two literals, (0, 0), and may be thought of as an extension of the literal pattern shown above. The next two patterns combine a literal and a variable, and the variable binds a value from the subject (point). The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point.
Patterns and classes
If you are using classes to structure your data, you can use as a pattern the class name followed by an argument list resembling a constructor. This pattern has the ability to capture instance attributes into variables:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def location(point):
match point:
case Point(x=0, y=0):
print("Origin is the point's location.")
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} and the point is on the x-axis.")
case Point():
print("The point is located somewhere else on the plane.")
case _:
print("Not a point")
Patterns with positional parameters
You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting the __match_args__ special attribute in your classes. If it's set to ("x", "y"), the following patterns are all equivalent (and all bind the y attribute to the var variable):
Point(1, var)
Point(1, y=var)
Point(x=1, y=var)
Point(y=var, x=1)
Nested patterns
Patterns can be arbitrarily nested. For example, if our data is a short list of points, it could be matched like this:
match points:
case []:
print("No points in the list.")
case [Point(0, 0)]:
print("The origin is the only point in the list.")
case [Point(x, y)]:
print(f"A single point {x}, {y} is in the list.")
case [Point(0, y1), Point(0, y2)]:
print(f"Two points on the Y axis at {y1}, {y2} are in the list.")
case _:
print("Something else is found in the list.")
Complex patterns and the wildcard
To this point, the examples have used _ alone in the last case statement. A wildcard can be used in more complex patterns, such as ('error', code, _). For example:
match test_variable:
case ('warning', code, 40):
print("A warning has been received.")
case ('error', code, _):
print(f"An error {code} occurred.")
In the above case, test_variable will match for ('error', code, 100) and ('error', code, 800).
Guard
We can add an if clause to a pattern, known as a "guard". If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:
match point:
case Point(x, y) if x == y:
print(f"The point is located on the diagonal Y=X at {x}.")
case Point(x, y):
print(f"Point is not on the diagonal.")
Other Key Features
Several other key features:
-
Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. Technically, the subject must be a sequence. Therefore, an important exception is that patterns don't match iterators. Also, to prevent a common mistake, sequence patterns don't match strings.
-
Sequence patterns support wildcards:
[x, y, *rest]and(x, y, *rest)work similar to wildcards in unpacking assignments. The name after*may also be_, so(x, y, *_)matches a sequence of at least two items without binding the remaining items. -
Mapping patterns:
{"bandwidth": b, "latency": l}captures the"bandwidth"and"latency"values from a dict. Unlike sequence patterns, extra keys are ignored. A wildcard**restis also supported. (But**_would be redundant, so is not allowed.) -
Subpatterns may be captured using the
askeyword:case (Point(x1, y1), Point(x2, y2) as p2): ...This binds x1, y1, x2, y2 like you would expect without the
asclause, and p2 to the entire second item of the subject. -
Most literals are compared by equality. However, the singletons
True,FalseandNoneare compared by identity. -
Named constants may be used in patterns. These named constants must be dotted names to prevent the constant from being interpreted as a capture variable:
from enum import Enum class Color(Enum): RED = 0 GREEN = 1 BLUE = 2 color = Color.GREEN match color: case Color.RED: print("I see red!") case Color.GREEN: print("Grass is green") case Color.BLUE: print("I'm feeling the blues :(")
For the full specification see 634. Motivation and rationale are in 635, and a longer tutorial is in 636.
Optional EncodingWarning and encoding="locale" option
The default encoding of ~io.TextIOWrapper and open is platform and locale dependent. Since UTF-8 is used on most Unix platforms, omitting encoding option when opening UTF-8 files (e.g. JSON, YAML, TOML, Markdown) is a very common bug. For example:
# BUG: "rb" mode or encoding="utf-8" should be used.
with open("data.json") as f:
data = json.load(f)
To find this type of bug, an optional EncodingWarning is added. It is emitted when sys.flags.warn_default_encoding <sys.flags> is true and locale-specific default encoding is used.
-X warn_default_encoding option and PYTHONWARNDEFAULTENCODING are added to enable the warning.
See io-text-encoding for more information.
New Features Related to Type Hints
This section covers major changes affecting 484 type hints and the typing module.
PEP 604: New Type Union Operator
A new type union operator was introduced which enables the syntax X | Y. This provides a cleaner way of expressing 'either type X or type Y' instead of using typing.Union, especially in type hints.
In previous versions of Python, to apply a type hint for functions accepting arguments of multiple types, typing.Union was used:
def square(number: Union[int, float]) -> Union[int, float]:
return number ** 2
Type hints can now be written in a more succinct manner:
def square(number: int | float) -> int | float:
return number ** 2
This new syntax is also accepted as the second argument to isinstance and issubclass:
>>> isinstance(1, int | str)
True
See types-union and 604 for more details.
(Contributed by Maggie Moss and Philippe Prados in 41428, with additions by Yurii Karabas and Serhiy Storchaka in 44490.)
PEP 612: Parameter Specification Variables
Two new options to improve the information provided to static type checkers for 484's Callable have been added to the typing module.
The first is the parameter specification variable. They are used to forward the parameter types of one callable to another callable -- a pattern commonly found in higher order functions and decorators. Examples of usage can be found in typing.ParamSpec. Previously, there was no easy way to type annotate dependency of parameter types in such a precise manner.
The second option is the new Concatenate operator. It's used in conjunction with parameter specification variables to type annotate a higher order callable which adds or removes parameters of another callable. Examples of usage can be found in typing.Concatenate.
See typing.Callable, typing.ParamSpec, typing.Concatenate, typing.ParamSpecArgs, typing.ParamSpecKwargs, and 612 for more details.
(Contributed by Ken Jin in 41559, with minor enhancements by Jelle Zijlstra in 43783. PEP written by Mark Mendoza.)
PEP 613: TypeAlias
484 introduced the concept of type aliases, only requiring them to be top-level unannotated assignments. This simplicity sometimes made it difficult for type checkers to distinguish between type aliases and ordinary assignments, especially when forward references or invalid types were involved. Compare:
StrCache = 'Cache[str]' # a type alias
LOG_PREFIX = 'LOG[DEBUG]' # a module constant
Now the typing module has a special value ~typing.TypeAlias which lets you declare type aliases more explicitly:
StrCache: TypeAlias = 'Cache[str]' # a type alias
LOG_PREFIX = 'LOG[DEBUG]' # a module constant
See 613 for more details.
(Contributed by Mikhail Golubev in 41923.)
PEP 647: User-Defined Type Guards
~typing.TypeGuard has been added to the typing module to annotate type guard functions and improve information provided to static type checkers during type narrowing. For more information, please see ~typing.TypeGuard's documentation, and 647.
(Contributed by Ken Jin and Guido van Rossum in 43766. PEP written by Eric Traut.)
Other Language Changes
- The
inttype has a new methodint.bit_count, returning the number of ones in the binary expansion of a given integer, also known as the population count. (Contributed by Niklas Fiekas in29882.) - The views returned by
dict.keys,dict.valuesanddict.itemsnow all have amappingattribute that gives atypes.MappingProxyTypeobject wrapping the original dictionary. (Contributed by Dennis Sweeney in40890.) 618: Thezipfunction now has an optionalstrictflag, used to require that all the iterables have an equal length.- Builtin and extension functions that take integer arguments no longer accept
~decimal.Decimals,~fractions.Fractions and other objects that can be converted to integers only with a loss (e.g. that have the~object.__int__method but do not have the~object.__index__method). (Contributed by Serhiy Storchaka in37999.) - If
object.__ipow__returnsNotImplemented, the operator will correctly fall back toobject.__pow__andobject.__rpow__as expected. (Contributed by Alex Shkop in38302.) - Assignment expressions can now be used unparenthesized within set literals and set comprehensions, as well as in sequence indexes (but not slices).
- Functions have a new
__builtins__attribute which is used to look for builtin symbols when a function is executed, instead of looking into__globals__['__builtins__']. The attribute is initialized from__globals__["__builtins__"]if it exists, else from the current builtins. (Contributed by Mark Shannon in42990.) - Two new builtin functions --
aiterandanexthave been added to provide asynchronous counterparts toiterandnext, respectively. (Contributed by Joshua Bronson, Daniel Pope, and Justin Wang in31861.) - Static methods (
staticmethod) and class methods (classmethod) now inherit the method attributes (__module__,__name__,__qualname__,__doc__,__annotations__) and have a new__wrapped__attribute. Moreover, static methods are now callable as regular functions. (Contributed by Victor Stinner in43682.) - Annotations for complex targets (everything beside
simple nametargets defined by526) no longer cause any runtime effects withfrom __future__ import annotations. (Contributed by Batuhan Taskaya in42737.) - Class and module objects now lazy-create empty annotations dicts on demand. The annotations dicts are stored in the object’s
__dict__for backwards compatibility. This improves the best practices for working with__annotations__; for more information, please seeannotations-howto. (Contributed by Larry Hastings in43901.) - Annotations consist of
yield,yield from,awaitor named expressions are now forbidden underfrom __future__ import annotationsdue to their side effects. (Contributed by Batuhan Taskaya in42725.) - Usage of unbound variables,
super()and other expressions that might alter the processing of symbol table as annotations are now rendered effectless underfrom __future__ import annotations. (Contributed by Batuhan Taskaya in42725.) - Hashes of NaN values of both
floattype anddecimal.Decimaltype now depend on object identity. Formerly, they always hashed to0even though NaN values are not equal to one another. This caused potentially quadratic runtime behavior due to excessive hash collisions when creating dictionaries and sets containing multiple NaNs. (Contributed by Raymond Hettinger in43475.) - A
SyntaxError(instead of aNameError) will be raised when deleting the__debug__constant. (Contributed by Donghee Na in45000.) SyntaxErrorexceptions now haveend_linenoandend_offsetattributes. They will beNoneif not determined. (Contributed by Pablo Galindo in43914.)
New Modules
- None.
Improved Modules
asyncio
Add missing ~asyncio.loop.connect_accepted_socket method. (Contributed by Alex Grönholm in 41332.)
argparse
Misleading phrase "optional arguments" was replaced with "options" in argparse help. Some tests might require adaptation if they rely on exact output match. (Contributed by Raymond Hettinger in 9694.)
array
The ~array.array.index method of array.array now has optional start and stop parameters. (Contributed by Anders Lorentsen and Zackery Spytz in 31956.)
asynchat, asyncore, smtpd
These modules have been marked as deprecated in their module documentation since Python 3.6. An import-time DeprecationWarning has now been added to all three of these modules.
base64
Add base64.b32hexencode and base64.b32hexdecode to support the Base32 Encoding with Extended Hex Alphabet.
bdb
Add !clearBreakpoints to reset all set breakpoints. (Contributed by Irit Katriel in 24160.)
bisect
Added the possibility of providing a key function to the APIs in the bisect module. (Contributed by Raymond Hettinger in 4356.)
codecs
Add a codecs.unregister function to unregister a codec search function. (Contributed by Hai Shi in 41842.)
collections.abc
The __args__ of the parameterized generic <types-genericalias> for collections.abc.Callable are now consistent with typing.Callable. collections.abc.Callable generic now flattens type parameters, similar to what typing.Callable currently does. This means that collections.abc.Callable[[int, str], str] will have __args__ of (int, str, str); previously this was ([int, str], str). To allow this change, types.GenericAlias can now be subclassed, and a subclass will be returned when subscripting the collections.abc.Callable type. Note that a TypeError may be raised for invalid forms of parameterizing collections.abc.Callable which may have passed silently in Python 3.9. (Contributed by Ken Jin in 42195.)
contextlib
Add a contextlib.aclosing context manager to safely close async generators and objects representing asynchronously released resources. (Contributed by Joongi Kim and John Belmonte in 41229.)
Add asynchronous context manager support to contextlib.nullcontext. (Contributed by Tom Gringauz in 41543.)
Add ~contextlib.AsyncContextDecorator, for supporting usage of async context managers as decorators.
curses
The extended color functions added in ncurses 6.1 will be used transparently by curses.color_content, curses.init_color, curses.init_pair, and curses.pair_content. A new function, curses.has_extended_color_support, indicates whether extended color support is provided by the underlying ncurses library. (Contributed by Jeffrey Kintscher and Hans Petter Jansson in 36982.)
dataclasses
__slots__
Added slots parameter in dataclasses.dataclass decorator. (Contributed by Yurii Karabas in 42269)
Keyword-only fields
dataclasses now supports fields that are keyword-only in the generated __init__ method. There are a number of ways of specifying keyword-only fields.
You can say that every field is keyword-only:
from dataclasses import dataclass
@dataclass(kw_only=True)
class Birthday:
name: str
birthday: datetime.date
Both name and birthday are keyword-only parameters to the generated __init__ method.
You can specify keyword-only on a per-field basis:
from dataclasses import dataclass, field
@dataclass
class Birthday:
name: str
birthday: datetime.date = field(kw_only=True)
Here only birthday is keyword-only. If you set kw_only on individual fields, be aware that there are rules about re-ordering fields due to keyword-only fields needing to follow non-keyword-only fields. See the full dataclasses documentation for details.
You can also specify that all fields following a KW_ONLY marker are keyword-only. This will probably be the most common usage:
from dataclasses import dataclass, KW_ONLY
@dataclass
class Point:
x: float
y: float
_: KW_ONLY
z: float = 0.0
t: float = 0.0
Here, z and t are keyword-only parameters, while x and y are not. (Contributed by Eric V. Smith in 43532.)
distutils
The entire distutils package is deprecated, to be removed in Python 3.12. Its functionality for specifying package builds has already been completely replaced by third-party packages setuptools and packaging, and most other commonly used APIs are available elsewhere in the standard library (such as platform, shutil, subprocess or sysconfig). There are no plans to migrate any other functionality from distutils, and applications that are using other functions should plan to make private copies of the code. Refer to 632 for discussion.
The bdist_wininst command deprecated in Python 3.8 has been removed. The bdist_wheel command is now recommended to distribute binary packages on Windows. (Contributed by Victor Stinner in 42802.)
doctest
When a module does not define __loader__, fall back to __spec__.loader. (Contributed by Brett Cannon in 42133.)
encodings
encodings.normalize_encoding now ignores non-ASCII characters. (Contributed by Hai Shi in 39337.)
enum
~enum.Enum ~object.__repr__ now returns enum_name.member_name and ~object.__str__ now returns member_name. Stdlib enums available as module constants have a repr of module_name.member_name. (Contributed by Ethan Furman in 40066.)
Add enum.StrEnum for enums where all members are strings. (Contributed by Ethan Furman in 41816.)
fileinput
Add encoding and errors parameters in fileinput.input and fileinput.FileInput. (Contributed by Inada Naoki in 43712.)
fileinput.hook_compressed now returns ~io.TextIOWrapper object when mode is "r" and file is compressed, like uncompressed files. (Contributed by Inada Naoki in 5758.)
faulthandler
The faulthandler module now detects if a fatal error occurs during a garbage collector collection. (Contributed by Victor Stinner in 44466.)
gc
Add audit hooks for gc.get_objects, gc.get_referrers and gc.get_referents. (Contributed by Pablo Galindo in 43439.)
glob
Add the root_dir and dir_fd parameters in ~glob.glob and ~glob.iglob which allow to specify the root directory for searching. (Contributed by Serhiy Storchaka in 38144.)
hashlib
The hashlib module requires OpenSSL 1.1.1 or newer. (Contributed by Christian Heimes in 644 and 43669.)
The hashlib module has preliminary support for OpenSSL 3.0.0. (Contributed by Christian Heimes in 38820 and other issues.)
The pure-Python fallback of ~hashlib.pbkdf2_hmac is deprecated. In the future PBKDF2-HMAC will only be available when Python has been built with OpenSSL support. (Contributed by Christian Heimes in 43880.)
hmac
The hmac module now uses OpenSSL's HMAC implementation internally. (Contributed by Christian Heimes in 40645.)
IDLE and idlelib
Make IDLE invoke sys.excepthook (when started without '-n'). User hooks were previously ignored. (Contributed by Ken Hilton in 43008.)
Rearrange the settings dialog. Split the General tab into Windows and Shell/Ed tabs. Move help sources, which extend the Help menu, to the Extensions tab. Make space for new options and shorten the dialog. The latter makes the dialog better fit small screens. (Contributed by Terry Jan Reedy in 40468.) Move the indent space setting from the Font tab to the new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy in 33962.)
The changes above were backported to a 3.9 maintenance release.
Use spaces instead of tabs to indent interactive code. This makes interactive code entries 'look right'. Making this feasible was a major motivation for adding the shell sidebar. (Contributed by Terry Jan Reedy in 37892.)
Highlight the new soft keywords <soft-keywords> match, case <match>, and _ <wildcard-patterns> in pattern-matching statements. However, this highlighting is not perfect and will be incorrect in some rare cases, including some _-s in case patterns. (Contributed by Tal Einat in 44010.)
New in 3.10 maintenance releases.
Apply syntax highlighting to .pyi files. (Contributed by Alex Waygood and Terry Jan Reedy in 45447.)
Include prompts when saving Shell with inputs and outputs. (Contributed by Terry Jan Reedy in 95191.)
importlib.metadata
Feature parity with importlib_metadata 4.6 (history).
importlib.metadata entry points <entry-points> now provide a nicer experience for selecting entry points by group and name through a new importlib.metadata.EntryPoints <entry-points> class. See the Compatibility Note in the docs for more info on the deprecation and usage.
Added importlib.metadata.packages_distributions() <package-distributions> for resolving top-level Python modules and packages to their importlib.metadata.Distribution <distributions>.
inspect
When a module does not define __loader__, fall back to __spec__.loader. (Contributed by Brett Cannon in 42133.)
Add inspect.get_annotations, which safely computes the annotations defined on an object. It works around the quirks of accessing the annotations on various types of objects, and makes very few assumptions about the object it examines. inspect.get_annotations can also correctly un-stringize stringized annotations. inspect.get_annotations is now considered best practice for accessing the annotations dict defined on any Python object; for more information on best practices for working with annotations, please see annotations-howto. Relatedly, inspect.signature, inspect.Signature.from_callable, and !inspect.Signature.from_function now call inspect.get_annotations to retrieve annotations. This means inspect.signature and inspect.Signature.from_callable can also now un-stringize stringized annotations. (Contributed by Larry Hastings in 43817.)
itertools
Add itertools.pairwise. (Contributed by Raymond Hettinger in 38200.)
linecache
When a module does not define __loader__, fall back to __spec__.loader. (Contributed by Brett Cannon in 42133.)
os
Add os.cpu_count support for VxWorks RTOS. (Contributed by Peixing Xin in 41440.)
Add a new function os.eventfd and related helpers to wrap the eventfd2 syscall on Linux. (Contributed by Christian Heimes in 41001.)
Add os.splice that allows to move data between two file descriptors without copying between kernel address space and user address space, where one of the file descriptors must refer to a pipe. (Contributed by Pablo Galindo in 41625.)
Add ~os.O_EVTONLY, ~os.O_FSYNC, ~os.O_SYMLINK and ~os.O_NOFOLLOW_ANY for macOS. (Contributed by Donghee Na in 43106.)
os.path
os.path.realpath now accepts a strict keyword-only argument. When set to True, OSError is raised if a path doesn't exist or a symlink loop is encountered. (Contributed by Barney Gale in 43757.)
pathlib
Add slice support to PurePath.parents <pathlib.PurePath.parents>. (Contributed by Joshua Cannon in 35498.)
Add negative indexing support to PurePath.parents <pathlib.PurePath.parents>. (Contributed by Yaroslav Pankovych in 21041.)
Add Path.hardlink_to <pathlib.Path.hardlink_to> method that supersedes !link_to. The new method has the same argument order as ~pathlib.Path.symlink_to. (Contributed by Barney Gale in 39950.)
pathlib.Path.stat and ~pathlib.Path.chmod now accept a follow_symlinks keyword-only argument for consistency with corresponding functions in the os module. (Contributed by Barney Gale in 39906.)
platform
Add platform.freedesktop_os_release to retrieve operation system identification from freedesktop.org os-release standard file. (Contributed by Christian Heimes in 28468.)
pprint
pprint.pprint now accepts a new underscore_numbers keyword argument. (Contributed by sblondon in 42914.)
pprint can now pretty-print dataclasses.dataclass instances. (Contributed by Lewis Gaul in 43080.)
py_compile
Add --quiet option to command-line interface of py_compile. (Contributed by Gregory Schevchenko in 38731.)
pyclbr
Add an end_lineno attribute to the Function and Class objects in the tree returned by pyclbr.readmodule and pyclbr.readmodule_ex. It matches the existing (start) lineno. (Contributed by Aviral Srivastava in 38307.)
shelve
The shelve module now uses pickle.DEFAULT_PROTOCOL by default instead of pickle protocol 3 when creating shelves. (Contributed by Zackery Spytz in 34204.)
statistics
Add ~statistics.covariance, Pearson's ~statistics.correlation, and simple ~statistics.linear_regression functions. (Contributed by Tymoteusz Wołodźko in 38490.)
site
When a module does not define __loader__, fall back to __spec__.loader. (Contributed by Brett Cannon in 42133.)
socket
The exception socket.timeout is now an alias of TimeoutError. (Contributed by Christian Heimes in 42413.)
Add option to create MPTCP sockets with IPPROTO_MPTCP (Contributed by Rui Cunha in 43571.)
Add IP_RECVTOS option to receive the type of service (ToS) or DSCP/ECN fields (Contributed by Georg Sauthoff in 44077.)
ssl
The ssl module requires OpenSSL 1.1.1 or newer. (Contributed by Christian Heimes in 644 and 43669.)
The ssl module has preliminary support for OpenSSL 3.0.0 and new option ~ssl.OP_IGNORE_UNEXPECTED_EOF. (Contributed by Christian Heimes in 38820, 43794, 43788, 43791, 43799, 43920, 43789, and 43811.)
Deprecated function and use of deprecated constants now result in a DeprecationWarning. ssl.SSLContext.options has ~ssl.OP_NO_SSLv2 and ~ssl.OP_NO_SSLv3 set by default and therefore cannot warn about setting the flag again. The deprecation section <whatsnew310-deprecated> has a list of deprecated features. (Contributed by Christian Heimes in 43880.)
The ssl module now has more secure default settings. Ciphers without forward secrecy or SHA-1 MAC are disabled by default. Security level 2 prohibits weak RSA, DH, and ECC keys with less than 112 bits of security. ~ssl.SSLContext defaults to minimum protocol version TLS 1.2. Settings are based on Hynek Schlawack's research. (Contributed by Christian Heimes in 43998.)
The deprecated protocols SSL 3.0, TLS 1.0, and TLS 1.1 are no longer officially supported. Python does not block them actively. However OpenSSL build options, distro configurations, vendor patches, and cipher suites may prevent a successful handshake.
Add a timeout parameter to the ssl.get_server_certificate function. (Contributed by Zackery Spytz in 31870.)
The ssl module uses heap-types and multi-phase initialization. (Contributed by Christian Heimes in 42333.)
A new verify flag ~ssl.VERIFY_X509_PARTIAL_CHAIN has been added. (Contributed by l0x in 40849.)
sqlite3
Add audit events for ~sqlite3.connect, ~sqlite3.Connection.enable_load_extension, and ~sqlite3.Connection.load_extension. (Contributed by Erlend E. Aasland in 43762.)
sys
Add sys.orig_argv attribute: the list of the original command line arguments passed to the Python executable. (Contributed by Victor Stinner in 23427.)
Add sys.stdlib_module_names, containing the list of the standard library module names. (Contributed by Victor Stinner in 42955.)
thread
_thread.interrupt_main now takes an optional signal number to simulate (the default is still signal.SIGINT). (Contributed by Antoine Pitrou in 43356.)
threading
Add threading.gettrace and threading.getprofile to retrieve the functions set by threading.settrace and threading.setprofile respectively. (Contributed by Mario Corchero in 42251.)
Add threading.__excepthook__ to allow retrieving the original value of threading.excepthook in case it is set to a broken or a different value. (Contributed by Mario Corchero in 42308.)
traceback
The ~traceback.format_exception, ~traceback.format_exception_only, and ~traceback.print_exception functions can now take an exception object as a positional-only argument. (Contributed by Zackery Spytz and Matthias Bussonnier in 26389.)
types
Reintroduce the types.EllipsisType, types.NoneType and types.NotImplementedType classes, providing a new set of types readily interpretable by type checkers. (Contributed by Bas van Beek in 41810.)
typing
For major changes, see new-feat-related-type-hints.
The behavior of typing.Literal was changed to conform with 586 and to match the behavior of static type checkers specified in the PEP.
-
Literalnow de-duplicates parameters. -
Equality comparisons between
Literalobjects are now order independent. -
Literalcomparisons now respect types. For example,Literal[0] == Literal[False]previously evaluated toTrue. It is nowFalse. To support this change, the internally used type cache now supports differentiating types. -
Literalobjects will now raise aTypeErrorexception during equality comparisons if any of their parameters are nothashable. Note that declaringLiteralwith unhashable parameters will not throw an error:>>> from typing import Literal >>> Literal[{0}] >>> Literal[{0}] == Literal[{False}] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set'
(Contributed by Yurii Karabas in 42345.)
Add new function typing.is_typeddict to introspect if an annotation is a typing.TypedDict. (Contributed by Patrick Reader in 41792.)
Subclasses of typing.Protocol which only have data variables declared will now raise a TypeError when checked with isinstance unless they are decorated with ~typing.runtime_checkable. Previously, these checks passed silently. Users should decorate their subclasses with the !runtime_checkable decorator if they want runtime protocols. (Contributed by Yurii Karabas in 38908.)
Importing from the typing.io and typing.re submodules will now emit DeprecationWarning. These submodules have been deprecated since Python 3.8 and will be removed in a future version of Python. Anything belonging to those submodules should be imported directly from typing instead. (Contributed by Sebastian Rittau in 38291.)
unittest
Add new method ~unittest.TestCase.assertNoLogs to complement the existing ~unittest.TestCase.assertLogs. (Contributed by Kit Yan Choi in 39385.)
urllib.parse
Python versions earlier than Python 3.10 allowed using both ; and & as query parameter separators in urllib.parse.parse_qs and urllib.parse.parse_qsl. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects !cgi.parse and !cgi.parse_multipart as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in 42967.)
The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates 3986, ASCII newline \n, \r and tab \t characters are stripped from the URL by the parser in urllib.parse preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (See 88048)
xml
Add a ~xml.sax.handler.LexicalHandler class to the xml.sax.handler module. (Contributed by Jonathan Gossage and Zackery Spytz in 35018.)
zipimport
Add ~zipimport.zipimporter.invalidate_caches method. (Contributed by Desmond Cheong in 14678.)
Optimizations
- Constructors
str,bytesandbytearrayare now faster (around 30--40% for small objects). (Contributed by Serhiy Storchaka in41334.) - The
runpymodule now imports fewer modules. Thepython3 -m module-namecommand startup time is 1.4x faster in average. On Linux,python3 -I -m module-nameimports 69 modules on Python 3.9, whereas it only imports 51 modules (-18) on Python 3.10. (Contributed by Victor Stinner in41006and41718.) - The
LOAD_ATTRinstruction now uses new "per opcode cache" mechanism. It is about 36% faster now for regular attributes and 44% faster for slots. (Contributed by Pablo Galindo and Yury Selivanov in42093and Guido van Rossum in42927, based on ideas implemented originally in PyPy and MicroPython.) - When building Python with
--enable-optimizationsnow-fno-semantic-interpositionis added to both the compile and link line. This speeds builds of the Python interpreter created with--enable-sharedwithgccby up to 30%. See this article for more details. (Contributed by Victor Stinner and Pablo Galindo in38980.) - Use a new output buffer management code for
bz2/lzma/zlibmodules, and add.readall()function to_compression.DecompressReaderclass. bz2 decompression is now 1.09x ~ 1.17x faster, lzma decompression 1.20x ~ 1.32x faster,GzipFile.read(-1)1.11x ~ 1.18x faster. (Contributed by Ma Lin, reviewed by Gregory P. Smith, in41486) - When using stringized annotations, annotations dicts for functions are no longer created when the function is created. Instead, they are stored as a tuple of strings, and the function object lazily converts this into the annotations dict on demand. This optimization cuts the CPU time needed to define an annotated function by half. (Contributed by Yurii Karabas and Inada Naoki in
42202.) - Substring search functions such as
str1 in str2andstr2.find(str1)now sometimes use Crochemore & Perrin's "Two-Way" string searching algorithm to avoid quadratic behavior on long strings. (Contributed by Dennis Sweeney in41972) - Add micro-optimizations to
_PyType_Lookup()to improve type attribute cache lookup performance in the common case of cache hits. This makes the interpreter 1.04 times faster on average. (Contributed by Dino Viehland in43452.) - The following built-in functions now support the faster
590vectorcall calling convention:map,filter,reversed,boolandfloat. (Contributed by Donghee Na and Jeroen Demeyer in43575,43287,41922,41873and41870.) ~bz2.BZ2Fileperformance is improved by removing internalRLock. This makes!BZ2Filethread unsafe in the face of multiple simultaneous readers or writers, just like its equivalent classes ingzipandlzmahave always been. (Contributed by Inada Naoki in43785.)
Deprecated
-
Currently Python accepts numeric literals immediately followed by keywords, for example
0in x,1or x,0if 1else 2. It allows confusing and ambiguous expressions like[0x1for x in y](which can be interpreted as[0x1 for x in y]or[0x1f or x in y]). Starting in this release, a deprecation warning is raised if the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In future releases it will be changed to syntax warning, and finally to syntax error. (Contributed by Serhiy Storchaka in43833.) -
Starting in this release, there will be a concerted effort to begin cleaning up old import semantics that were kept for Python 2.7 compatibility. Specifically,
!find_loader/!find_module(superseded by~importlib.abc.MetaPathFinder.find_spec),importlib.abc.Loader.load_module(superseded by~importlib.abc.Loader.exec_module),!module_repr(which the import system takes care of for you), the__package__attribute (superseded by__spec__.parent), the__loader__attribute (superseded by__spec__.loader), and the__cached__attribute (superseded by__spec__.cached) will slowly be removed (as well as other classes and methods inimportlib).ImportWarningand/orDeprecationWarningwill be raised as appropriate to help identify code which needs updating during this transition. -
The entire
distutilsnamespace is deprecated, to be removed in Python 3.12. Refer to themodule changes <distutils-deprecated>section for more information. -
Non-integer arguments to
random.randrangeare deprecated. TheValueErroris deprecated in favor of aTypeError. (Contributed by Serhiy Storchaka and Raymond Hettinger in37319.) -
The various
load_module()methods ofimportlibhave been documented as deprecated since Python 3.6, but will now also trigger aDeprecationWarning. Use~importlib.abc.Loader.exec_moduleinstead. (Contributed by Brett Cannon in26131.) -
!zipimport.zipimporter.load_modulehas been deprecated in preference for~zipimport.zipimporter.exec_module. (Contributed by Brett Cannon in26131.) -
The use of
importlib.abc.Loader.load_moduleby the import system now triggers anImportWarningas~importlib.abc.Loader.exec_moduleis preferred. (Contributed by Brett Cannon in26131.) -
The use of
!importlib.abc.MetaPathFinder.find_moduleand!importlib.abc.PathEntryFinder.find_moduleby the import system now trigger anImportWarningasimportlib.abc.MetaPathFinder.find_specandimportlib.abc.PathEntryFinder.find_specare preferred, respectively. You can useimportlib.util.spec_from_loaderto help in porting. (Contributed by Brett Cannon in42134.) -
The use of
!importlib.abc.PathEntryFinder.find_loaderby the import system now triggers anImportWarningasimportlib.abc.PathEntryFinder.find_specis preferred. You can useimportlib.util.spec_from_loaderto help in porting. (Contributed by Brett Cannon in43672.) -
The various implementations of
!importlib.abc.MetaPathFinder.find_module(!importlib.machinery.BuiltinImporter.find_module,!importlib.machinery.FrozenImporter.find_module,!importlib.machinery.WindowsRegistryFinder.find_module,!importlib.machinery.PathFinder.find_module,!importlib.abc.MetaPathFinder.find_module),!importlib.abc.PathEntryFinder.find_module(!importlib.machinery.FileFinder.find_module), and!importlib.abc.PathEntryFinder.find_loader(!importlib.machinery.FileFinder.find_loader) now raiseDeprecationWarningand are slated for removal in Python 3.12 (previously they were documented as deprecated in Python 3.4). (Contributed by Brett Cannon in42135.) -
!importlib.abc.Finderis deprecated (including its sole method,!find_module). Bothimportlib.abc.MetaPathFinderandimportlib.abc.PathEntryFinderno longer inherit from the class. Users should inherit from one of these two classes as appropriate instead. (Contributed by Brett Cannon in42135.) -
The deprecations of
!imp,!importlib.find_loader,!importlib.util.set_package_wrapper,!importlib.util.set_loader_wrapper,!importlib.util.module_for_loader,!pkgutil.ImpImporter, and!pkgutil.ImpLoaderhave all been updated to list Python 3.12 as the slated version of removal (they began raisingDeprecationWarningin previous versions of Python). (Contributed by Brett Cannon in43720.) -
The import system now uses the
__spec__attribute on modules before falling back on!module_reprfor a module's__repr__()method. Removal of the use ofmodule_repr()is scheduled for Python 3.12. (Contributed by Brett Cannon in42137.) -
!importlib.abc.Loader.module_repr,!importlib.machinery.FrozenImporter.module_repr, and!importlib.machinery.BuiltinImporter.module_reprare deprecated and slated for removal in Python 3.12. (Contributed by Brett Cannon in42136.) -
sqlite3.OptimizedUnicodehas been undocumented and obsolete since Python 3.3, when it was made an alias tostr. It is now deprecated, scheduled for removal in Python 3.12. (Contributed by Erlend E. Aasland in42264.) -
The undocumented built-in function
sqlite3.enable_shared_cacheis now deprecated, scheduled for removal in Python 3.12. Its use is strongly discouraged by the SQLite3 documentation. See the SQLite3 docs for more details. If a shared cache must be used, open the database in URI mode using thecache=sharedquery parameter. (Contributed by Erlend E. Aasland in24464.) -
The following
threadingmethods are now deprecated:threading.currentThread=>threading.current_threadthreading.activeCount=>threading.active_countthreading.Condition.notifyAll=>threading.Condition.notify_allthreading.Event.isSet=>threading.Event.is_setthreading.Thread.setName=>threading.Thread.namethreading.Thread.getName=>threading.Thread.namethreading.Thread.isDaemon=>threading.Thread.daemonthreading.Thread.setDaemon=>threading.Thread.daemon
(Contributed by Jelle Zijlstra in
87889.) -
!pathlib.Path.link_tois deprecated and slated for removal in Python 3.12. Usepathlib.Path.hardlink_toinstead. (Contributed by Barney Gale in39950.) -
cgi.log()is deprecated and slated for removal in Python 3.12. (Contributed by Inada Naoki in41139.) -
The following
sslfeatures have been deprecated since Python 3.6, Python 3.7, or OpenSSL 1.1.0 and will be removed in 3.11:!OP_NO_SSLv2,!OP_NO_SSLv3,!OP_NO_TLSv1,!OP_NO_TLSv1_1,!OP_NO_TLSv1_2, and!OP_NO_TLSv1_3are replaced by~ssl.SSLContext.minimum_versionand~ssl.SSLContext.maximum_version.!PROTOCOL_SSLv2,!PROTOCOL_SSLv3,!PROTOCOL_SSLv23,!PROTOCOL_TLSv1,!PROTOCOL_TLSv1_1,!PROTOCOL_TLSv1_2, and!PROTOCOL_TLSare deprecated in favor of~ssl.PROTOCOL_TLS_CLIENTand~ssl.PROTOCOL_TLS_SERVER!wrap_socketis replaced byssl.SSLContext.wrap_socket!match_hostname!RAND_pseudo_bytes,!RAND_egd- NPN features like
ssl.SSLSocket.selected_npn_protocolandssl.SSLContext.set_npn_protocolsare replaced by ALPN.
-
The threading debug (
!PYTHONTHREADDEBUGenvironment variable) is deprecated in Python 3.10 and will be removed in Python 3.12. This feature requires adebug build of Python <debug-build>. (Contributed by Victor Stinner in44584.) -
Importing from the
typing.ioandtyping.resubmodules will now emitDeprecationWarning. These submodules will be removed in a future version of Python. Anything belonging to these submodules should be imported directly fromtypinginstead. (Contributed by Sebastian Rittau in38291.)
Removed
-
Removed special methods
__int__,__float__,__floordiv__,__mod__,__divmod__,__rfloordiv__,__rmod__and__rdivmod__of thecomplexclass. They always raised aTypeError. (Contributed by Serhiy Storchaka in41974.) -
The
ParserBase.error()method from the private and undocumented_markupbasemodule has been removed.html.parser.HTMLParseris the only subclass ofParserBaseand itserror()implementation was already removed in Python 3.5. (Contributed by Berker Peksag in31844.) -
Removed the
unicodedata.ucnhash_CAPIattribute which was an internal PyCapsule object. The related private_PyUnicode_Name_CAPIstructure was moved to the internal C API. (Contributed by Victor Stinner in42157.) -
Removed the
parsermodule, which was deprecated in 3.9 due to the switch to the new PEG parser, as well as all the C source and header files that were only being used by the old parser, includingnode.h,parser.h,graminit.handgrammar.h. -
Removed the Public C API functions
PyParser_SimpleParseStringFlags,PyParser_SimpleParseStringFlagsFilename,PyParser_SimpleParseFileFlagsandPyNode_Compilethat were deprecated in 3.9 due to the switch to the new PEG parser. -
Removed the
formattermodule, which was deprecated in Python 3.4. It is somewhat obsolete, little used, and not tested. It was originally scheduled to be removed in Python 3.6, but such removals were delayed until after Python 2.7 EOL. Existing users should copy whatever classes they use into their code. (Contributed by Donghee Na and Terry J. Reedy in42299.) -
Removed the
!PyModule_GetWarningsModulefunction that was useless now due to the!_warningsmodule was converted to a builtin module in 2.6. (Contributed by Hai Shi in42599.) -
Remove deprecated aliases to
collections-abstract-base-classesfrom thecollectionsmodule. (Contributed by Victor Stinner in37324.) -
The
loopparameter has been removed from most ofasyncio'shigh-level API <../library/asyncio-api-index>following deprecation in Python 3.8. The motivation behind this change is multifold:- This simplifies the high-level API.
- The functions in the high-level API have been implicitly getting the current thread's running event loop since Python 3.7. There isn't a need to pass the event loop to the API in most normal use cases.
- Event loop passing is error-prone especially when dealing with loops running in different threads.
Note that the low-level API will still accept
loop. Seechanges-python-apifor examples of how to replace existing code.(Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley in
42392.)
Porting to Python 3.10
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in the Python syntax
- Deprecation warning is now emitted when compiling previously valid syntax if the numeric literal is immediately followed by a keyword (like in
0in x). In future releases it will be changed to syntax warning, and finally to a syntax error. To get rid of the warning and make the code compatible with future releases just add a space between the numeric literal and the following keyword. (Contributed by Serhiy Storchaka in43833.)
Changes in the Python API
-
The etype parameters of the
~traceback.format_exception,~traceback.format_exception_only, and~traceback.print_exceptionfunctions in thetracebackmodule have been renamed to exc. (Contributed by Zackery Spytz and Matthias Bussonnier in26389.) -
atexit: At Python exit, if a callback registered withatexit.registerfails, its exception is now logged. Previously, only some exceptions were logged, and the last exception was always silently ignored. (Contributed by Victor Stinner in42639.) -
collections.abc.Callablegeneric now flattens type parameters, similar to whattyping.Callablecurrently does. This means thatcollections.abc.Callable[[int, str], str]will have__args__of(int, str, str); previously this was([int, str], str). Code which accesses the arguments viatyping.get_argsor__args__need to account for this change. Furthermore,TypeErrormay be raised for invalid forms of parameterizingcollections.abc.Callablewhich may have passed silently in Python 3.9. (Contributed by Ken Jin in42195.) -
socket.htonsandsocket.ntohsnow raiseOverflowErrorinstead ofDeprecationWarningif the given parameter will not fit in a 16-bit unsigned integer. (Contributed by Erlend E. Aasland in42393.) -
The
loopparameter has been removed from most ofasyncio'shigh-level API <../library/asyncio-api-index>following deprecation in Python 3.8.A coroutine that currently looks like this:
async def foo(loop): await asyncio.sleep(1, loop=loop)Should be replaced with this:
async def foo(): await asyncio.sleep(1)If
foo()was specifically designed not to run in the current thread's running event loop (e.g. running in another thread's event loop), consider usingasyncio.run_coroutine_threadsafeinstead.(Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley in
42392.) -
The
types.FunctionTypeconstructor now inherits the current builtins if the globals dictionary has no"__builtins__"key, rather than using{"None": None}as builtins: same behavior asevalandexecfunctions. Defining a function withdef function(...): ...in Python is not affected, globals cannot be overridden with this syntax: it also inherits the current builtins. (Contributed by Victor Stinner in42990.)
Changes in the C API
-
The C API functions
PyParser_SimpleParseStringFlags,PyParser_SimpleParseStringFlagsFilename,PyParser_SimpleParseFileFlags,PyNode_Compileand the type used by these functions,struct _node, were removed due to the switch to the new PEG parser.Source should be now be compiled directly to a code object using, for example,
Py_CompileString. The resulting code object can then be evaluated using, for example,PyEval_EvalCode.Specifically:
-
A call to
PyParser_SimpleParseStringFlagsfollowed byPyNode_Compilecan be replaced by callingPy_CompileString. -
There is no direct replacement for
PyParser_SimpleParseFileFlags. To compile code from aFILE *argument, you will need to read the file in C and pass the resulting buffer toPy_CompileString. -
To compile a file given a
char *filename, explicitly open the file, read it and compile the result. One way to do this is using theiomodule withPyImport_ImportModule,PyObject_CallMethod,PyBytes_AsStringandPy_CompileString, as sketched below. (Declarations and error handling are omitted.) :io_module = PyImport_ImportModule("io"); fileobject = PyObject_CallMethod(io_module, "open", "ss", filename, "rb"); source_bytes_object = PyObject_CallMethod(fileobject, "read", ""); result = PyObject_CallMethod(fileobject, "close", ""); source_buf = PyBytes_AsString(source_bytes_object); code = Py_CompileString(source_buf, filename, Py_file_input); -
For
FrameObjectobjects, the~frame.f_lastimember now represents a wordcode offset instead of a simple offset into the bytecode string. This means that this number needs to be multiplied by 2 to be used with APIs that expect a byte offset instead (likePyCode_Addr2Linefor example). Notice as well that the!f_lastimember ofFrameObjectobjects is not considered stable: please usePyFrame_GetLineNumberinstead.
-
CPython bytecode changes
- The
MAKE_FUNCTIONinstruction now accepts either a dict or a tuple of strings as the function's annotations. (Contributed by Yurii Karabas and Inada Naoki in42202.)
Build Changes
-
644: Python now requires OpenSSL 1.1.1 or newer. OpenSSL 1.0.2 is no longer supported. (Contributed by Christian Heimes in43669.) -
The C99 functions
snprintfandvsnprintfare now required to build Python. (Contributed by Victor Stinner in36020.) -
sqlite3requires SQLite 3.7.15 or higher. (Contributed by Sergey Fedoseev and Erlend E. Aasland in40744and40810.) -
The
atexitmodule must now always be built as a built-in module. (Contributed by Victor Stinner in42639.) -
Add
--disable-test-modulesoption to theconfigurescript: don't build nor install test modules. (Contributed by Xavier de Gaye, Thomas Petazzoni and Peixing Xin in27640.) -
Add
--with-wheel-pkg-dir=PATH option <--with-wheel-pkg-dir>to the./configurescript. If specified, theensurepipmodule looks forsetuptoolsandpipwheel packages in this directory: if both are present, these wheel packages are used instead of ensurepip bundled wheel packages.Some Linux distribution packaging policies recommend against bundling dependencies. For example, Fedora installs wheel packages in the
/usr/share/python-wheels/directory and don't install theensurepip._bundledpackage.(Contributed by Victor Stinner in
42856.) -
Add a new
configure --without-static-libpython option <--without-static-libpython>to not build thelibpythonMAJOR.MINOR.astatic library and not install thepython.oobject file.(Contributed by Victor Stinner in
43103.) -
The
configurescript now uses thepkg-configutility, if available, to detect the location of Tcl/Tk headers and libraries. As before, those locations can be explicitly specified with the--with-tcltk-includesand--with-tcltk-libsconfiguration options. (Contributed by Manolis Stamatogiannakis in42603.) -
Add
--with-openssl-rpathoption toconfigurescript. The option simplifies building Python with a custom OpenSSL installation, e.g../configure --with-openssl=/path/to/openssl --with-openssl-rpath=auto. (Contributed by Christian Heimes in43466.)
C API Changes
PEP 652: Maintaining the Stable ABI
The Stable ABI (Application Binary Interface) for extension modules or embedding Python is now explicitly defined. stable describes C API and ABI stability guarantees along with best practices for using the Stable ABI.
(Contributed by Petr Viktorin in 652 and 43795.)
New Features
-
The result of
PyNumber_Indexnow always has exact typeint. Previously, the result could have been an instance of a subclass ofint. (Contributed by Serhiy Storchaka in40792.) -
Add a new
~PyConfig.orig_argvmember to thePyConfigstructure: the list of the original command line arguments passed to the Python executable. (Contributed by Victor Stinner in23427.) -
The
PyDateTime_DATE_GET_TZINFOandPyDateTime_TIME_GET_TZINFOmacros have been added for accessing thetzinfoattributes ofdatetime.datetimeanddatetime.timeobjects. (Contributed by Zackery Spytz in30155.) -
Add a
PyCodec_Unregisterfunction to unregister a codec search function. (Contributed by Hai Shi in41842.) -
The
PyIter_Sendfunction was added to allow sending value into iterator without raisingStopIterationexception. (Contributed by Vladimir Matveev in41756.) -
Add
PyUnicode_AsUTF8AndSizeto the limited C API. (Contributed by Alex Gaynor in41784.) -
Add
PyModule_AddObjectReffunction: similar toPyModule_AddObjectbut don't steal a reference to the value on success. (Contributed by Victor Stinner in1635741.) -
Add
Py_NewRefandPy_XNewReffunctions to increment the reference count of an object and return the object. (Contributed by Victor Stinner in42262.) -
The
PyType_FromSpecWithBasesandPyType_FromModuleAndSpecfunctions now accept a single class as the bases argument. (Contributed by Serhiy Storchaka in42423.) -
The
PyType_FromModuleAndSpecfunction now accepts NULLtp_docslot. (Contributed by Hai Shi in41832.) -
The
PyType_GetSlotfunction can acceptstatic types <static-types>. (Contributed by Hai Shi and Petr Viktorin in41073.) -
Add a new
PySet_CheckExactfunction to the C-API to check if an object is an instance ofsetbut not an instance of a subtype. (Contributed by Pablo Galindo in43277.) -
Add
PyErr_SetInterruptExwhich allows passing a signal number to simulate. (Contributed by Antoine Pitrou in43356.) -
The limited C API is now supported if
Python is built in debug mode <debug-build>(if thePy_DEBUGmacro is defined). In the limited C API, thePy_INCREFandPy_DECREFfunctions are now implemented as opaque function calls, rather than accessing directly thePyObject.ob_refcntmember, if Python is built in debug mode and thePy_LIMITED_APImacro targets Python 3.10 or newer. It became possible to support the limited C API in debug mode because thePyObjectstructure is the same in release and debug mode since Python 3.8 (see36465).The limited C API is still not supported in the
--with-trace-refsspecial build (Py_TRACE_REFSmacro). (Contributed by Victor Stinner in43688.) -
Add the
Py_Is(x, y) <Py_Is>function to test if the x object is the y object, the same asx is yin Python. Add also thePy_IsNone,Py_IsTrue,Py_IsFalsefunctions to test if an object is, respectively, theNonesingleton, theTruesingleton or theFalsesingleton. (Contributed by Victor Stinner in43753.) -
Add new functions to control the garbage collector from C code:
PyGC_Enable(),PyGC_Disable(),PyGC_IsEnabled(). These functions allow to activate, deactivate and query the state of the garbage collector from C code without having to import thegcmodule. -
Add a new
Py_TPFLAGS_DISALLOW_INSTANTIATIONtype flag to disallow creating type instances. (Contributed by Victor Stinner in43916.) -
Add a new
Py_TPFLAGS_IMMUTABLETYPEtype flag for creating immutable type objects: type attributes cannot be set nor deleted. (Contributed by Victor Stinner and Erlend E. Aasland in43908.)
Porting to Python 3.10
-
The
PY_SSIZE_T_CLEANmacro must now be defined to usePyArg_ParseTupleandPy_BuildValueformats which use#:es#,et#,s#,u#,y#,z#,U#andZ#. Seearg-parsingand353. (Contributed by Victor Stinner in40943.) -
Since
Py_REFCNT()is changed to the inline static function,Py_REFCNT(obj) = new_refcntmust be replaced withPy_SET_REFCNT(obj, new_refcnt): seePy_SET_REFCNT()(available since Python 3.9). For backward compatibility, this macro can be used:#if PY_VERSION_HEX < 0x030900A4 # define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0) #endif(Contributed by Victor Stinner in
39573.) -
Calling
PyDict_GetItemwithoutGILheld had been allowed for historical reason. It is no longer allowed. (Contributed by Victor Stinner in40839.) -
PyUnicode_FromUnicode(NULL, size)andPyUnicode_FromStringAndSize(NULL, size)raiseDeprecationWarningnow. UsePyUnicode_Newto allocate Unicode object without initial data. (Contributed by Inada Naoki in36346.) -
The private
_PyUnicode_Name_CAPIstructure of the PyCapsule APIunicodedata.ucnhash_CAPIhas been moved to the internal C API. (Contributed by Victor Stinner in42157.) -
!Py_GetPath,!Py_GetPrefix,!Py_GetExecPrefix,!Py_GetProgramFullPath,!Py_GetPythonHomeand!Py_GetProgramNamefunctions now returnNULLif called beforePy_Initialize(before Python is initialized). Use the newinit-configAPI to get theinit-path-config. (Contributed by Victor Stinner in42260.) -
PyList_SET_ITEM,PyTuple_SET_ITEMandPyCell_SETmacros can no longer be used as l-value or r-value. For example,x = PyList_SET_ITEM(a, b, c)andPyList_SET_ITEM(a, b, c) = xnow fail with a compiler error. It prevents bugs likeif (PyList_SET_ITEM (a, b, c) < 0) ...test. (Contributed by Zackery Spytz and Victor Stinner in30459.) -
The non-limited API files
odictobject.h,parser_interface.h,picklebufobject.h,pyarena.h,pyctype.h,pydebug.h,pyfpe.h, andpytime.hhave been moved to theInclude/cpythondirectory. These files must not be included directly, as they are already included inPython.h; seeapi-includes. If they have been included directly, consider includingPython.hinstead. (Contributed by Nicholas Sim in35134.) -
Use the
Py_TPFLAGS_IMMUTABLETYPEtype flag to create immutable type objects. Do not rely onPy_TPFLAGS_HEAPTYPEto decide if a type object is mutable or not; check ifPy_TPFLAGS_IMMUTABLETYPEis set instead. (Contributed by Victor Stinner and Erlend E. Aasland in43908.) -
The undocumented function
Py_FrozenMainhas been removed from the limited API. The function is mainly useful for custom builds of Python. (Contributed by Petr Viktorin in26241.)
Deprecated
- The
PyUnicode_InternImmortal()function is now deprecated and will be removed in Python 3.12: usePyUnicode_InternInPlaceinstead. (Contributed by Victor Stinner in41692.)
Removed
-
Removed
Py_UNICODE_str*functions manipulatingPy_UNICODE*strings. (Contributed by Inada Naoki in41123.)Py_UNICODE_strlen: usePyUnicode_GetLengthorPyUnicode_GET_LENGTHPy_UNICODE_strcat: usePyUnicode_CopyCharactersorPyUnicode_FromFormatPy_UNICODE_strcpy,Py_UNICODE_strncpy: usePyUnicode_CopyCharactersorPyUnicode_SubstringPy_UNICODE_strcmp: usePyUnicode_ComparePy_UNICODE_strncmp: usePyUnicode_TailmatchPy_UNICODE_strchr,Py_UNICODE_strrchr: usePyUnicode_FindChar
-
Removed
PyUnicode_GetMax(). Please migrate to new (393) APIs. (Contributed by Inada Naoki in41103.) -
Removed
PyLong_FromUnicode(). Please migrate toPyLong_FromUnicodeObject. (Contributed by Inada Naoki in41103.) -
Removed
PyUnicode_AsUnicodeCopy(). Please usePyUnicode_AsUCS4CopyorPyUnicode_AsWideCharString(Contributed by Inada Naoki in41103.) -
Removed
_Py_CheckRecursionLimitvariable: it has been replaced byceval.recursion_limitof thePyInterpreterStatestructure. (Contributed by Victor Stinner in41834.) -
Removed undocumented macros
Py_ALLOW_RECURSIONandPy_END_ALLOW_RECURSIONand therecursion_criticalfield of thePyInterpreterStatestructure. (Contributed by Serhiy Storchaka in41936.) -
Removed the undocumented
PyOS_InitInterrupts()function. Initializing Python already implicitly installs signal handlers: seePyConfig.install_signal_handlers. (Contributed by Victor Stinner in41713.) -
Remove the
PyAST_Validate()function. It is no longer possible to build a AST object (mod_tytype) with the public C API. The function was already excluded from the limited C API (384). (Contributed by Victor Stinner in43244.) -
Remove the
symtable.hheader file and the undocumented functions:PyST_GetScope()PySymtable_Build()PySymtable_BuildObject()PySymtable_Free()Py_SymtableString()Py_SymtableStringObject()
The
Py_SymtableString()function was part the stable ABI by mistake but it could not be used, because thesymtable.hheader file was excluded from the limited C API.Use Python
symtablemodule instead. (Contributed by Victor Stinner in43244.) -
Remove
PyOS_ReadlineFunctionPointerfrom the limited C API headers and frompython3.dll, the library that provides the stable ABI on Windows. Since the function takes aFILE*argument, its ABI stability cannot be guaranteed. (Contributed by Petr Viktorin in43868.) -
Remove
ast.h,asdl.h, andPython-ast.hheader files. These functions were undocumented and excluded from the limited C API. Most names defined by these header files were not prefixed byPyand so could create names conflicts. For example,Python-ast.hdefined aYieldmacro which was conflict with theYieldname used by the Windows<winbase.h>header. Use the Pythonastmodule instead. (Contributed by Victor Stinner in43244.) -
Remove the compiler and parser functions using
struct _modtype, because the public AST C API was removed:PyAST_Compile()PyAST_CompileEx()PyAST_CompileObject()PyFuture_FromAST()PyFuture_FromASTObject()PyParser_ASTFromFile()PyParser_ASTFromFileObject()PyParser_ASTFromFilename()PyParser_ASTFromString()PyParser_ASTFromStringObject()
These functions were undocumented and excluded from the limited C API. (Contributed by Victor Stinner in
43244.) -
Remove the
pyarena.hheader file with functions:PyArena_New()PyArena_Free()PyArena_Malloc()PyArena_AddPyObject()
These functions were undocumented, excluded from the limited C API, and were only used internally by the compiler. (Contributed by Victor Stinner in
43244.) -
The
PyThreadState.use_tracingmember has been removed to optimize Python. (Contributed by Mark Shannon in43760.)
Notable security feature in 3.10.7
Converting between int and str in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for 2020-10735. This limit can be configured or disabled by environment variable, command line flag, or sys APIs. See the integer string conversion length limitation <int_max_str_digits> documentation. The default limit is 4300 digits in string form.
Notable security feature in 3.10.8
The deprecated !mailcap module now refuses to inject unsafe text (filenames, MIME types, parameters) into shell commands. Instead of using such text, it will warn and act as if a match was not found (or for test commands, as if the test failed). (Contributed by Petr Viktorin in 98966.)
Notable changes in 3.10.12
tarfile
- The extraction methods in
tarfile, andshutil.unpack_archive, have a new a filter argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. Seetarfile-extraction-filterfor details. In Python 3.12, use without the filter argument will show aDeprecationWarning. In Python 3.14, the default will switch to'data'. (Contributed by Petr Viktorin in706.)
What's New In Python 3.11
Editor
Pablo Galindo Salgado
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Mercurial log when researching a change.
This article explains the new features in Python 3.11, compared to 3.10. Python 3.11 was released on October 24, 2022. For full details, see the changelog <changelog>.
Summary -- Release highlights
- Python 3.11 is between 10-60% faster than Python 3.10. On average, we measured a 1.25x speedup on the standard benchmark suite. See
whatsnew311-faster-cpythonfor details.
New syntax features:
whatsnew311-pep654
New built-in features:
whatsnew311-pep678
New standard library modules:
680:tomllib— Support for parsing TOML in the Standard Library
Interpreter improvements:
whatsnew311-pep657- New
-Pcommand line option andPYTHONSAFEPATHenvironment variable todisable automatically prepending potentially unsafe paths <whatsnew311-pythonsafepath>tosys.path
New typing features:
whatsnew311-pep646whatsnew311-pep655whatsnew311-pep673whatsnew311-pep675whatsnew311-pep681
Important deprecations, removals and restrictions:
594:Many legacy standard library modules have been deprecated <whatsnew311-pep594>and will be removed in Python 3.13624:Py_UNICODE encoder APIs have been removed <whatsnew311-pep624>670:Macros converted to static inline functions <whatsnew311-pep670>
New Features
PEP 657: Fine-grained error locations in tracebacks
When printing tracebacks, the interpreter will now point to the exact expression that caused the error, instead of just the line. For example:
Traceback (most recent call last):
File "distance.py", line 11, in <module>
print(manhattan_distance(p1, p2))
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "distance.py", line 6, in manhattan_distance
return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'x'
Previous versions of the interpreter would point to just the line, making it ambiguous which object was None. These enhanced errors can also be helpful when dealing with deeply nested dict objects and multiple function calls:
Traceback (most recent call last):
File "query.py", line 37, in <module>
magic_arithmetic('foo')
File "query.py", line 18, in magic_arithmetic
return add_counts(x) / 25
^^^^^^^^^^^^^
File "query.py", line 24, in add_counts
return 25 + query_user(user1) + query_user(user2)
^^^^^^^^^^^^^^^^^
File "query.py", line 32, in query_user
return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
~~~~~~~~~~~~~~~~~~^^^^^
TypeError: 'NoneType' object is not subscriptable
As well as complex arithmetic expressions:
Traceback (most recent call last):
File "calculation.py", line 54, in <module>
result = (x / y / z) * (a / b / c)
~~~~~~^~~
ZeroDivisionError: division by zero
Additionally, the information used by the enhanced traceback feature is made available via a general API, that can be used to correlate bytecode instructions <bytecodes> with source code location. This information can be retrieved using:
- The
codeobject.co_positionsmethod in Python. - The
PyCode_Addr2Locationfunction in the C API.
See 657 for more details. (Contributed by Pablo Galindo, Batuhan Taskaya and Ammar Askar in 43950.)
[!NOTE] This feature requires storing column positions in
codeobjects, which may result in a small increase in interpreter memory usage and disk usage for compiled Python files. To avoid storing the extra information and deactivate printing the extra traceback information, use the-X no_debug_ranges <-X>command line option or thePYTHONNODEBUGRANGESenvironment variable.
PEP 654: Exception Groups and except*
654 introduces language features that enable a program to raise and handle multiple unrelated exceptions simultaneously. The builtin types ExceptionGroup and BaseExceptionGroup make it possible to group exceptions and raise them together, and the new except* <except_star> syntax generalizes except to match subgroups of exception groups.
See 654 for more details.
(Contributed by Irit Katriel in 45292. PEP written by Irit Katriel, Yury Selivanov and Guido van Rossum.)
PEP 678: Exceptions can be enriched with notes
The ~BaseException.add_note method is added to BaseException. It can be used to enrich exceptions with context information that is not available at the time when the exception is raised. The added notes appear in the default traceback.
See 678 for more details.
(Contributed by Irit Katriel in 45607. PEP written by Zac Hatfield-Dodds.)
Windows py.exe launcher improvements
The copy of the launcher included with Python 3.11 has been significantly updated. It now supports company/tag syntax as defined in 514 using the -V:{<company>}/{<tag>} argument instead of the limited -{<major>}.{<minor>}. This allows launching distributions other than PythonCore, the one hosted on python.org.
When using -V: selectors, either company or tag can be omitted, but all installs will be searched. For example, -V:OtherPython/ will select the "best" tag registered for OtherPython, while -V:3.11 or -V:/3.11 will select the "best" distribution with tag 3.11.
When using the legacy -{<major>}, -{<major>}.{<minor>}, -{<major>}-{<bitness>} or -{<major>}.{<minor>}-{<bitness>} arguments, all existing behaviour should be preserved from past versions, and only releases from PythonCore will be selected. However, the -64 suffix now implies "not 32-bit" (not necessarily x86-64), as there are multiple supported 64-bit platforms. 32-bit runtimes are detected by checking the runtime's tag for a -32 suffix. All releases of Python since 3.5 have included this in their 32-bit builds.
New Features Related to Type Hints
This section covers major changes affecting 484 type hints and the typing module.
PEP 646: Variadic generics
484 previously introduced ~typing.TypeVar, enabling creation of generics parameterised with a single type. 646 adds ~typing.TypeVarTuple, enabling parameterisation with an arbitrary number of types. In other words, a ~typing.TypeVarTuple is a variadic type variable, enabling variadic generics.
This enables a wide variety of use cases. In particular, it allows the type of array-like structures in numerical computing libraries such as NumPy and TensorFlow to be parameterised with the array shape. Static type checkers will now be able to catch shape-related bugs in code that uses these libraries.
See 646 for more details.
(Contributed by Matthew Rahtz in 43224, with contributions by Serhiy Storchaka and Jelle Zijlstra. PEP written by Mark Mendoza, Matthew Rahtz, Pradeep Kumar Srinivasan, and Vincent Siles.)
PEP 655: Marking individual TypedDict items as required or not-required
~typing.Required and ~typing.NotRequired provide a straightforward way to mark whether individual items in a ~typing.TypedDict must be present. Previously, this was only possible using inheritance.
All fields are still required by default, unless the total parameter is set to False, in which case all fields are still not-required by default. For example, the following specifies a !TypedDict with one required and one not-required key:
class Movie(TypedDict):
title: str
year: NotRequired[int]
m1: Movie = {"title": "Black Panther", "year": 2018} # OK
m2: Movie = {"title": "Star Wars"} # OK (year is not required)
m3: Movie = {"year": 2022} # ERROR (missing required field title)
The following definition is equivalent:
class Movie(TypedDict, total=False):
title: Required[str]
year: int
See 655 for more details.
(Contributed by David Foster and Jelle Zijlstra in 47087. PEP written by David Foster.)
PEP 673: Self type
The new ~typing.Self annotation provides a simple and intuitive way to annotate methods that return an instance of their class. This behaves the same as the ~typing.TypeVar-based approach specified in PEP 484 <484#annotating-instance-and-class-methods>, but is more concise and easier to follow.
Common use cases include alternative constructors provided as classmethod <classmethod>s, and ~object.__enter__ methods that return self:
class MyLock:
def __enter__(self) -> Self:
self.lock()
return self
...
class MyInt:
@classmethod
def fromhex(cls, s: str) -> Self:
return cls(int(s, 16))
...
~typing.Self can also be used to annotate method parameters or attributes of the same type as their enclosing class.
See 673 for more details.
(Contributed by James Hilton-Balfe in 46534. PEP written by Pradeep Kumar Srinivasan and James Hilton-Balfe.)
PEP 675: Arbitrary literal string type
The new ~typing.LiteralString annotation may be used to indicate that a function parameter can be of any literal string type. This allows a function to accept arbitrary literal string types, as well as strings created from other literal strings. Type checkers can then enforce that sensitive functions, such as those that execute SQL statements or shell commands, are called only with static arguments, providing protection against injection attacks.
For example, a SQL query function could be annotated as follows:
def run_query(sql: LiteralString) -> ...:
...
def caller(
arbitrary_string: str,
query_string: LiteralString,
table_name: LiteralString,
) -> None:
run_query("SELECT * FROM students") # ok
run_query(query_string) # ok
run_query("SELECT * FROM " + table_name) # ok
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
See 675 for more details.
(Contributed by Jelle Zijlstra in 47088. PEP written by Pradeep Kumar Srinivasan and Graham Bleaney.)
PEP 681: Data class transforms
~typing.dataclass_transform may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of @dataclass_transform() tells a static type checker that the decorated object performs runtime "magic" that transforms a class, giving it dataclass <dataclasses.dataclass>-like behaviors.
For example:
# The create_model decorator is defined by a library.
@typing.dataclass_transform()
def create_model(cls: Type[T]) -> Type[T]:
cls.__init__ = ...
cls.__eq__ = ...
cls.__ne__ = ...
return cls
# The create_model decorator can now be used to create new model classes:
@create_model
class CustomerModel:
id: int
name: str
c = CustomerModel(id=327, name="Eric Idle")
See 681 for more details.
(Contributed by Jelle Zijlstra in 91860. PEP written by Erik De Bonte and Eric Traut.)
PEP 563 may not be the future
563 Postponed Evaluation of Annotations (the from __future__ import annotations future statement <future>) that was originally planned for release in Python 3.10 has been put on hold indefinitely. See this message from the Steering Council for more information.
Other Language Changes
- Starred unpacking expressions can now be used in
forstatements. (See46725for more details.) - Asynchronous
comprehensions <comprehensions>are now allowed inside comprehensions inasynchronous functions <async def>. Outer comprehensions implicitly become asynchronous in this case. (Contributed by Serhiy Storchaka in33346.) - A
TypeErroris now raised instead of anAttributeErrorinwithstatements andcontextlib.ExitStack.enter_contextfor objects that do not support thecontext managerprotocol, and inasync withstatements andcontextlib.AsyncExitStack.enter_async_contextfor objects not supporting theasynchronous context managerprotocol. (Contributed by Serhiy Storchaka in12022and44471.) - Added
object.__getstate__, which provides the default implementation of the!__getstate__method.copying andpickleing instances of subclasses of builtin typesbytearray,set,frozenset,collections.OrderedDict,collections.deque,weakref.WeakSet, anddatetime.tzinfonow copies and pickles instance attributes implemented asslots <__slots__>. This change has an unintended side effect: It trips up a small minority of existing Python projects not expectingobject.__getstate__to exist. See the later comments on70766for discussions of what workarounds such code may need. (Contributed by Serhiy Storchaka in26579.)
- Added a
-Pcommand line option and aPYTHONSAFEPATHenvironment variable, which disable the automatic prepending tosys.pathof the script's directory when running a script, or the current directory when using-cand-m. This ensures only stdlib and installed modules are picked up byimport, and avoids unintentionally or maliciously shadowing modules with those in a local (and typically user-writable) directory. (Contributed by Victor Stinner in57684.) - A
"z"option was added to theformatspecthat coerces negative to positive zero after rounding to the format precision. See682for more details. (Contributed by John Belmonte in90153.) - Bytes are no longer accepted on
sys.path. Support broke sometime between Python 3.2 and 3.6, with no one noticing until after Python 3.10.0 was released. In addition, bringing back support would be problematic due to interactions between-bandsys.path_importer_cachewhen there is a mixture ofstrandbyteskeys. (Contributed by Thomas Grainger in91181.)
Other CPython Implementation Changes
- The special methods
~object.__complex__forcomplexand~object.__bytes__forbytesare implemented to support thetyping.SupportsComplexandtyping.SupportsBytesprotocols. (Contributed by Mark Dickinson and Donghee Na in24234.) siphash13is added as a new internal hashing algorithm. It has similar security properties assiphash24, but it is slightly faster for long inputs.str,bytes, and some other types now use it as the default algorithm forhash.552hash-based .pyc files <pyc-invalidation>now usesiphash13too. (Contributed by Inada Naoki in29410.)- When an active exception is re-raised by a
raisestatement with no parameters, the traceback attached to this exception is now alwayssys.exc_info()[1].__traceback__. This means that changes made to the traceback in the currentexceptclause are reflected in the re-raised exception. (Contributed by Irit Katriel in45711.) - The interpreter state's representation of handled exceptions (aka
exc_infoor_PyErr_StackItem) now only has theexc_valuefield;exc_typeandexc_tracebackhave been removed, as they can be derived fromexc_value. (Contributed by Irit Katriel in45711.) - A new command line option,
AppendPath, has been added for the Windows installer. It behaves similarly toPrependPath, but appends the install and scripts directories instead of prepending them. (Contributed by Bastian Neuburger in44934.) - The
PyConfig.module_search_paths_setfield must now be set to1for initialization to usePyConfig.module_search_pathsto initializesys.path. Otherwise, initialization will recalculate the path and replace any values added tomodule_search_paths. - The output of the
--helpoption now fits in 50 lines/80 columns. Information aboutPython environment variables <using-on-envvars>and-Xoptions is now available using the respective--help-envand--help-xoptionsflags, and with the new--help-all. (Contributed by Éric Araujo in46142.) - Converting between
intandstrin bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises aValueErrorif the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for2020-10735. This limit can be configured or disabled by environment variable, command line flag, orsysAPIs. See theinteger string conversion length limitation <int_max_str_digits>documentation. The default limit is 4300 digits in string form.
New Modules
tomllib: For parsing TOML. See680for more details. (Contributed by Taneli Hukkinen in40059.)wsgiref.types:WSGI <3333>-specific types for static type checking. (Contributed by Sebastian Rittau in42012.)
Improved Modules
asyncio
- Added the
~asyncio.TaskGroupclass, anasynchronous context manager <async-context-managers>holding a group of tasks that will wait for all of them upon exit. For new code this is recommended over using~asyncio.create_taskand~asyncio.gatherdirectly. (Contributed by Yury Selivanov and others in90908.) - Added
~asyncio.timeout, an asynchronous context manager for setting a timeout on asynchronous operations. For new code this is recommended over using~asyncio.wait_fordirectly. (Contributed by Andrew Svetlov in90927.) - Added the
~asyncio.Runnerclass, which exposes the machinery used by~asyncio.run. (Contributed by Andrew Svetlov in91218.) - Added the
~asyncio.Barrierclass to the synchronization primitives in the asyncio library, and the related~asyncio.BrokenBarrierErrorexception. (Contributed by Yves Duprat and Andrew Svetlov in87518.) - Added keyword argument all_errors to
asyncio.loop.create_connectionso that multiple connection errors can be raised as anExceptionGroup. - Added the
asyncio.StreamWriter.start_tlsmethod for upgrading existing stream-based connections to TLS. (Contributed by Ian Good in34975.) - Added raw datagram socket functions to the event loop:
~asyncio.loop.sock_sendto,~asyncio.loop.sock_recvfromand~asyncio.loop.sock_recvfrom_into. These have implementations in~asyncio.SelectorEventLoopand~asyncio.ProactorEventLoop. (Contributed by Alex Grönholm in46805.) - Added
~asyncio.Task.cancellingand~asyncio.Task.uncancelmethods to~asyncio.Task. These are primarily intended for internal use, notably by~asyncio.TaskGroup.
contextlib
- Added non parallel-safe
~contextlib.chdircontext manager to change the current working directory and then restore it on exit. Simple wrapper around~os.chdir. (Contributed by Filipe Laíns in25625)
dataclasses
- Change field default mutability check, allowing only defaults which are
hashableinstead of any object which is not an instance ofdict,listorset. (Contributed by Eric V. Smith in44674.)
datetime
- Add
datetime.UTC, a convenience alias fordatetime.timezone.utc. (Contributed by Kabir Kwatra in91973.) datetime.date.fromisoformat,datetime.time.fromisoformatanddatetime.datetime.fromisoformatcan now be used to parse most ISO 8601 formats (barring only those that support fractional hours and minutes). (Contributed by Paul Ganssle in80010.)
enum
- Renamed
!EnumMetato~enum.EnumType(!EnumMetakept as an alias). - Added
~enum.StrEnum, with members that can be used as (and must be) strings. - Added
~enum.ReprEnum, which only modifies the~object.__repr__of members while returning their literal values (rather than names) for~object.__str__and~object.__format__(used bystr,formatandf-strings). - Changed
Enum.__format__() <enum.Enum.__format__>(the default forformat,str.formatandf-strings) to always produce the same result asEnum.__str__() <enum.Enum.__str__>: for enums inheriting from~enum.ReprEnumit will be the member's value; for all other enums it will be the enum and member name (e.g.Color.RED). - Added a new boundary class parameter to
~enum.Flagenums and the~enum.FlagBoundaryenum with its options, to control how to handle out-of-range flag values. - Added the
~enum.verifyenum decorator and the~enum.EnumCheckenum with its options, to check enum classes against several specific constraints. - Added the
~enum.memberand~enum.nonmemberdecorators, to ensure the decorated object is/is not converted to an enum member. - Added the
~enum.propertydecorator, which works likepropertyexcept for enums. Use this instead oftypes.DynamicClassAttribute. - Added the
~enum.global_enumenum decorator, which adjusts~object.__repr__and~object.__str__to show values as members of their module rather than the enum class. For example,'re.ASCII'for the~re.ASCIImember ofre.RegexFlagrather than'RegexFlag.ASCII'. - Enhanced
~enum.Flagto supportlen, iteration andin/not inon its members. For example, the following now works:len(AFlag(3)) == 2 and list(AFlag(3)) == (AFlag.ONE, AFlag.TWO) - Changed
~enum.Enumand~enum.Flagso that members are now defined before~object.__init_subclass__is called;dirnow includes methods, etc., from mixed-in data types. - Changed
~enum.Flagto only consider primary values (power of two) canonical while composite values (3,6,10, etc.) are considered aliases; inverted flags are coerced to their positive equivalent.
fcntl
- On FreeBSD, the
!F_DUP2FDand!F_DUP2FD_CLOEXECflags respectively are supported, the former equals todup2usage while the latter set theFD_CLOEXECflag in addition.
fractions
- Support PEP 515-style initialization of
~fractions.Fractionfrom string. (Contributed by Sergey B Kirpichev in44258.) ~fractions.Fractionnow implements an__int__method, so that anisinstance(some_fraction, typing.SupportsInt)check passes. (Contributed by Mark Dickinson in44547.)
functools
-
functools.singledispatchnow supportstypes.UnionTypeandtyping.Unionas annotations to the dispatch argument.:>>> from functools import singledispatch >>> @singledispatch ... def fun(arg, verbose=False): ... if verbose: ... print("Let me just say,", end=" ") ... print(arg) ... >>> @fun.register ... def _(arg: int | float, verbose=False): ... if verbose: ... print("Strength in numbers, eh?", end=" ") ... print(arg) ... >>> from typing import Union >>> @fun.register ... def _(arg: Union[list, set], verbose=False): ... if verbose: ... print("Enumerate this:") ... for i, elem in enumerate(arg): ... print(i, elem) ...(Contributed by Yurii Karabas in
46014.)
gzip
- The
gzip.compressfunction is now faster when used with the mtime=0 argument as it delegates the compression entirely to a singlezlib.compressoperation. There is one side effect of this change: The gzip file header contains an "OS" byte in its header. That was traditionally always set to a value of 255 representing "unknown" by thegzipmodule. Now, when using~gzip.compresswith mtime=0, it may be set to a different value by the underlying zlib C library Python was linked against. (See112346for details on the side effect.)
hashlib
hashlib.blake2bandhashlib.blake2snow prefer libb2 over Python's vendored copy. (Contributed by Christian Heimes in47095.)- The internal
_sha3module with SHA3 and SHAKE algorithms now uses tiny_sha3 instead of the Keccak Code Package to reduce code and binary size. Thehashlibmodule prefers optimized SHA3 and SHAKE implementations from OpenSSL. The change affects only installations without OpenSSL support. (Contributed by Christian Heimes in47098.) - Add
hashlib.file_digest, a helper function for efficient hashing of files or file-like objects. (Contributed by Christian Heimes in89313.)
IDLE and idlelib
- Apply syntax highlighting to
.pyifiles. (Contributed by Alex Waygood and Terry Jan Reedy in45447.) - Include prompts when saving Shell with inputs and outputs. (Contributed by Terry Jan Reedy in
95191.)
inspect
-
Add
~inspect.getmembers_staticto return all members without triggering dynamic lookup via the descriptor protocol. (Contributed by Weipeng Hong in30533.) -
Add
~inspect.ismethodwrapperfor checking if the type of an object is a~types.MethodWrapperType. (Contributed by Hakan Çelik in29418.) -
Change the frame-related functions in the
inspectmodule to return new~inspect.FrameInfoand~inspect.Tracebackclass instances (backwards compatible with the previousnamed tuple-like interfaces) that includes the extended657position information (end line number, column and end column). The affected functions are:inspect.getframeinfoinspect.getouterframesinspect.getinnerframes,inspect.stackinspect.trace
(Contributed by Pablo Galindo in
88116.)
locale
- Add
locale.getencodingto get the current locale encoding. It is similar tolocale.getpreferredencoding(False)but ignores thePython UTF-8 Mode <utf8-mode>.
logging
- Added
~logging.getLevelNamesMappingto return a mapping from logging level names (e.g.'CRITICAL') to the values of their correspondinglevels(e.g.50, by default). (Contributed by Andrei Kulakovin in88024.) - Added a
~logging.handlers.SysLogHandler.createSocketmethod to~logging.handlers.SysLogHandler, to matchSocketHandler.createSocket() <logging.handlers.SocketHandler.createSocket>. It is called automatically during handler initialization and when emitting an event, if there is no active socket. (Contributed by Kirill Pinchuk in88457.)
math
- Add
math.exp2: return 2 raised to the power of x. (Contributed by Gideon Mitchell in45917.) - Add
math.cbrt: return the cube root of x. (Contributed by Ajith Ramachandran in44357.) - The behaviour of two
math.powcorner cases was changed, for consistency with the IEEE 754 specification. The operationsmath.pow(0.0, -math.inf)andmath.pow(-0.0, -math.inf)now returninf. Previously they raisedValueError. (Contributed by Mark Dickinson in44339.) - The
math.nanvalue is now always available. (Contributed by Victor Stinner in46917.)
operator
- A new function
operator.callhas been added, such thatoperator.call(obj, *args, **kwargs) == obj(*args, **kwargs). (Contributed by Antony Lee in44019.)
os
- On Windows,
os.urandomnow usesBCryptGenRandom(), instead ofCryptGenRandom()which is deprecated. (Contributed by Donghee Na in44611.)
pathlib
~pathlib.Path.globand~pathlib.Path.rglobreturn only directories if pattern ends with a pathname components separator:~os.sepor~os.altsep. (Contributed by Eisuke Kawasima in22276and33392.)
re
- Atomic grouping (
(?>...)) and possessive quantifiers (*+,++,?+,{m,n}+) are now supported in regular expressions. (Contributed by Jeffrey C. Jacobs and Serhiy Storchaka in433030.)
shutil
- Add optional parameter dir_fd in
shutil.rmtree. (Contributed by Serhiy Storchaka in46245.)
socket
- Add CAN Socket support for NetBSD. (Contributed by Thomas Klausner in
30512.) ~socket.create_connectionhas an option to raise, in case of failure to connect, anExceptionGroupcontaining all errors instead of only raising the last error. (Contributed by Irit Katriel in29980.)
sqlite3
- You can now disable the authorizer by passing
Noneto~sqlite3.Connection.set_authorizer. (Contributed by Erlend E. Aasland in44491.) - Collation name
~sqlite3.Connection.create_collationcan now contain any Unicode character. Collation names with invalid characters now raiseUnicodeEncodeErrorinstead ofsqlite3.ProgrammingError. (Contributed by Erlend E. Aasland in44688.) sqlite3exceptions now include the SQLite extended error code as~sqlite3.Error.sqlite_errorcodeand the SQLite error name as~sqlite3.Error.sqlite_errorname. (Contributed by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland in16379and24139.)- Add
~sqlite3.Connection.setlimitand~sqlite3.Connection.getlimittosqlite3.Connectionfor setting and getting SQLite limits by connection basis. (Contributed by Erlend E. Aasland in45243.) sqlite3now setssqlite3.threadsafetybased on the default threading mode the underlying SQLite library has been compiled with. (Contributed by Erlend E. Aasland in45613.)sqlite3C callbacks now use unraisable exceptions if callback tracebacks are enabled. Users can now register anunraisable hook handler <sys.unraisablehook>to improve their debug experience. (Contributed by Erlend E. Aasland in45828.)- Fetch across rollback no longer raises
~sqlite3.InterfaceError. Instead we leave it to the SQLite library to handle these cases. (Contributed by Erlend E. Aasland in44092.) - Add
~sqlite3.Connection.serializeand~sqlite3.Connection.deserializetosqlite3.Connectionfor serializing and deserializing databases. (Contributed by Erlend E. Aasland in41930.) - Add
~sqlite3.Connection.create_window_functiontosqlite3.Connectionfor creating aggregate window functions. (Contributed by Erlend E. Aasland in34916.) - Add
~sqlite3.Connection.blobopentosqlite3.Connection.sqlite3.Bloballows incremental I/O operations on blobs. (Contributed by Aviv Palivoda and Erlend E. Aasland in24905.)
string
- Add
~string.Template.get_identifiersand~string.Template.is_validtostring.Template, which respectively return all valid placeholders, and whether any invalid placeholders are present. (Contributed by Ben Kehoe in90465.)
sys
sys.exc_infonow derives thetypeandtracebackfields from thevalue(the exception instance), so when an exception is modified while it is being handled, the changes are reflected in the results of subsequent calls to!exc_info. (Contributed by Irit Katriel in45711.)- Add
sys.exceptionwhich returns the active exception instance (equivalent tosys.exc_info()[1]). (Contributed by Irit Katriel in46328.) - Add the
sys.flags.safe_path <sys.flags>flag. (Contributed by Victor Stinner in57684.)
sysconfig
- Three new
installation schemes <installation_paths>(posix_venv, nt_venv and venv) were added and are used when Python creates new virtual environments or when it is running from a virtual environment. The first two schemes (posix_venv and nt_venv) are OS-specific for non-Windows and Windows, the venv is essentially an alias to one of them according to the OS Python runs on. This is useful for downstream distributors who modifysysconfig.get_preferred_scheme. Third party code that creates new virtual environments should use the new venv installation scheme to determine the paths, as doesvenv. (Contributed by Miro Hrončok in45413.)
tempfile
~tempfile.SpooledTemporaryFileobjects now fully implement the methods ofio.BufferedIOBaseorio.TextIOBase(depending on file mode). This lets them work correctly with APIs that expect file-like objects, such as compression modules. (Contributed by Carey Metcalfe in70363.)
threading
- On Unix, if the
sem_clockwait()function is available in the C library (glibc 2.30 and newer), thethreading.Lock.acquiremethod now uses the monotonic clock (time.CLOCK_MONOTONIC) for the timeout, rather than using the system clock (time.CLOCK_REALTIME), to not be affected by system clock changes. (Contributed by Victor Stinner in41710.)
time
- On Unix,
time.sleepnow uses theclock_nanosleep()ornanosleep()function, if available, which has a resolution of 1 nanosecond (10-9 seconds), rather than usingselect()which has a resolution of 1 microsecond (10-6 seconds). (Contributed by Benjamin Szőke and Victor Stinner in21302.) - On Windows 8.1 and newer,
time.sleepnow uses a waitable timer based on high-resolution timers which has a resolution of 100 nanoseconds (10-7 seconds). Previously, it had a resolution of 1 millisecond (10-3 seconds). (Contributed by Benjamin Szőke, Donghee Na, Eryk Sun and Victor Stinner in21302and45429.)
tkinter
- Added method
info_patchlevel()which returns the exact version of the Tcl library as a named tuple similar tosys.version_info. (Contributed by Serhiy Storchaka in91827.)
traceback
- Add
traceback.StackSummary.format_frame_summaryto allow users to override which frames appear in the traceback, and how they are formatted. (Contributed by Ammar Askar in44569.) - Add
traceback.TracebackException.print, which prints the formatted~traceback.TracebackExceptioninstance to a file. (Contributed by Irit Katriel in33809.)
typing
For major changes, see new-feat-related-type-hints-311.
- Add
typing.assert_neverandtyping.Never.typing.assert_neveris useful for asking a type checker to confirm that a line of code is not reachable. At runtime, it raises anAssertionError. (Contributed by Jelle Zijlstra in90633.) - Add
typing.reveal_type. This is useful for asking a type checker what type it has inferred for a given expression. At runtime it prints the type of the received value. (Contributed by Jelle Zijlstra in90572.) - Add
typing.assert_type. This is useful for asking a type checker to confirm that the type it has inferred for a given expression matches the given type. At runtime it simply returns the received value. (Contributed by Jelle Zijlstra in90638.) typing.TypedDicttypes can now be generic. (Contributed by Samodya Abeysiriwardane in89026.)~typing.NamedTupletypes can now be generic. (Contributed by Serhiy Storchaka in43923.)- Allow subclassing of
typing.Any. This is useful for avoiding type checker errors related to highly dynamic class, such as mocks. (Contributed by Shantanu Jain in91154.) - The
typing.finaldecorator now sets the__final__attributed on the decorated object. (Contributed by Jelle Zijlstra in90500.) - The
typing.get_overloadsfunction can be used for introspecting the overloads of a function.typing.clear_overloadscan be used to clear all registered overloads of a function. (Contributed by Jelle Zijlstra in89263.) - The
~object.__init__method of~typing.Protocolsubclasses is now preserved. (Contributed by Adrian Garcia Badarasco in88970.) - The representation of empty tuple types (
Tuple[()]) is simplified. This affects introspection, e.g.get_args(Tuple[()])now evaluates to()instead of((),). (Contributed by Serhiy Storchaka in91137.) - Loosen runtime requirements for type annotations by removing the callable check in the private
typing._type_checkfunction. (Contributed by Gregory Beauregard in90802.) typing.get_type_hintsnow supports evaluating strings as forward references inPEP 585 generic aliases <types-genericalias>. (Contributed by Niklas Rosenstein in85542.)typing.get_type_hintsno longer adds~typing.Optionalto parameters withNoneas a default. (Contributed by Nikita Sobolev in90353.)typing.get_type_hintsnow supports evaluating bare stringified~typing.ClassVarannotations. (Contributed by Gregory Beauregard in90711.)typing.no_type_checkno longer modifies external classes and functions. It also now correctly marks classmethods as not to be type checked. (Contributed by Nikita Sobolev in90729.)
unicodedata
- The Unicode database has been updated to version 14.0.0. (Contributed by Benjamin Peterson in
45190).
unittest
- Added methods
~unittest.TestCase.enterContextand~unittest.TestCase.enterClassContextof class~unittest.TestCase, method~unittest.IsolatedAsyncioTestCase.enterAsyncContextof class~unittest.IsolatedAsyncioTestCaseand functionunittest.enterModuleContext. (Contributed by Serhiy Storchaka in45046.)
venv
- When new Python virtual environments are created, the venv
sysconfig installation scheme <installation_paths>is used to determine the paths inside the environment. When Python runs in a virtual environment, the same installation scheme is the default. That means that downstream distributors can change the default sysconfig install scheme without changing behavior of virtual environments. Third party code that also creates new virtual environments should do the same. (Contributed by Miro Hrončok in45413.)
warnings
warnings.catch_warningsnow accepts arguments forwarnings.simplefilter, providing a more concise way to locally ignore warnings or convert them to errors. (Contributed by Zac Hatfield-Dodds in47074.)
zipfile
- Added support for specifying member name encoding for reading metadata in a
~zipfile.ZipFile's directory and file headers. (Contributed by Stephen J. Turnbull and Serhiy Storchaka in28080.) - Added
ZipFile.mkdir() <zipfile.ZipFile.mkdir>for creating new directories inside ZIP archives. (Contributed by Sam Ezeh in49083.) - Added
~zipfile.Path.stem,~zipfile.Path.suffixand~zipfile.Path.suffixestozipfile.Path. (Contributed by Miguel Brito in88261.)
Optimizations
This section covers specific optimizations independent of the whatsnew311-faster-cpython project, which is covered in its own section.
- The compiler now optimizes simple
printf-style % formatting <old-string-formatting>on string literals containing only the format codes%s,%rand%aand makes it as fast as a correspondingf-stringexpression. (Contributed by Serhiy Storchaka in28307.) - Integer division (
//) is better tuned for optimization by compilers. It is now around 20% faster on x86-64 when dividing anintby a value smaller than2**30. (Contributed by Gregory P. Smith and Tim Peters in90564.) sumis now nearly 30% faster for integers smaller than2**30. (Contributed by Stefan Behnel in68264.)- Resizing lists is streamlined for the common case, speeding up
list.appendby ≈15% and simplelist comprehensions by up to 20-30% (Contributed by Dennis Sweeney in91165.) - Dictionaries don't store hash values when all keys are Unicode objects, decreasing
dictsize. For example,sys.getsizeof(dict.fromkeys("abcdefg"))is reduced from 352 bytes to 272 bytes (23% smaller) on 64-bit platforms. (Contributed by Inada Naoki in46845.) - Using
asyncio.DatagramProtocolis now orders of magnitude faster when transferring large files over UDP, with speeds over 100 times higher for a ≈60 MiB file. (Contributed by msoxzw in91487.) mathfunctions~math.comband~math.permare now ≈10 times faster for large arguments (with a larger speedup for larger k). (Contributed by Serhiy Storchaka in37295.)- The
statisticsfunctions~statistics.mean,~statistics.varianceand~statistics.stdevnow consume iterators in one pass rather than converting them to alistfirst. This is twice as fast and can save substantial memory. (Contributed by Raymond Hettinger in90415.) unicodedata.normalizenow normalizes pure-ASCII strings in constant time. (Contributed by Donghee Na in44987.)
Faster CPython
CPython 3.11 is an average of 25% faster than CPython 3.10 as measured with the pyperformance benchmark suite, when compiled with GCC on Ubuntu Linux. Depending on your workload, the overall speedup could be 10-60%.
This project focuses on two major areas in Python: whatsnew311-faster-startup and whatsnew311-faster-runtime. Optimizations not covered by this project are listed separately under whatsnew311-optimizations.
Faster Startup
Frozen imports / Static code objects
Python caches bytecode in the __pycache__ <tut-pycache> directory to speed up module loading.
Previously in 3.10, Python module execution looked like this:
Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate
In Python 3.11, the core modules essential for Python startup are "frozen". This means that their codeobjects (and bytecode) are statically allocated by the interpreter. This reduces the steps in module execution process to:
Statically allocated code object -> Evaluate
Interpreter startup is now 10-15% faster in Python 3.11. This has a big impact for short-running programs using Python.
(Contributed by Eric Snow, Guido van Rossum and Kumar Aditya in many issues.)
Faster Runtime
Cheaper, lazy Python frames
Python frames, holding execution information, are created whenever Python calls a Python function. The following are new frame optimizations:
- Streamlined the frame creation process.
- Avoided memory allocation by generously re-using frame space on the C stack.
- Streamlined the internal frame struct to contain only essential information. Frames previously held extra debugging and memory management information.
Old-style frame objects <frame-objects> are now created only when requested by debuggers or by Python introspection functions such as sys._getframe and inspect.currentframe. For most user code, no frame objects are created at all. As a result, nearly all Python functions calls have sped up significantly. We measured a 3-7% speedup in pyperformance.
(Contributed by Mark Shannon in 44590.)
Inlined Python function calls
During a Python function call, Python will call an evaluating C function to interpret that function's code. This effectively limits pure Python recursion to what's safe for the C stack.
In 3.11, when CPython detects Python code calling another Python function, it sets up a new frame, and "jumps" to the new code inside the new frame. This avoids calling the C interpreting function altogether.
Most Python function calls now consume no C stack space, speeding them up. In simple recursive functions like fibonacci or factorial, we observed a 1.7x speedup. This also means recursive functions can recurse significantly deeper (if the user increases the recursion limit with sys.setrecursionlimit). We measured a 1-3% improvement in pyperformance.
(Contributed by Pablo Galindo and Mark Shannon in 45256.)
PEP 659: Specializing Adaptive Interpreter
659 is one of the key parts of the Faster CPython project. The general idea is that while Python is a dynamic language, most code has regions where objects and types rarely change. This concept is known as type stability.
At runtime, Python will try to look for common patterns and type stability in the executing code. Python will then replace the current operation with a more specialized one. This specialized operation uses fast paths available only to those use cases/types, which generally outperform their generic counterparts. This also brings in another concept called inline caching, where Python caches the results of expensive operations directly in the bytecode.
The specializer will also combine certain common instruction pairs into one superinstruction, reducing the overhead during execution.
Python will only specialize when it sees code that is "hot" (executed multiple times). This prevents Python from wasting time on run-once code. Python can also de-specialize when code is too dynamic or when the use changes. Specialization is attempted periodically, and specialization attempts are not too expensive, allowing specialization to adapt to new circumstances.
(PEP written by Mark Shannon, with ideas inspired by Stefan Brunthaler. See 659 for more information. Implementation by Mark Shannon and Brandt Bucher, with additional help from Irit Katriel and Dennis Sweeney.)
Operation |
Form |
Specialization |
Operation speedup (up to) |
Contributor(s) |
|---|---|---|---|---|
Binary operations |
|
Binary add, multiply and subtract for common types such as |
10% |
Mark Shannon, Donghee Na, Brandt Bucher, Dennis Sweeney |
Subscript |
|
Subscripting container types such as Subscripting custom |
10-25% |
Irit Katriel, Mark Shannon |
Store subscript |
|
Similar to subscripting specialization above. |
10-25% |
Dennis Sweeney |
Calls |
|
Calls to common builtin (C) functions and types such as |
20% |
Mark Shannon, Ken Jin |
Load global variable |
|
The object's index in the globals/builtins namespace is cached. Loading globals and builtins require zero namespace lookups. |
Mark Shannon |
|
Load attribute |
|
Similar to loading global variables. The attribute's index inside the class/object's namespace is cached. In most cases, attribute loading will require zero namespace lookups. |
Mark Shannon |
|
Load methods for call |
|
The actual address of the method is cached. Method loading now has no namespace lookups -- even for classes with long inheritance chains. |
10-20% |
Ken Jin, Mark Shannon |
Store attribute |
|
Similar to load attribute optimization. |
2% in pyperformance |
Mark Shannon |
Unpack Sequence |
|
Specialized for common containers such as |
8% |
Brandt Bucher |
Misc
- Objects now require less memory due to lazily created object namespaces. Their namespace dictionaries now also share keys more freely. (Contributed Mark Shannon in
45340and40116.) - "Zero-cost" exceptions are implemented, eliminating the cost of
trystatements when no exception is raised. (Contributed by Mark Shannon in40222.) - A more concise representation of exceptions in the interpreter reduced the time required for catching an exception by about 10%. (Contributed by Irit Katriel in
45711.) re's regular expression matching engine has been partially refactored, and now uses computed gotos (or "threaded code") on supported platforms. As a result, Python 3.11 executes the pyperformance regular expression benchmarks up to 10% faster than Python 3.10. (Contributed by Brandt Bucher in91404.)
FAQ
How should I write my code to utilize these speedups?
Write Pythonic code that follows common best practices; you don't have to change your code. The Faster CPython project optimizes for common code patterns we observe.
Will CPython 3.11 use more memory?
Maybe not; we don't expect memory use to exceed 20% higher than 3.10. This is offset by memory optimizations for frame objects and object dictionaries as mentioned above.
I don't see any speedups in my workload. Why?
Certain code won't have noticeable benefits. If your code spends most of its time on I/O operations, or already does most of its computation in a C extension library like NumPy, there won't be significant speedups. This project currently benefits pure-Python workloads the most.
Furthermore, the pyperformance figures are a geometric mean. Even within the pyperformance benchmarks, certain benchmarks have slowed down slightly, while others have sped up by nearly 2x!
Is there a JIT compiler?
No. We're still exploring other optimizations.
About
Faster CPython explores optimizations for CPython. The main team is funded by Microsoft to work on this full-time. Pablo Galindo Salgado is also funded by Bloomberg LP to work on the project part-time. Finally, many contributors are volunteers from the community.
CPython bytecode changes
The bytecode now contains inline cache entries, which take the form of the newly-added CACHE instructions. Many opcodes expect to be followed by an exact number of caches, and instruct the interpreter to skip over them at runtime. Populated caches can look like arbitrary instructions, so great care should be taken when reading or modifying raw, adaptive bytecode containing quickened data.
New opcodes
!ASYNC_GEN_WRAP,RETURN_GENERATORandSEND, used in generators and co-routines.COPY_FREE_VARS, which avoids needing special caller-side code for closures.JUMP_BACKWARD_NO_INTERRUPT, for use in certain loops where handling interrupts is undesirable.MAKE_CELL, to createcell-objects.CHECK_EG_MATCHand!PREP_RERAISE_STAR, to handle thenew exception groups and except* <whatsnew311-pep654>added in654.PUSH_EXC_INFO, for use in exception handlers.RESUME, a no-op, for internal tracing, debugging and optimization checks.
Replaced opcodes
Replaced Opcode(s) |
New Opcode(s) |
Notes |
|---|---|---|
!BINARY_*!INPLACE_* |
|
Replaced all numeric binary/in-place opcodes with a single opcode |
!CALL_FUNCTION!CALL_FUNCTION_KW!CALL_METHOD |
CALL!KW_NAMES!PRECALLPUSH_NULL |
Decouples argument shifting for methods from handling of keyword arguments; allows better specialization of calls |
!DUP_TOP!DUP_TOP_TWO!ROT_TWO!ROT_THREE!ROT_FOUR!ROT_N |
COPYSWAP |
Stack manipulation instructions |
!JUMP_IF_NOT_EXC_MATCH |
CHECK_EXC_MATCH |
Now performs check but doesn't jump |
!JUMP_ABSOLUTE!POP_JUMP_IF_FALSE!POP_JUMP_IF_TRUE |
JUMP_BACKWARD!POP_JUMP_BACKWARD_IF_*!POP_JUMP_FORWARD_IF_* |
See1; |
!SETUP_WITH!SETUP_ASYNC_WITH |
|
|
All jump opcodes are now relative, including the existing
!JUMP_IF_TRUE_OR_POPand!JUMP_IF_FALSE_OR_POP. The argument is now an offset from the current instruction rather than an absolute location.↩︎
Changed/removed opcodes
- Changed
MATCH_CLASSandMATCH_KEYSto no longer push an additional boolean value to indicate success/failure. Instead,Noneis pushed on failure in place of the tuple of extracted values. - Changed opcodes that work with exceptions to reflect them now being represented as one item on the stack instead of three (see
89874). - Removed
!COPY_DICT_WITHOUT_KEYS,!GEN_START,!POP_BLOCK,!SETUP_FINALLYand!YIELD_FROM.
Deprecated
This section lists Python APIs that have been deprecated in Python 3.11.
Deprecated C APIs are listed separately <whatsnew311-c-api-deprecated>.
Language/Builtins
- Chaining
classmethoddescriptors (introduced in19072) is now deprecated. It can no longer be used to wrap other descriptors such asproperty. The core design of this feature was flawed and caused a number of downstream problems. To "pass-through" aclassmethod, consider using the!__wrapped__attribute that was added in Python 3.10. (Contributed by Raymond Hettinger in89519.) - Octal escapes in string and bytes literals with values larger than
0o377(255 in decimal) now produce aDeprecationWarning. In a future Python version, they will raise aSyntaxWarningand eventually aSyntaxError. (Contributed by Serhiy Storchaka in81548.) - The delegation of
intto~object.__trunc__is now deprecated. Callingint(a)whentype(a)implements!__trunc__but not~object.__int__or~object.__index__now raises aDeprecationWarning. (Contributed by Zackery Spytz in44977.)
Modules
-
594led to the deprecations of the following modules slated for removal in Python 3.13:!aifc!chunk!msilib!pipes!telnetlib!audioop!crypt!nis!sndhdr!uu!cgi!imghdr!nntplib!spwd!xdrlib!cgitb!mailcap!ossaudiodev!sunau(Contributed by Brett Cannon in
47061and Victor Stinner in68966.) -
The
!asynchat,!asyncoreand!smtpdmodules have been deprecated since at least Python 3.6. Their documentation and deprecation warnings have now been updated to note they will be removed in Python 3.12. (Contributed by Hugo van Kemenade in47022.) -
The
!lib2to3package and2to3tool are now deprecated and may not be able to parse Python 3.10 or newer. See617, introducing the new PEG parser, for details. (Contributed by Victor Stinner in40360.) -
Undocumented modules
!sre_compile,!sre_constantsand!sre_parseare now deprecated. (Contributed by Serhiy Storchaka in47152.)
Standard Library
-
The following have been deprecated in
configparsersince Python 3.2. Their deprecation warnings have now been updated to note they will be removed in Python 3.12:- the
!configparser.SafeConfigParserclass - the
!configparser.ParsingError.filenameproperty - the
!configparser.RawConfigParser.readfpmethod
(Contributed by Hugo van Kemenade in
45173.) - the
-
!configparser.LegacyInterpolationhas been deprecated in the docstring since Python 3.2, and is not listed in theconfigparserdocumentation. It now emits aDeprecationWarningand will be removed in Python 3.13. Useconfigparser.BasicInterpolationorconfigparser.ExtendedInterpolationinstead. (Contributed by Hugo van Kemenade in46607.) -
The older set of
importlib.resourcesfunctions were deprecated in favor of the replacements added in Python 3.9 and will be removed in a future Python version, due to not supporting resources located within package subdirectories:!importlib.resources.contents!importlib.resources.is_resource!importlib.resources.open_binary!importlib.resources.open_text!importlib.resources.read_binary!importlib.resources.read_text!importlib.resources.path
-
The
locale.getdefaultlocalefunction is deprecated and will be removed in Python 3.15. Uselocale.setlocale,locale.getpreferredencoding(False) <locale.getpreferredencoding>andlocale.getlocalefunctions instead. (Contributed by Victor Stinner in90817.) -
The
!locale.resetlocalefunction is deprecated and will be removed in Python 3.13. Uselocale.setlocale(locale.LC_ALL, "")instead. (Contributed by Victor Stinner in90817.) -
Stricter rules will now be applied for numerical group references and group names in
regular expressions <re-syntax>. Only sequences of ASCII digits will now be accepted as a numerical reference, and the group name inbytespatterns and replacement strings can only contain ASCII letters, digits and underscores. For now, a deprecation warning is raised for syntax violating these rules. (Contributed by Serhiy Storchaka in91760.) -
In the
remodule, the!re.templatefunction and the corresponding!re.TEMPLATEand!re.Tflags are deprecated, as they were undocumented and lacked an obvious purpose. They will be removed in Python 3.13. (Contributed by Serhiy Storchaka and Miro Hrončok in92728.) -
!turtle.settiltanglehas been deprecated since Python 3.1; it now emits a deprecation warning and will be removed in Python 3.13. Useturtle.tiltangleinstead (it was earlier incorrectly marked as deprecated, and its docstring is now corrected). (Contributed by Hugo van Kemenade in45837.) -
typing.Text, which exists solely to provide compatibility support between Python 2 and Python 3 code, is now deprecated. Its removal is currently unplanned, but users are encouraged to usestrinstead wherever possible. (Contributed by Alex Waygood in92332.) -
The keyword argument syntax for constructing
typing.TypedDicttypes is now deprecated. Support will be removed in Python 3.13. (Contributed by Jingchen Ye in90224.) -
!webbrowser.MacOSXis deprecated and will be removed in Python 3.13. It is untested, undocumented, and not used bywebbrowseritself. (Contributed by Donghee Na in42255.) -
The behavior of returning a value from a
~unittest.TestCaseand~unittest.IsolatedAsyncioTestCasetest methods (other than the defaultNonevalue) is now deprecated. -
Deprecated the following not-formally-documented
unittestfunctions, scheduled for removal in Python 3.13:!unittest.findTestCases!unittest.makeSuite!unittest.getTestCaseNames
Use
~unittest.TestLoadermethods instead:unittest.TestLoader.loadTestsFromModuleunittest.TestLoader.loadTestsFromTestCaseunittest.TestLoader.getTestCaseNames
(Contributed by Erlend E. Aasland in
5846.) -
!unittest.TestProgram.usageExitis marked deprecated, to be removed in 3.13. (Contributed by Carlos Damázio in67048.)
Pending Removal in Python 3.12
The following Python APIs have been deprecated in earlier Python releases, and will be removed in Python 3.12.
C APIs pending removal are listed separately <whatsnew311-c-api-pending-removal>.
-
The
!asynchatmodule -
The
!asyncoremodule -
The
entire distutils package <distutils-deprecated> -
The
!impmodule -
The
typing.io <typing.IO>namespace -
The
typing.re <typing.Pattern>namespace -
!cgi.log -
!importlib.find_loader -
!importlib.abc.Loader.module_repr -
!importlib.abc.MetaPathFinder.find_module -
!importlib.abc.PathEntryFinder.find_loader -
!importlib.abc.PathEntryFinder.find_module -
!importlib.machinery.BuiltinImporter.find_module -
!importlib.machinery.BuiltinImporter.module_repr -
!importlib.machinery.FileFinder.find_loader -
!importlib.machinery.FileFinder.find_module -
!importlib.machinery.FrozenImporter.find_module -
!importlib.machinery.FrozenImporter.module_repr -
!importlib.machinery.PathFinder.find_module -
!importlib.machinery.WindowsRegistryFinder.find_module -
!importlib.util.module_for_loader -
!importlib.util.set_loader_wrapper -
!importlib.util.set_package_wrapper -
!pkgutil.ImpImporter -
!pkgutil.ImpLoader -
!pathlib.Path.link_to -
!sqlite3.enable_shared_cache -
!sqlite3.OptimizedUnicode -
!PYTHONTHREADDEBUGenvironment variable -
The following deprecated aliases in
unittest:Deprecated alias Method Name Deprecated in failUnless.assertTrue3.1 failIf.assertFalse3.1 failUnlessEqual.assertEqual3.1 failIfEqual.assertNotEqual3.1 failUnlessAlmostEqual.assertAlmostEqual3.1 failIfAlmostEqual.assertNotAlmostEqual3.1 failUnlessRaises.assertRaises3.1 assert_.assertTrue3.2 assertEquals.assertEqual3.2 assertNotEquals.assertNotEqual3.2 assertAlmostEquals.assertAlmostEqual3.2 assertNotAlmostEquals.assertNotAlmostEqual3.2 assertRegexpMatches.assertRegex3.2 assertRaisesRegexp.assertRaisesRegex3.2 assertNotRegexpMatches.assertNotRegex3.5
Removed
This section lists Python APIs that have been removed in Python 3.11.
Removed C APIs are listed separately <whatsnew311-c-api-removed>.
-
Removed the
!@asyncio.coroutinedecoratorenabling legacy generator-based coroutines to be compatible withasync/awaitcode. The function has been deprecated since Python 3.8 and the removal was initially scheduled for Python 3.10. Useasync definstead. (Contributed by Illia Volochii in43216.) -
Removed
!asyncio.coroutines.CoroWrapperused for wrapping legacy generator-based coroutine objects in the debug mode. (Contributed by Illia Volochii in43216.) -
Due to significant security concerns, the reuse_address parameter of
asyncio.loop.create_datagram_endpoint, disabled in Python 3.9, is now entirely removed. This is because of the behavior of the socket optionSO_REUSEADDRin UDP. (Contributed by Hugo van Kemenade in45129.) -
Removed the
!binhexmodule, deprecated in Python 3.9. Also removed the related, similarly-deprecatedbinasciifunctions:!binascii.a2b_hqx!binascii.b2a_hqx!binascii.rlecode_hqx!binascii.rldecode_hqx
The
binascii.crc_hqxfunction remains available.(Contributed by Victor Stinner in
45085.) -
Removed the
!distutilsbdist_msicommand deprecated in Python 3.9. Usebdist_wheel(wheel packages) instead. (Contributed by Hugo van Kemenade in45124.) -
Removed the
~object.__getitem__methods ofxml.dom.pulldom.DOMEventStream,wsgiref.util.FileWrapperandfileinput.FileInput, deprecated since Python 3.9. (Contributed by Hugo van Kemenade in45132.) -
Removed the deprecated
gettextfunctions!lgettext,!ldgettext,!lngettextand!ldngettext. Also removed the!bind_textdomain_codesetfunction, the!NullTranslations.output_charsetand!NullTranslations.set_output_charsetmethods, and the codeset parameter of!translationand!install, since they are only used for the!l*gettextfunctions. (Contributed by Donghee Na and Serhiy Storchaka in44235.) -
Removed from the
inspectmodule:- The
!getargspecfunction, deprecated since Python 3.0; useinspect.signatureorinspect.getfullargspecinstead. - The
!formatargspecfunction, deprecated since Python 3.5; use theinspect.signaturefunction or theinspect.Signatureobject directly. - The undocumented
!Signature.from_builtinand!Signature.from_functionmethods, deprecated since Python 3.5; use theSignature.from_callable() <inspect.Signature.from_callable>method instead.
(Contributed by Hugo van Kemenade in
45320.) - The
-
Removed the
~object.__class_getitem__method frompathlib.PurePath, because it was not used and added by mistake in previous versions. (Contributed by Nikita Sobolev in46483.) -
Removed the
!MailmanProxyclass in the!smtpdmodule, as it is unusable without the external!mailmanpackage. (Contributed by Donghee Na in35800.) -
Removed the deprecated
!splitmethod of!_tkinter.TkappType. (Contributed by Erlend E. Aasland in38371.) -
Removed namespace package support from
unittestdiscovery. It was introduced in Python 3.4 but has been broken since Python 3.7. (Contributed by Inada Naoki in23882.) -
Removed the undocumented private
!float.__set_format__method, previously known as!float.__setformat__in Python 3.7. Its docstring said: "You probably don't want to use this function. It exists mainly to be used in Python's test suite." (Contributed by Victor Stinner in46852.) -
The
!--experimental-isolated-subinterpretersconfigure flag (and corresponding!EXPERIMENTAL_ISOLATED_SUBINTERPRETERSmacro) have been removed. -
Pynche--- The Pythonically Natural Color and Hue Editor --- has been moved out ofTools/scriptsand is being developed independently from the Python source tree.
Porting to Python 3.11
This section lists previously described changes and other bugfixes in the Python API that may require changes to your Python code.
Porting notes for the C API are listed separately <whatsnew311-c-api-porting>.
open,io.open,codecs.openandfileinput.FileInputno longer accept'U'("universal newline") in the file mode. In Python 3, "universal newline" mode is used by default whenever a file is opened in text mode, and the'U'flag has been deprecated since Python 3.3. Thenewline parameter <open-newline-parameter>to these functions controls how universal newlines work. (Contributed by Victor Stinner in37330.)ast.ASTnode positions are now validated when provided tocompileand other related functions. If invalid positions are detected, aValueErrorwill be raised. (Contributed by Pablo Galindo in93351)- Prohibited passing non-
concurrent.futures.ThreadPoolExecutorexecutors toasyncio.loop.set_default_executorfollowing a deprecation in Python 3.8. (Contributed by Illia Volochii in43234.) calendar: Thecalendar.LocaleTextCalendarandcalendar.LocaleHTMLCalendarclasses now uselocale.getlocale, instead of usinglocale.getdefaultlocale, if no locale is specified. (Contributed by Victor Stinner in46659.)- The
pdbmodule now reads the.pdbrcconfiguration file with the'UTF-8'encoding. (Contributed by Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి) in41137.) - The population parameter of
random.samplemust be a sequence, and automatic conversion ofsets tolists is no longer supported. Also, if the sample size is larger than the population size, aValueErroris raised. (Contributed by Raymond Hettinger in40465.) - The random optional parameter of
random.shufflewas removed. It was previously an arbitrary random function to use for the shuffle; now,random.random(its previous default) will always be used. - In
rere-syntax, global inline flags (e.g.(?i)) can now only be used at the start of regular expressions. Using them elsewhere has been deprecated since Python 3.6. (Contributed by Serhiy Storchaka in47066.) - In the
remodule, several long-standing bugs where fixed that, in rare cases, could cause capture groups to get the wrong result. Therefore, this could change the captured output in these cases. (Contributed by Ma Lin in35859.)
Build Changes
-
CPython now has
11Tier 3 support <11#tier-3>for cross compiling to the WebAssembly platforms Emscripten (wasm32-unknown-emscripten, i.e. Python in the browser) and WebAssembly System Interface (WASI) (wasm32-unknown-wasi). The effort is inspired by previous work like Pyodide. These platforms provide a limited subset of POSIX APIs; Python standard libraries features and modules related to networking, processes, threading, signals, mmap, and users/groups are not available or don't work. (Emscripten contributed by Christian Heimes and Ethan Smith in84461and WASI contributed by Christian Heimes in90473; platforms promoted in95085) -
Building CPython now requires:
- A C11 compiler and standard library. Optional C11 features are not required. (Contributed by Victor Stinner in
46656,45440and46640.) - Support for IEEE 754 floating-point numbers. (Contributed by Victor Stinner in
46917.)
- A C11 compiler and standard library. Optional C11 features are not required. (Contributed by Victor Stinner in
-
The
!Py_NO_NANmacro has been removed. Since CPython now requires IEEE 754 floats, NaN values are always available. (Contributed by Victor Stinner in46656.) -
The
tkinterpackage now requires Tcl/Tk version 8.5.12 or newer. (Contributed by Serhiy Storchaka in46996.) -
Build dependencies, compiler flags, and linker flags for most stdlib extension modules are now detected by
configure. libffi, libnsl, libsqlite3, zlib, bzip2, liblzma, libcrypt, Tcl/Tk, and uuid flags are detected by pkg-config (when available).tkinternow requires a pkg-config command to detect development settings for Tcl/Tk headers and libraries. (Contributed by Christian Heimes and Erlend Egeberg Aasland in45847,45747, and45763.) -
libpython is no longer linked against libcrypt. (Contributed by Mike Gilbert in
45433.) -
CPython can now be built with the ThinLTO option via passing
thinto--with-lto, i.e.--with-lto=thin. (Contributed by Donghee Na and Brett Holman in44340.) -
Freelists for object structs can now be disabled. A new
configureoption--without-freelistscan be used to disable all freelists except empty tuple singleton. (Contributed by Christian Heimes in45522.) -
Modules/SetupandModules/makesetuphave been improved and tied up. Extension modules can now be built throughmakesetup. All except some test modules can be linked statically into a main binary or library. (Contributed by Brett Cannon and Christian Heimes in45548,45570,45571, and43974.)[!NOTE] Use the environment variables
!TCLTK_CFLAGSand!TCLTK_LIBSto manually specify the location of Tcl/Tk headers and libraries. Theconfigureoptions!--with-tcltk-includesand!--with-tcltk-libshave been removed.On RHEL 7 and CentOS 7 the development packages do not provide
tcl.pcandtk.pc; useTCLTK_LIBS="-ltk8.5 -ltkstub8.5 -ltcl8.5". The directoryMisc/rhel7contains.pcfiles and instructions on how to build Python with RHEL 7's and CentOS 7's Tcl/Tk and OpenSSL. -
CPython will now use 30-bit digits by default for the Python
intimplementation. Previously, the default was to use 30-bit digits on platforms withSIZEOF_VOID_P >= 8, and 15-bit digits otherwise. It's still possible to explicitly request use of 15-bit digits via either the--enable-big-digitsoption to the configure script or (for Windows) thePYLONG_BITS_IN_DIGITvariable inPC/pyconfig.h, but this option may be removed at some point in the future. (Contributed by Mark Dickinson in45569.)
C API Changes
New Features
-
Add a new
PyType_GetNamefunction to get type's short name. (Contributed by Hai Shi in42035.) -
Add a new
PyType_GetQualNamefunction to get type's qualified name. (Contributed by Hai Shi in42035.) -
Add new
PyThreadState_EnterTracingandPyThreadState_LeaveTracingfunctions to the limited C API to suspend and resume tracing and profiling. (Contributed by Victor Stinner in43760.) -
Added the
Py_Versionconstant which bears the same value asPY_VERSION_HEX. (Contributed by Gabriele N. Tornetta in43931.) -
Py_bufferand APIs are now part of the limited API and the stable ABI:PyObject_CheckBufferPyObject_GetBufferPyBuffer_GetPointerPyBuffer_SizeFromFormatPyBuffer_ToContiguousPyBuffer_FromContiguousPyObject_CopyDataPyBuffer_IsContiguousPyBuffer_FillContiguousStridesPyBuffer_FillInfoPyBuffer_ReleasePyMemoryView_FromBuffer~PyBufferProcs.bf_getbufferand~PyBufferProcs.bf_releasebuffertype slots
(Contributed by Christian Heimes in
45459.) -
Added the
PyType_GetModuleByDeffunction, used to get the module in which a method was defined, in cases where this information is not available directly (viaPyCMethod). (Contributed by Petr Viktorin in46613.) -
Add new functions to pack and unpack C double (serialize and deserialize):
PyFloat_Pack2,PyFloat_Pack4,PyFloat_Pack8,PyFloat_Unpack2,PyFloat_Unpack4andPyFloat_Unpack8. (Contributed by Victor Stinner in46906.) -
Add new functions to get frame object attributes:
PyFrame_GetBuiltins,PyFrame_GetGenerator,PyFrame_GetGlobals,PyFrame_GetLasti. -
Added two new functions to get and set the active exception instance:
PyErr_GetHandledExceptionandPyErr_SetHandledException. These are alternatives toPyErr_SetExcInfo()andPyErr_GetExcInfo()which work with the legacy 3-tuple representation of exceptions. (Contributed by Irit Katriel in46343.) -
Added the
PyConfig.safe_pathmember. (Contributed by Victor Stinner in57684.)
Porting to Python 3.11
-
Some macros have been converted to static inline functions to avoid macro pitfalls. The change should be mostly transparent to users, as the replacement functions will cast their arguments to the expected types to avoid compiler warnings due to static type checks. However, when the limited C API is set to >=3.11, these casts are not done, and callers will need to cast arguments to their expected types. See
670for more details. (Contributed by Victor Stinner and Erlend E. Aasland in89653.) -
PyErr_SetExcInfo()no longer uses thetypeandtracebackarguments, the interpreter now derives those values from the exception instance (thevalueargument). The function still steals references of all three arguments. (Contributed by Irit Katriel in45711.) -
PyErr_GetExcInfo()now derives thetypeandtracebackfields of the result from the exception instance (thevaluefield). (Contributed by Irit Katriel in45711.) -
_frozenhas a newis_packagefield to indicate whether or not the frozen module is a package. Previously, a negative value in thesizefield was the indicator. Now only non-negative values be used forsize. (Contributed by Kumar Aditya in46608.) -
_PyFrameEvalFunctionnow takes_PyInterpreterFrame*as its second parameter, instead ofPyFrameObject*. See523for more details of how to use this function pointer type. -
!PyCode_Newand!PyCode_NewWithPosOnlyArgsnow take an additionalexception_tableargument. Using these functions should be avoided, if at all possible. To get a custom code object: create a code object using the compiler, then get a modified version with thereplacemethod. -
PyCodeObjectno longer has theco_code,co_varnames,co_cellvarsandco_freevarsfields. Instead, usePyCode_GetCode,PyCode_GetVarnames,PyCode_GetCellvarsandPyCode_GetFreevarsrespectively to access them via the C API. (Contributed by Brandt Bucher in46841and Ken Jin in92154and94936.) -
The old trashcan macros (
Py_TRASHCAN_SAFE_BEGIN/Py_TRASHCAN_SAFE_END) are now deprecated. They should be replaced by the new macrosPy_TRASHCAN_BEGINandPy_TRASHCAN_END.A tp_dealloc function that has the old macros, such as:
static void mytype_dealloc(mytype *p) { PyObject_GC_UnTrack(p); Py_TRASHCAN_SAFE_BEGIN(p); ... Py_TRASHCAN_SAFE_END(p) }should migrate to the new macros as follows:
static void mytype_dealloc(mytype *p) { PyObject_GC_UnTrack(p); Py_TRASHCAN_BEGIN(p, mytype_dealloc) ... Py_TRASHCAN_END }Note that
Py_TRASHCAN_BEGINhas a second argument which should be the deallocation function it is in.To support older Python versions in the same codebase, you can define the following macros and use them throughout the code (credit: these were copied from the
mypycodebase):#if PY_VERSION_HEX >= 0x03080000 # define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc) # define CPy_TRASHCAN_END(op) Py_TRASHCAN_END #else # define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op) # define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op) #endif -
The
PyType_Readyfunction now raises an error if a type is defined with thePy_TPFLAGS_HAVE_GCflag set but has no traverse function (PyTypeObject.tp_traverse). (Contributed by Victor Stinner in44263.) -
Heap types with the
Py_TPFLAGS_IMMUTABLETYPEflag can now inherit the590vectorcall protocol. Previously, this was only possible forstatic types <static-types>. (Contributed by Erlend E. Aasland in43908) -
Since
Py_TYPE()is changed to a inline static function,Py_TYPE(obj) = new_typemust be replaced withPy_SET_TYPE(obj, new_type): see thePy_SET_TYPE()function (available since Python 3.9). For backward compatibility, this macro can be used:#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE) static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) { ob->ob_type = type; } #define Py_SET_TYPE(ob, type) _Py_SET_TYPE((PyObject*)(ob), type) #endif(Contributed by Victor Stinner in
39573.) -
Since
Py_SIZE()is changed to a inline static function,Py_SIZE(obj) = new_sizemust be replaced withPy_SET_SIZE(obj, new_size): see thePy_SET_SIZE()function (available since Python 3.9). For backward compatibility, this macro can be used:#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE) static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) { ob->ob_size = size; } #define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size) #endif(Contributed by Victor Stinner in
39573.) -
<Python.h>no longer includes the header files<stdlib.h>,<stdio.h>,<errno.h>and<string.h>when thePy_LIMITED_APImacro is set to0x030b0000(Python 3.11) or higher. C extensions should explicitly include the header files after#include <Python.h>. (Contributed by Victor Stinner in45434.) -
The non-limited API files
cellobject.h,classobject.h,code.h,context.h,funcobject.h,genobject.handlongintrepr.hhave been moved to theInclude/cpythondirectory. Moreover, theeval.hheader file was removed. These files must not be included directly, as they are already included inPython.h:Include Files <api-includes>. If they have been included directly, consider includingPython.hinstead. (Contributed by Victor Stinner in35134.) -
The
!PyUnicode_CHECK_INTERNEDmacro has been excluded from the limited C API. It was never usable there, because it used internal structures which are not available in the limited C API. (Contributed by Victor Stinner in46007.) -
The following frame functions and type are now directly available with
#include <Python.h>, it's no longer needed to add#include <frameobject.h>:PyFrame_CheckPyFrame_GetBackPyFrame_GetBuiltinsPyFrame_GetGeneratorPyFrame_GetGlobalsPyFrame_GetLastiPyFrame_GetLocalsPyFrame_Type
(Contributed by Victor Stinner in
93937.)
-
The
PyFrameObjectstructure members have been removed from the public C API.While the documentation notes that the
PyFrameObjectfields are subject to change at any time, they have been stable for a long time and were used in several popular extensions.In Python 3.11, the frame struct was reorganized to allow performance optimizations. Some fields were removed entirely, as they were details of the old implementation.
PyFrameObjectfields:f_back: usePyFrame_GetBack.f_blockstack: removed.f_builtins: usePyFrame_GetBuiltins.f_code: usePyFrame_GetCode.f_gen: usePyFrame_GetGenerator.f_globals: usePyFrame_GetGlobals.f_iblock: removed.f_lasti: usePyFrame_GetLasti. Code usingf_lastiwithPyCode_Addr2Line()should usePyFrame_GetLineNumberinstead; it may be faster.f_lineno: usePyFrame_GetLineNumberf_locals: usePyFrame_GetLocals.f_stackdepth: removed.f_state: no public API (renamed tof_frame.f_state).f_trace: no public API.f_trace_lines: usePyObject_GetAttrString((PyObject*)frame, "f_trace_lines").f_trace_opcodes: usePyObject_GetAttrString((PyObject*)frame, "f_trace_opcodes").f_localsplus: no public API (renamed tof_frame.localsplus).f_valuestack: removed.
The Python frame object is now created lazily. A side effect is that the
~frame.f_backmember must not be accessed directly, since its value is now also computed lazily. ThePyFrame_GetBackfunction must be called instead.Debuggers that accessed the
~frame.f_localsdirectly must callPyFrame_GetLocalsinstead. They no longer need to call!PyFrame_FastToLocalsWithErroror!PyFrame_LocalsToFast, in fact they should not call those functions. The necessary updating of the frame is now managed by the virtual machine.Code defining
PyFrame_GetCode()on Python 3.8 and older:#if PY_VERSION_HEX < 0x030900B1 static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame) { Py_INCREF(frame->f_code); return frame->f_code; } #endifCode defining
PyFrame_GetBack()on Python 3.8 and older:#if PY_VERSION_HEX < 0x030900B1 static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame) { Py_XINCREF(frame->f_back); return frame->f_back; } #endifOr use the pythoncapi_compat project to get these two functions on older Python versions.
-
Changes of the
PyThreadStatestructure members:frame: removed, usePyThreadState_GetFrame(function added to Python 3.9 by40429). Warning: the function returns astrong reference, need to callPy_XDECREF.tracing: changed, usePyThreadState_EnterTracingandPyThreadState_LeaveTracing(functions added to Python 3.11 by43760).recursion_depth: removed, use(tstate->recursion_limit - tstate->recursion_remaining)instead.stackcheck_counter: removed.
Code defining
PyThreadState_GetFrame()on Python 3.8 and older:#if PY_VERSION_HEX < 0x030900B1 static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate) { Py_XINCREF(tstate->frame); return tstate->frame; } #endifCode defining
PyThreadState_EnterTracing()andPyThreadState_LeaveTracing()on Python 3.10 and older:#if PY_VERSION_HEX < 0x030B00A2 static inline void PyThreadState_EnterTracing(PyThreadState *tstate) { tstate->tracing++; #if PY_VERSION_HEX >= 0x030A00A1 tstate->cframe->use_tracing = 0; #else tstate->use_tracing = 0; #endif } static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) { int use_tracing = (tstate->c_tracefunc != NULL || tstate->c_profilefunc != NULL); tstate->tracing--; #if PY_VERSION_HEX >= 0x030A00A1 tstate->cframe->use_tracing = use_tracing; #else tstate->use_tracing = use_tracing; #endif } #endifOr use the pythoncapi-compat project to get these functions on old Python functions.
-
Distributors are encouraged to build Python with the optimized Blake2 library libb2.
-
The
PyConfig.module_search_paths_setfield must now be set to 1 for initialization to usePyConfig.module_search_pathsto initializesys.path. Otherwise, initialization will recalculate the path and replace any values added tomodule_search_paths. -
PyConfig_Readno longer calculates the initial search path, and will not fill any values intoPyConfig.module_search_paths. To calculate default paths and then modify them, finish initialization and usePySys_GetObjectto retrievesys.pathas a Python list object and modify it directly.
Deprecated
-
Deprecate the following functions to configure the Python initialization:
!PySys_AddWarnOptionUnicode!PySys_AddWarnOption!PySys_AddXOption!PySys_HasWarnOptions!PySys_SetArgvEx!PySys_SetArgv!PySys_SetPath!Py_SetPath!Py_SetProgramName!Py_SetPythonHome!Py_SetStandardStreamEncoding!_Py_SetProgramFullPath
Use the new
PyConfigAPI of thePython Initialization Configuration <init-config>instead (587). (Contributed by Victor Stinner in88279.) -
Deprecate the
ob_shashmember of thePyBytesObject. UsePyObject_Hashinstead. (Contributed by Inada Naoki in46864.)
Pending Removal in Python 3.12
The following C APIs have been deprecated in earlier Python releases, and will be removed in Python 3.12.
!PyUnicode_AS_DATA!PyUnicode_AS_UNICODE!PyUnicode_AsUnicodeAndSize!PyUnicode_AsUnicode!PyUnicode_FromUnicode!PyUnicode_GET_DATA_SIZE!PyUnicode_GET_SIZE!PyUnicode_GetSize!PyUnicode_IS_COMPACT!PyUnicode_IS_READYPyUnicode_READY!PyUnicode_WSTR_LENGTH!_PyUnicode_AsUnicode!PyUnicode_WCHAR_KINDPyUnicodeObject!PyUnicode_InternImmortal
Removed
-
!PyFrame_BlockSetupand!PyFrame_BlockPophave been removed. (Contributed by Mark Shannon in40222.) -
Remove the following math macros using the
errnovariable:Py_ADJUST_ERANGE1()Py_ADJUST_ERANGE2()Py_OVERFLOWED()Py_SET_ERANGE_IF_OVERFLOW()Py_SET_ERRNO_ON_MATH_ERROR()
(Contributed by Victor Stinner in
45412.) -
Remove
Py_UNICODE_COPY()andPy_UNICODE_FILL()macros, deprecated since Python 3.3. UsePyUnicode_CopyCharacters()ormemcpy()(wchar_t*string), andPyUnicode_Fill()functions instead. (Contributed by Victor Stinner in41123.) -
Remove the
pystrhex.hheader file. It only contains private functions. C extensions should only include the main<Python.h>header file. (Contributed by Victor Stinner in45434.) -
Remove the
Py_FORCE_DOUBLE()macro. It was used by thePy_IS_INFINITY()macro. (Contributed by Victor Stinner in45440.) -
The following items are no longer available when
Py_LIMITED_APIis defined:PyMarshal_WriteLongToFilePyMarshal_WriteObjectToFilePyMarshal_ReadObjectFromStringPyMarshal_WriteObjectToString- the
Py_MARSHAL_VERSIONmacro
These are not part of the
limited API <limited-api-list>.(Contributed by Victor Stinner in
45474.) -
Exclude
!PyWeakref_GET_OBJECTfrom the limited C API. It never worked since the!PyWeakReferencestructure is opaque in the limited C API. (Contributed by Victor Stinner in35134.) -
Remove the
PyHeapType_GET_MEMBERS()macro. It was exposed in the public C API by mistake, it must only be used by Python internally. Use thePyTypeObject.tp_membersmember instead. (Contributed by Victor Stinner in40170.) -
Remove the
HAVE_PY_SET_53BIT_PRECISIONmacro (moved to the internal C API). (Contributed by Victor Stinner in45412.)
-
Remove the
Py_UNICODEencoder APIs, as they have been deprecated since Python 3.3, are little used and are inefficient relative to the recommended alternatives.The removed functions are:
!PyUnicode_Encode!PyUnicode_EncodeASCII!PyUnicode_EncodeLatin1!PyUnicode_EncodeUTF7!PyUnicode_EncodeUTF8!PyUnicode_EncodeUTF16!PyUnicode_EncodeUTF32!PyUnicode_EncodeUnicodeEscape!PyUnicode_EncodeRawUnicodeEscape!PyUnicode_EncodeCharmap!PyUnicode_TranslateCharmap!PyUnicode_EncodeDecimal!PyUnicode_TransformDecimalToASCII
See
624for details andmigration guidance <624#alternative-apis>. (Contributed by Inada Naoki in44029.)
Notable changes in 3.11.4
tarfile
- The extraction methods in
tarfile, andshutil.unpack_archive, have a new a filter argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. Seetarfile-extraction-filterfor details. In Python 3.12, use without the filter argument will show aDeprecationWarning. In Python 3.14, the default will switch to'data'. (Contributed by Petr Viktorin in706.)
Notable changes in 3.11.5
OpenSSL
- Windows builds and macOS installers from python.org now use OpenSSL 3.0.
What's New In Python 3.12
Editor
Adam Turner
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the issue number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the VCS log when researching a change.
This article explains the new features in Python 3.12, compared to 3.11. Python 3.12 was released on October 2, 2023. For full details, see the changelog <changelog>.
693 -- Python 3.12 Release Schedule
Summary -- Release highlights
Python 3.12 is a stable release of the Python programming language, with a mix of changes to the language and the standard library. The library changes focus on cleaning up deprecated APIs, usability, and correctness. Of note, the !distutils package has been removed from the standard library. Filesystem support in os and pathlib has seen a number of improvements, and several modules have better performance.
The language changes focus on usability, as f-strings <f-string> have had many limitations removed and 'Did you mean ...' suggestions continue to improve. The new type parameter syntax <whatsnew312-pep695> and type statement improve ergonomics for using generic types <generic type> and type aliases <type alias> with static type checkers.
This article doesn't attempt to provide a complete specification of all new features, but instead gives a convenient overview. For full details, you should refer to the documentation, such as the Library Reference <library-index> and Language Reference <reference-index>. If you want to understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented.
New syntax features:
PEP 695 <whatsnew312-pep695>, type parameter syntax and thetypestatement
New grammar features:
PEP 701 <whatsnew312-pep701>,f-strings <f-string>in the grammar
Interpreter improvements:
PEP 684 <whatsnew312-pep684>, a unique per-interpreterGIL <global interpreter lock>PEP 669 <whatsnew312-pep669>, low impact monitoring- Improved 'Did you mean ...' suggestions for
NameError,ImportError, andSyntaxErrorexceptions
Python data model improvements:
PEP 688 <whatsnew312-pep688>, using thebuffer protocol <bufferobjects>from Python
Significant improvements in the standard library:
- The
pathlib.Pathclass now supports subclassing - The
osmodule received several improvements for Windows support - A
command-line interface <sqlite3-cli>has been added to thesqlite3module isinstancechecks againstruntime-checkable protocols <typing.runtime_checkable>enjoy a speed up of between two and 20 times- The
asynciopackage has had a number of performance improvements, with some benchmarks showing a 75% speed up. - A
command-line interface <uuid-cli>has been added to theuuidmodule - Due to the changes in
PEP 701 <whatsnew312-pep701>, producing tokens via thetokenizemodule is up to 64% faster.
Security improvements:
- Replace the builtin
hashlibimplementations of SHA1, SHA3, SHA2-384, SHA2-512, and MD5 with formally verified code from the HACL* project. These builtin implementations remain as fallbacks that are only used when OpenSSL does not provide them.
C API improvements:
PEP 697 <whatsnew312-pep697>, unstable C API tierPEP 683 <whatsnew312-pep683>, immortal objects
CPython implementation improvements:
PEP 709 <whatsnew312-pep709>, comprehension inliningCPython support <perf_profiling>for the Linuxperfprofiler- Implement stack overflow protection on supported platforms
New typing features:
PEP 692 <whatsnew312-pep692>, using~typing.TypedDictto annotate**kwargs <argument>PEP 698 <whatsnew312-pep698>,typing.overridedecorator
Important deprecations, removals or restrictions:
623: Removewstrfrom Unicode objects in Python's C API, reducing the size of everystrobject by at least 8 bytes.632: Remove the!distutilspackage. Seethe migration guide <0632#migration-advice>for advice replacing the APIs it provided. The third-party Setuptools package continues to provide!distutils, if you still require it in Python 3.12 and beyond.95299: Do not pre-installsetuptoolsin virtual environments created withvenv. This means thatdistutils,setuptools,pkg_resources, andeasy_installwill no longer available by default; to access these runpip install setuptoolsin theactivated <venv-explanation>virtual environment.- The
!asynchat,!asyncore, and!impmodules have been removed, along with severalunittest.TestCasemethod aliases.
New Features
PEP 695: Type Parameter Syntax
Generic classes and functions under 484 were declared using a verbose syntax that left the scope of type parameters unclear and required explicit declarations of variance.
695 introduces a new, more compact and explicit way to create generic classes <generic-classes> and functions <generic-functions>:
def max[T](args: Iterable[T]) -> T:
...
class list[T]:
def __getitem__(self, index: int, /) -> T:
...
def append(self, element: T) -> None:
...
In addition, the PEP introduces a new way to declare type aliases <type-aliases> using the type statement, which creates an instance of ~typing.TypeAliasType:
type Point = tuple[float, float]
Type aliases can also be generic <generic-type-aliases>:
type Point[T] = tuple[T, T]
The new syntax allows declaring ~typing.TypeVarTuple and ~typing.ParamSpec parameters, as well as ~typing.TypeVar parameters with bounds or constraints:
type IntFunc[**P] = Callable[P, int] # ParamSpec
type LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple
type HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound
type IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints
The value of type aliases and the bound and constraints of type variables created through this syntax are evaluated only on demand (see lazy evaluation <lazy-evaluation>). This means type aliases are able to refer to other types defined later in the file.
Type parameters declared through a type parameter list are visible within the scope of the declaration and any nested scopes, but not in the outer scope. For example, they can be used in the type annotations for the methods of a generic class or in the class body. However, they cannot be used in the module scope after the class is defined. See type-params for a detailed description of the runtime semantics of type parameters.
In order to support these scoping semantics, a new kind of scope is introduced, the annotation scope <annotation-scopes>. Annotation scopes behave for the most part like function scopes, but interact differently with enclosing class scopes. In Python 3.13, annotations <annotation> will also be evaluated in annotation scopes.
See 695 for more details.
(PEP written by Eric Traut. Implementation by Jelle Zijlstra, Eric Traut, and others in 103764.)
PEP 701: Syntactic formalization of f-strings
701 lifts some restrictions on the usage of f-strings <f-string>. Expression components inside f-strings can now be any valid Python expression, including strings reusing the same quote as the containing f-string, multi-line expressions, comments, backslashes, and unicode escape sequences. Let's cover these in detail:
-
Quote reuse: in Python 3.11, reusing the same quotes as the enclosing f-string raises a
SyntaxError, forcing the user to either use other available quotes (like using double quotes or triple quotes if the f-string uses single quotes). In Python 3.12, you can now do things like this:>>> songs = ['Take me back to Eden', 'Alkaline', 'Ascensionism'] >>> f"This is the playlist: {", ".join(songs)}" 'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
Note that before this change there was no explicit limit in how f-strings can be nested, but the fact that string quotes cannot be reused inside the expression component of f-strings made it impossible to nest f-strings arbitrarily. In fact, this is the most nested f-string that could be written:
>>> f"""{f'''{f'{f"{1+1}"}'}'''}""" '2'
As now f-strings can contain any valid Python expression inside expression components, it is now possible to nest f-strings arbitrarily:
>>> f"{f"{f"{f"{f"{f"{1+1}"}"}"}"}"}" '2'
-
Multi-line expressions and comments: In Python 3.11, f-string expressions must be defined in a single line, even if the expression within the f-string could normally span multiple lines (like literal lists being defined over multiple lines), making them harder to read. In Python 3.12 you can now define f-strings spanning multiple lines, and add inline comments:
>>> f"This is the playlist: {", ".join([ ... 'Take me back to Eden', # My, my, those eyes like fire ... 'Alkaline', # Not acid nor alkaline ... 'Ascensionism' # Take to the broken skies at last ... ])}" 'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
-
Backslashes and unicode characters: before Python 3.12 f-string expressions couldn't contain any
\character. This also affected unicodeescape sequences <escape-sequences>(such as\N{snowman}) as these contain the\Npart that previously could not be part of expression components of f-strings. Now, you can define expressions like this:>>> print(f"This is the playlist: {"n".join(songs)}") This is the playlist: Take me back to Eden Alkaline Ascensionism >>> print(f"This is the playlist: {"N{BLACK HEART SUIT}".join(songs)}") This is the playlist: Take me back to Eden♥Alkaline♥Ascensionism
See 701 for more details.
As a positive side-effect of how this feature has been implemented (by parsing f-strings with the PEG parser <617>), now error messages for f-strings are more precise and include the exact location of the error. For example, in Python 3.11, the following f-string raises a SyntaxError:
>>> my_string = f"{x z y}" + f"{1 + 1}"
File "<stdin>", line 1
(x z y)
^^^
SyntaxError: f-string: invalid syntax. Perhaps you forgot a comma?
but the error message doesn't include the exact location of the error within the line and also has the expression artificially surrounded by parentheses. In Python 3.12, as f-strings are parsed with the PEG parser, error messages can be more precise and show the entire line:
>>> my_string = f"{x z y}" + f"{1 + 1}"
File "<stdin>", line 1
my_string = f"{x z y}" + f"{1 + 1}"
^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
(Contributed by Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou, Cristián Maureira-Fredes and Marta Gómez in 102856. PEP written by Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou and Marta Gómez).
PEP 684: A Per-Interpreter GIL
684 introduces a per-interpreter GIL <global interpreter lock>, so that sub-interpreters may now be created with a unique GIL per interpreter. This allows Python programs to take full advantage of multiple CPU cores. This is currently only available through the C-API, though a Python API is anticipated for 3.13 <554>.
Use the new Py_NewInterpreterFromConfig function to create an interpreter with its own GIL:
PyInterpreterConfig config = {
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = NULL;
PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
if (PyStatus_Exception(status)) {
return -1;
}
/* The new interpreter is now active in the current thread. */
For further examples how to use the C-API for sub-interpreters with a per-interpreter GIL, see Modules/_xxsubinterpretersmodule.c.
(Contributed by Eric Snow in 104210, etc.)
PEP 669: Low impact monitoring for CPython
669 defines a new API <sys.monitoring> for profilers, debuggers, and other tools to monitor events in CPython. It covers a wide range of events, including calls, returns, lines, exceptions, jumps, and more. This means that you only pay for what you use, providing support for near-zero overhead debuggers and coverage tools. See sys.monitoring for details.
(Contributed by Mark Shannon in 103082.)
PEP 688: Making the buffer protocol accessible in Python
688 introduces a way to use the buffer protocol <bufferobjects> from Python code. Classes that implement the ~object.__buffer__ method are now usable as buffer types.
The new collections.abc.Buffer ABC provides a standard way to represent buffer objects, for example in type annotations. The new inspect.BufferFlags enum represents the flags that can be used to customize buffer creation. (Contributed by Jelle Zijlstra in 102500.)
PEP 709: Comprehension inlining
Dictionary, list, and set comprehensions are now inlined, rather than creating a new single-use function object for each execution of the comprehension. This speeds up execution of a comprehension by up to two times. See 709 for further details.
Comprehension iteration variables remain isolated and don't overwrite a variable of the same name in the outer scope, nor are they visible after the comprehension. Inlining does result in a few visible behavior changes:
- There is no longer a separate frame for the comprehension in tracebacks, and tracing/profiling no longer shows the comprehension as a function call.
- The
symtablemodule will no longer produce child symbol tables for each comprehension; instead, the comprehension's locals will be included in the parent function's symbol table. - Calling
localsinside a comprehension now includes variables from outside the comprehension, and no longer includes the synthetic.0variable for the comprehension "argument". - A comprehension iterating directly over
locals()(e.g.[k for k in locals()]) may see "RuntimeError: dictionary changed size during iteration" when run under tracing (e.g. code coverage measurement). This is the same behavior already seen in e.g.for k in locals():. To avoid the error, first create a list of keys to iterate over:keys = list(locals()); [k for k in keys].
(Contributed by Carl Meyer and Vladimir Matveev in 709.)
Improved Error Messages
-
Modules from the standard library are now potentially suggested as part of the error messages displayed by the interpreter when a
NameErroris raised to the top level. (Contributed by Pablo Galindo in98254.)>>> sys.version_info Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sys' is not defined. Did you forget to import 'sys'?
-
Improve the error suggestion for
NameErrorexceptions for instances. Now if aNameErroris raised in a method and the instance has an attribute that's exactly equal to the name in the exception, the suggestion will includeself.<NAME>instead of the closest match in the method scope. (Contributed by Pablo Galindo in99139.)>>> class A: ... def __init__(self): ... self.blech = 1 ... ... def foo(self): ... somethin = blech ... >>> A().foo() Traceback (most recent call last): File "<stdin>", line 1 somethin = blech ^^^^^ NameError: name 'blech' is not defined. Did you mean: 'self.blech'?
-
Improve the
SyntaxErrorerror message when the user typesimport x from yinstead offrom y import x. (Contributed by Pablo Galindo in98931.)>>> import a.y.z from b.y.z Traceback (most recent call last): File "<stdin>", line 1 import a.y.z from b.y.z ^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: Did you mean to use 'from ... import ...' instead?
-
ImportErrorexceptions raised from failedfrom <module> import <name>statements now include suggestions for the value of<name>based on the available names in<module>. (Contributed by Pablo Galindo in91058.)>>> from collections import chainmap Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?
New Features Related to Type Hints
This section covers major changes affecting type hints <484> and the typing module.
PEP 692: Using TypedDict for more precise **kwargs typing
Typing **kwargs in a function signature as introduced by 484 allowed for valid annotations only in cases where all of the **kwargs were of the same type.
692 specifies a more precise way of typing **kwargs by relying on typed dictionaries:
from typing import TypedDict, Unpack
class Movie(TypedDict):
name: str
year: int
def foo(**kwargs: Unpack[Movie]): ...
See 692 for more details.
(Contributed by Franek Magiera in 103629.)
PEP 698: Override Decorator for Static Typing
A new decorator typing.override has been added to the typing module. It indicates to type checkers that the method is intended to override a method in a superclass. This allows type checkers to catch mistakes where a method that is intended to override something in a base class does not in fact do so.
Example:
from typing import override
class Base:
def get_color(self) -> str:
return "blue"
class GoodChild(Base):
@override # ok: overrides Base.get_color
def get_color(self) -> str:
return "yellow"
class BadChild(Base):
@override # type checker error: does not override Base.get_color
def get_colour(self) -> str:
return "red"
See 698 for more details.
(Contributed by Steven Troxler in 101561.)
Other Language Changes
- The parser now raises
SyntaxErrorwhen parsing source code containing null bytes. (Contributed by Pablo Galindo in96670.) - A backslash-character pair that is not a valid escape sequence now generates a
SyntaxWarning, instead ofDeprecationWarning. For example,re.compile("\d+\.\d+")now emits aSyntaxWarning("\d"is an invalid escape sequence, use raw strings for regular expression:re.compile(r"\d+\.\d+")). In a future Python version,SyntaxErrorwill eventually be raised, instead ofSyntaxWarning. (Contributed by Victor Stinner in98401.) - Octal escapes with value larger than
0o377(ex:"\477"), deprecated in Python 3.11, now produce aSyntaxWarning, instead ofDeprecationWarning. In a future Python version they will be eventually aSyntaxError. (Contributed by Victor Stinner in98401.) - Variables used in the target part of comprehensions that are not stored to can now be used in assignment expressions (
:=). For example, in[(b := 1) for a, b.prop in some_iter], the assignment tobis now allowed. Note that assigning to variables stored to in the target part of comprehensions (likea) is still disallowed, as per572. (Contributed by Nikita Sobolev in100581.) - Exceptions raised in a class or type's
__set_name__method are no longer wrapped by aRuntimeError. Context information is added to the exception as a678note. (Contributed by Irit Katriel in77757.) - When a
try-except*construct handles the entireExceptionGroupand raises one other exception, that exception is no longer wrapped in anExceptionGroup. Also changed in version 3.11.4. (Contributed by Irit Katriel in103590.) - The Garbage Collector now runs only on the eval breaker mechanism of the Python bytecode evaluation loop instead of object allocations. The GC can also run when
PyErr_CheckSignalsis called so C extensions that need to run for a long time without executing any Python code also have a chance to execute the GC periodically. (Contributed by Pablo Galindo in97922.) - All builtin and extension callables expecting boolean parameters now accept arguments of any type instead of just
boolandint. (Contributed by Serhiy Storchaka in60203.) memoryviewnow supports the half-float type (the "e" format code). (Contributed by Donghee Na and Antoine Pitrou in90751.)sliceobjects are now hashable, allowing them to be used as dict keys and set items. (Contributed by Will Bradshaw, Furkan Onder, and Raymond Hettinger in101264.)sumnow uses Neumaier summation to improve accuracy and commutativity when summing floats or mixed ints and floats. (Contributed by Raymond Hettinger in100425.)ast.parsenow raisesSyntaxErrorinstead ofValueErrorwhen parsing source code containing null bytes. (Contributed by Pablo Galindo in96670.)- The extraction methods in
tarfile, andshutil.unpack_archive, have a new a filter argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. Seetarfile extraction filters <tarfile-extraction-filter>for details. In Python 3.14, the default will switch to'data'. (Contributed by Petr Viktorin in706.) types.MappingProxyTypeinstances are now hashable if the underlying mapping is hashable. (Contributed by Serhiy Storchaka in87995.)- Add
support for the perf profiler <perf_profiling>through the new environment variablePYTHONPERFSUPPORTand command-line option-X perf <-X>, as well as the newsys.activate_stack_trampoline,sys.deactivate_stack_trampoline, andsys.is_stack_trampoline_activefunctions. (Design by Pablo Galindo. Contributed by Pablo Galindo and Christian Heimes with contributions from Gregory P. Smith [Google] and Mark Shannon in96123.)
New Modules
- None.
Improved Modules
array
- The
array.arrayclass now supports subscripting, making it ageneric type. (Contributed by Jelle Zijlstra in98658.)
asyncio
- The performance of writing to sockets in
asynciohas been significantly improved.asyncionow avoids unnecessary copying when writing to sockets and uses~socket.socket.sendmsgif the platform supports it. (Contributed by Kumar Aditya in91166.) - Add
asyncio.eager_task_factoryandasyncio.create_eager_task_factoryfunctions to allow opting an event loop in to eager task execution, making some use-cases 2x to 5x faster. (Contributed by Jacob Bower & Itamar Oren in102853,104140, and104138) - On Linux,
asynciouses!asyncio.PidfdChildWatcherby default ifos.pidfd_openis available and functional instead of!asyncio.ThreadedChildWatcher. (Contributed by Kumar Aditya in98024.) - The event loop now uses the best available child watcher for each platform (
!asyncio.PidfdChildWatcherif supported and!asyncio.ThreadedChildWatcherotherwise), so manually configuring a child watcher is not recommended. (Contributed by Kumar Aditya in94597.) - Add loop_factory parameter to
asyncio.runto allow specifying a custom event loop factory. (Contributed by Kumar Aditya in99388.) - Add C implementation of
asyncio.current_taskfor 4x-6x speedup. (Contributed by Itamar Oren and Pranav Thulasiram Bhat in100344.) asyncio.iscoroutinenow returnsFalsefor generators asasynciodoes not support legacy generator-based coroutines. (Contributed by Kumar Aditya in102748.)asyncio.waitandasyncio.as_completednow accepts generators yielding tasks. (Contributed by Kumar Aditya in78530.)
calendar
- Add enums
calendar.Monthandcalendar.Daydefining months of the year and days of the week. (Contributed by Prince Roshan in103636.)
csv
- Add
csv.QUOTE_NOTNULLandcsv.QUOTE_STRINGSflags to provide finer grained control ofNoneand empty strings by~csv.readerand~csv.writerobjects.
dis
- Pseudo instruction opcodes (which are used by the compiler but do not appear in executable bytecode) are now exposed in the
dismodule.HAVE_ARGUMENTis still relevant to real opcodes, but it is not useful for pseudo instructions. Use the newdis.hasargcollection instead. (Contributed by Irit Katriel in94216.) - Add the
dis.hasexccollection to signify instructions that set an exception handler. (Contributed by Irit Katriel in94216.)
fractions
- Objects of type
fractions.Fractionnow support float-style formatting. (Contributed by Mark Dickinson in100161.)
importlib.resources
importlib.resources.as_filenow supports resource directories. (Contributed by Jason R. Coombs in97930.)- Rename first parameter of
importlib.resources.filesto anchor. (Contributed by Jason R. Coombs in100598.)
inspect
- Add
inspect.markcoroutinefunctionto mark sync functions that return acoroutinefor use withinspect.iscoroutinefunction. (Contributed by Carlton Gibson in99247.) - Add
inspect.getasyncgenstateandinspect.getasyncgenlocalsfor determining the current state of asynchronous generators. (Contributed by Thomas Krennwallner in79940.) - The performance of
inspect.getattr_statichas been considerably improved. Most calls to the function should be at least 2x faster than they were in Python 3.11. (Contributed by Alex Waygood in103193.)
itertools
- Add
itertools.batchedfor collecting into even-sized tuples where the last batch may be shorter than the rest. (Contributed by Raymond Hettinger in98363.)
math
- Add
math.sumprodfor computing a sum of products. (Contributed by Raymond Hettinger in100485.) - Extend
math.nextafterto include a steps argument for moving up or down multiple steps at a time. (Contributed by Matthias Goergens, Mark Dickinson, and Raymond Hettinger in94906.)
os
- Add
os.PIDFD_NONBLOCKto open a file descriptor for a process withos.pidfd_openin non-blocking mode. (Contributed by Kumar Aditya in93312.) os.DirEntrynow includes anos.DirEntry.is_junctionmethod to check if the entry is a junction. (Contributed by Charles Machalow in99547.)- Add
os.listdrives,os.listvolumesandos.listmountsfunctions on Windows for enumerating drives, volumes and mount points. (Contributed by Steve Dower in102519.) os.statandos.lstatare now more accurate on Windows. Thest_birthtimefield will now be filled with the creation time of the file, andst_ctimeis deprecated but still contains the creation time (but in the future will return the last metadata change, for consistency with other platforms).st_devmay be up to 64 bits andst_inoup to 128 bits depending on your file system, andst_rdevis always set to zero rather than incorrect values. Both functions may be significantly faster on newer releases of Windows. (Contributed by Steve Dower in99726.)
os.path
- Add
os.path.isjunctionto check if a given path is a junction. (Contributed by Charles Machalow in99547.) - Add
os.path.splitrootto split a path into a triad(drive, root, tail). (Contributed by Barney Gale in101000.)
pathlib
- Add support for subclassing
pathlib.PurePathandpathlib.Path, plus their Posix- and Windows-specific variants. Subclasses may override thepathlib.PurePath.with_segmentsmethod to pass information between path instances. - Add
pathlib.Path.walkfor walking the directory trees and generating all file or directory names within them, similar toos.walk. (Contributed by Stanislav Zmiev in90385.) - Add walk_up optional parameter to
pathlib.PurePath.relative_toto allow the insertion of..entries in the result; this behavior is more consistent withos.path.relpath. (Contributed by Domenico Ragusa in84538.) - Add
pathlib.Path.is_junctionas a proxy toos.path.isjunction. (Contributed by Charles Machalow in99547.) - Add case_sensitive optional parameter to
pathlib.Path.glob,pathlib.Path.rglobandpathlib.PurePath.matchfor matching the path's case sensitivity, allowing for more precise control over the matching process.
platform
- Add support for detecting Windows 11 and Windows Server releases past 2012. Previously, lookups on Windows Server platforms newer than Windows Server 2012 and on Windows 11 would return
Windows-10. (Contributed by Steve Dower in89545.)
pdb
- Add convenience variables to hold values temporarily for debug session and provide quick access to values like the current frame or the return value. (Contributed by Tian Gao in
103693.)
random
- Add
random.binomialvariate. (Contributed by Raymond Hettinger in81620.) - Add a default of
lambd=1.0torandom.expovariate. (Contributed by Raymond Hettinger in100234.)
shutil
-
shutil.make_archivenow passes the root_dir argument to custom archivers which support it. In this case it no longer temporarily changes the current working directory of the process to root_dir to perform archiving. (Contributed by Serhiy Storchaka in74696.) -
shutil.rmtreenow accepts a new argument onexc which is an error handler like onerror but which expects an exception instance rather than a (typ, val, tb) triplet. onerror is deprecated. (Contributed by Irit Katriel in102828.) -
shutil.whichnow consults the PATHEXT environment variable to find matches within PATH on Windows even when the given cmd includes a directory component. (Contributed by Charles Machalow in103179.)shutil.whichwill callNeedCurrentDirectoryForExePathWwhen querying for executables on Windows to determine if the current working directory should be prepended to the search path. (Contributed by Charles Machalow in103179.)shutil.whichwill return a path matching the cmd with a component fromPATHEXTprior to a direct match elsewhere in the search path on Windows. (Contributed by Charles Machalow in103179.)
sqlite3
- Add a
command-line interface <sqlite3-cli>. (Contributed by Erlend E. Aasland in77617.) - Add the
sqlite3.Connection.autocommitattribute tosqlite3.Connectionand the autocommit parameter tosqlite3.connectto control249-complianttransaction handling <sqlite3-transaction-control-autocommit>. (Contributed by Erlend E. Aasland in83638.) - Add entrypoint keyword-only parameter to
sqlite3.Connection.load_extension, for overriding the SQLite extension entry point. (Contributed by Erlend E. Aasland in103015.) - Add
sqlite3.Connection.getconfigandsqlite3.Connection.setconfigtosqlite3.Connectionto make configuration changes to a database connection. (Contributed by Erlend E. Aasland in103489.)
statistics
- Extend
statistics.correlationto include as arankedmethod for computing the Spearman correlation of ranked data. (Contributed by Raymond Hettinger in95861.)
sys
- Add the
sys.monitoringnamespace to expose the newPEP 669 <whatsnew312-pep669>monitoring API. (Contributed by Mark Shannon in103082.) - Add
sys.activate_stack_trampolineandsys.deactivate_stack_trampolinefor activating and deactivating stack profiler trampolines, andsys.is_stack_trampoline_activefor querying if stack profiler trampolines are active. (Contributed by Pablo Galindo and Christian Heimes with contributions from Gregory P. Smith [Google] and Mark Shannon in96123.) - Add
sys.last_excwhich holds the last unhandled exception that was raised (for post-mortem debugging use cases). Deprecate the three fields that have the same information in its legacy form:sys.last_type,sys.last_valueandsys.last_traceback. (Contributed by Irit Katriel in102778.) sys._current_exceptionsnow returns a mapping from thread-id to an exception instance, rather than to a(typ, exc, tb)tuple. (Contributed by Irit Katriel in103176.)sys.setrecursionlimitandsys.getrecursionlimit. The recursion limit now applies only to Python code. Builtin functions do not use the recursion limit, but are protected by a different mechanism that prevents recursion from causing a virtual machine crash.
tempfile
- The
tempfile.NamedTemporaryFilefunction has a new optional parameter delete_on_close (Contributed by Evgeny Zorin in58451.) tempfile.mkdtempnow always returns an absolute path, even if the argument provided to the dir parameter is a relative path.
threading
- Add
threading.settrace_all_threadsandthreading.setprofile_all_threadsthat allow to set tracing and profiling functions in all running threads in addition to the calling one. (Contributed by Pablo Galindo in93503.)
tkinter
tkinter.Canvas.coords()now flattens its arguments. It now accepts not only coordinates as separate arguments (x1, y1, x2, y2, ...) and a sequence of coordinates ([x1, y1, x2, y2, ...]), but also coordinates grouped in pairs ((x1, y1), (x2, y2), ...and[(x1, y1), (x2, y2), ...]), likecreate_*()methods. (Contributed by Serhiy Storchaka in94473.)
tokenize
- The
tokenizemodule includes the changes introduced in701. (Contributed by Marta Gómez Macías and Pablo Galindo in102856.) Seewhatsnew312-porting-to-python312for more information on the changes to thetokenizemodule.
types
- Add
types.get_original_basesto allow for further introspection ofuser-defined-genericswhen subclassed. (Contributed by James Hilton-Balfe and Alex Waygood in101827.)
typing
-
isinstancechecks againstruntime-checkable protocols <typing.runtime_checkable>now useinspect.getattr_staticrather thanhasattrto lookup whether attributes exist. This means that descriptors and~object.__getattr__methods are no longer unexpectedly evaluated duringisinstance()checks against runtime-checkable protocols. However, it may also mean that some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change. (Contributed by Alex Waygood in102433.) -
The members of a runtime-checkable protocol are now considered "frozen" at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on
isinstancechecks comparing objects to the protocol. For example:>>> from typing import Protocol, runtime_checkable >>> @runtime_checkable ... class HasX(Protocol): ... x = 1 ... >>> class Foo: ... ... >>> f = Foo() >>> isinstance(f, HasX) False >>> f.x = 1 >>> isinstance(f, HasX) True >>> HasX.y = 2 >>> isinstance(f, HasX) # unchanged, even though HasX now also has a "y" attribute TrueThis change was made in order to speed up
isinstance()checks against runtime-checkable protocols. -
The performance profile of
isinstancechecks againstruntime-checkable protocols <typing.runtime_checkable>has changed significantly. Mostisinstance()checks against protocols with only a few members should be at least 2x faster than in 3.11, and some may be 20x faster or more. However,isinstance()checks against protocols with many members may be slower than in Python 3.11. (Contributed by Alex Waygood in74690and103193.) -
All
typing.TypedDictandtyping.NamedTupleclasses now have the__orig_bases__attribute. (Contributed by Adrian Garcia Badaracco in103699.) -
Add
frozen_defaultparameter totyping.dataclass_transform. (Contributed by Erik De Bonte in99957.)
unicodedata
- The Unicode database has been updated to version 15.0.0. (Contributed by Benjamin Peterson in
96734).
unittest
Add a --durations command line option, showing the N slowest test cases:
python3 -m unittest --durations=3 lib.tests.test_threading
.....
Slowest test durations
----------------------------------------------------------------------
1.210s test_timeout (Lib.test.test_threading.BarrierTests)
1.003s test_default_timeout (Lib.test.test_threading.BarrierTests)
0.518s test_timeout (Lib.test.test_threading.EventTests)
(0.000 durations hidden. Use -v to show these durations.)
----------------------------------------------------------------------
Ran 158 tests in 9.869s
OK (skipped=3)
(Contributed by Giampaolo Rodola in 48330)
uuid
- Add a
command-line interface <uuid-cli>. (Contributed by Adam Chhina in88597.)
Optimizations
- Remove
wstrandwstr_lengthmembers from Unicode objects. It reduces object size by 8 or 16 bytes on 64bit platform. (623) (Contributed by Inada Naoki in92536.) - Add experimental support for using the BOLT binary optimizer in the build process, which improves performance by 1-5%. (Contributed by Kevin Modzelewski in
90536and tuned by Donghee Na in101525) - Speed up the regular expression substitution (functions
re.subandre.subnand corresponding!re.Patternmethods) for replacement strings containing group references by 2--3 times. (Contributed by Serhiy Storchaka in91524.) - Speed up
asyncio.Taskcreation by deferring expensive string formatting. (Contributed by Itamar Oren in103793.) - The
tokenize.tokenizeandtokenize.generate_tokensfunctions are up to 64% faster as a side effect of the changes required to cover701in thetokenizemodule. (Contributed by Marta Gómez Macías and Pablo Galindo in102856.) - Speed up
supermethod calls and attribute loads via the newLOAD_SUPER_ATTRinstruction. (Contributed by Carl Meyer and Vladimir Matveev in103497.)
CPython bytecode changes
- Remove the
!LOAD_METHODinstruction. It has been merged intoLOAD_ATTR.LOAD_ATTRwill now behave like the old!LOAD_METHODinstruction if the low bit of its oparg is set. (Contributed by Ken Jin in93429.) - Remove the
!JUMP_IF_FALSE_OR_POPand!JUMP_IF_TRUE_OR_POPinstructions. (Contributed by Irit Katriel in102859.) - Remove the
!PRECALLinstruction. (Contributed by Mark Shannon in92925.) - Add the
BINARY_SLICEandSTORE_SLICEinstructions. (Contributed by Mark Shannon in94163.) - Add the
CALL_INTRINSIC_1instructions. (Contributed by Mark Shannon in99005.) - Add the
CALL_INTRINSIC_2instruction. (Contributed by Irit Katriel in101799.) - Add the
CLEANUP_THROWinstruction. (Contributed by Brandt Bucher in90997.) - Add the
!END_SENDinstruction. (Contributed by Mark Shannon in103082.) - Add the
LOAD_FAST_AND_CLEARinstruction as part of the implementation of709. (Contributed by Carl Meyer in101441.) - Add the
LOAD_FAST_CHECKinstruction. (Contributed by Dennis Sweeney in93143.) - Add the
LOAD_FROM_DICT_OR_DEREF,LOAD_FROM_DICT_OR_GLOBALS, andLOAD_LOCALSopcodes as part of the implementation of695. Remove the!LOAD_CLASSDEREFopcode, which can be replaced withLOAD_LOCALSplusLOAD_FROM_DICT_OR_DEREF. (Contributed by Jelle Zijlstra in103764.) - Add the
LOAD_SUPER_ATTRinstruction. (Contributed by Carl Meyer and Vladimir Matveev in103497.) - Add the
RETURN_CONSTinstruction. (Contributed by Wenyang Wang in101632.)
Demos and Tools
- Remove the
Tools/demo/directory which contained old demo scripts. A copy can be found in the old-demos project. (Contributed by Victor Stinner in97681.) - Remove outdated example scripts of the
Tools/scripts/directory. A copy can be found in the old-demos project. (Contributed by Victor Stinner in97669.)
Deprecated
-
argparse: The type, choices, and metavar parameters of!argparse.BooleanOptionalActionare deprecated and will be removed in 3.14. (Contributed by Nikita Sobolev in92248.) -
ast: The followingastfeatures have been deprecated in documentation since Python 3.8, now cause aDeprecationWarningto be emitted at runtime when they are accessed or used, and will be removed in Python 3.14:!ast.Num!ast.Str!ast.Bytes!ast.NameConstant!ast.Ellipsis
Use
ast.Constantinstead. (Contributed by Serhiy Storchaka in90953.) -
asyncio:- The child watcher classes
!asyncio.MultiLoopChildWatcher,!asyncio.FastChildWatcher,!asyncio.AbstractChildWatcherand!asyncio.SafeChildWatcherare deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in94597.) !asyncio.set_child_watcher,!asyncio.get_child_watcher,!asyncio.AbstractEventLoopPolicy.set_child_watcherand!asyncio.AbstractEventLoopPolicy.get_child_watcherare deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in94597.)- The
~asyncio.get_event_loopmethod of the default event loop policy now emits aDeprecationWarningif there is no current event loop set and it decides to create one. (Contributed by Serhiy Storchaka and Guido van Rossum in100160.)
- The child watcher classes
-
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.) -
collections.abc: Deprecatedcollections.abc.ByteString.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.) -
datetime:datetime.datetime's~datetime.datetime.utcnowand~datetime.datetime.utcfromtimestampare deprecated and will be removed in a future version. Instead, use timezone-aware objects to represent datetimes in UTC: respectively, call~datetime.datetime.nowand~datetime.datetime.fromtimestampwith the tz parameter set todatetime.UTC. (Contributed by Paul Ganssle in103857.) -
email: Deprecate the isdst parameter inemail.utils.localtime. (Contributed by Alan Williams in72346.) -
importlib.abc: Deprecated the following classes, scheduled for removal in Python 3.14:!importlib.abc.ResourceReader!importlib.abc.Traversable!importlib.abc.TraversableResources
Use
importlib.resources.abcclasses instead:importlib.resources.abc.Traversableimportlib.resources.abc.TraversableResources
(Contributed by Jason R. Coombs and Hugo van Kemenade in
93963.) -
itertools: Deprecate the support for copy, deepcopy, and pickle operations, which is undocumented, inefficient, historically buggy, and inconsistent. This will be removed in 3.14 for a significant reduction in code volume and maintenance burden. (Contributed by Raymond Hettinger in101588.) -
multiprocessing: In Python 3.14, the defaultmultiprocessingstart method will change to a safer one on Linux, BSDs, and other non-macOS POSIX platforms where'fork'is currently the default (84559). Adding a runtime warning about this was deemed too disruptive as the majority of code is not expected to care. Use the~multiprocessing.get_contextor~multiprocessing.set_start_methodAPIs to explicitly specify when your code requires'fork'. Seecontexts and start methods <multiprocessing-start-methods>. -
pkgutil:!pkgutil.find_loaderand!pkgutil.get_loaderare deprecated and will be removed in Python 3.14; useimportlib.util.find_specinstead. (Contributed by Nikita Sobolev in97850.) -
pty: The module has two undocumentedmaster_open()andslave_open()functions that have been deprecated since Python 2 but only gained a properDeprecationWarningin 3.12. Remove them in 3.14. (Contributed by Soumendra Ganguly and Gregory P. Smith in85984.) -
os:- The
st_ctimefields return byos.statandos.lstaton Windows are deprecated. In a future release, they will contain the last metadata change time, consistent with other platforms. For now, they still contain the creation time, which is also available in the newst_birthtimefield. (Contributed by Steve Dower in99726.) - On POSIX platforms,
os.forkcan now raise aDeprecationWarningwhen it can detect being called from a multithreaded process. There has always been a fundamental incompatibility with the POSIX platform when doing so. Even if such code appeared to work. We added the warning to raise awareness as issues encountered by code doing this are becoming more frequent. See theos.forkdocumentation for more details along with this discussion on fork being incompatible with threads for why we're now surfacing this longstanding platform compatibility problem to developers.
When this warning appears due to usage of
multiprocessingorconcurrent.futuresthe fix is to use a differentmultiprocessingstart method such as"spawn"or"forkserver". - The
-
shutil: The onerror argument ofshutil.rmtreeis deprecated; use onexc instead. (Contributed by Irit Katriel in102828.) -
sqlite3:default adapters and converters <sqlite3-default-converters>are now deprecated. Instead, use thesqlite3-adapter-converter-recipesand tailor them to your needs. (Contributed by Erlend E. Aasland in90016.)- In
~sqlite3.Cursor.execute,DeprecationWarningis now emitted whennamed placeholders <sqlite3-placeholders>are used together with parameters supplied as asequenceinstead of as adict. Starting from Python 3.14, using named placeholders with parameters supplied as a sequence will raise a~sqlite3.ProgrammingError. (Contributed by Erlend E. Aasland in101698.)
-
sys: Thesys.last_type,sys.last_valueandsys.last_tracebackfields are deprecated. Usesys.last_excinstead. (Contributed by Irit Katriel in102778.) -
tarfile: Extracting tar archives without specifying filter is deprecated until Python 3.14, when'data'filter will become the default. Seetarfile-extraction-filterfor details. -
typing:typing.Hashableandtyping.Sized, aliases forcollections.abc.Hashableandcollections.abc.Sizedrespectively, are deprecated. (94309.)typing.ByteString, deprecated since Python 3.9, now causes aDeprecationWarningto be emitted when it is used. (Contributed by Alex Waygood in91896.)
-
xml.etree.ElementTree: The module now emitsDeprecationWarningwhen testing the truth value of anxml.etree.ElementTree.Element. Before, the Python implementation emittedFutureWarning, and the C implementation emitted nothing. (Contributed by Jacob Walls in83122.) -
The 3-arg signatures (type, value, traceback) of
coroutine throw() <coroutine.throw>,generator throw() <generator.throw>andasync generator throw() <agen.athrow>are deprecated and may be removed in a future version of Python. Use the single-arg versions of these functions instead. (Contributed by Ofey Chan in89874.) -
DeprecationWarningis now raised when~module.__package__on a module differs from__spec__.parent <importlib.machinery.ModuleSpec.parent>(previously it wasImportWarning). (Contributed by Brett Cannon in65961.) -
Setting
~module.__package__or__cached__on a module is deprecated, and will cease to be set or taken into consideration by the import system in Python 3.14. (Contributed by Brett Cannon in65961.) -
The bitwise inversion operator (
~) on bool is deprecated. It will throw an error in Python 3.16. Usenotfor logical negation of bools instead. In the rare case that you really need the bitwise inversion of the underlyingint, convert to int explicitly:~int(x). (Contributed by Tim Hoffmann in103487.) -
Accessing
!codeobject.co_lnotabon code objects was deprecated in Python 3.10 via626, but it only got a properDeprecationWarningin 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in101866.)
Pending removal in Python 3.13
Modules (see 594):
!aifc!audioop!cgi!cgitb!chunk!crypt!imghdr!mailcap!msilib!nis!nntplib!ossaudiodev!pipes!sndhdr!spwd!sunau!telnetlib!uu!xdrlib
Other modules:
!lib2to3, and the2to3program (84540)
APIs:
!configparser.LegacyInterpolation(90765)locale.resetlocale()(90817)!turtle.RawTurtle.settiltangle(50096)!unittest.findTestCases(50096)!unittest.getTestCaseNames(50096)!unittest.makeSuite(50096)!unittest.TestProgram.usageExit(67048)!webbrowser.MacOSX(86421)classmethoddescriptor chaining (89519)
Pending removal in Python 3.14
-
argparse: The type, choices, and metavar parameters of!argparse.BooleanOptionalActionare deprecated and will be removed in 3.14. (Contributed by Nikita Sobolev in92248.) -
ast: The following features have been deprecated in documentation since Python 3.8, now cause aDeprecationWarningto be emitted at runtime when they are accessed or used, and will be removed in Python 3.14:!ast.Num!ast.Str!ast.Bytes!ast.NameConstant!ast.Ellipsis
Use
ast.Constantinstead. (Contributed by Serhiy Storchaka in90953.) -
asyncio:- The child watcher classes
!asyncio.MultiLoopChildWatcher,!asyncio.FastChildWatcher,!asyncio.AbstractChildWatcherand!asyncio.SafeChildWatcherare deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in94597.) !asyncio.set_child_watcher,!asyncio.get_child_watcher,!asyncio.AbstractEventLoopPolicy.set_child_watcherand!asyncio.AbstractEventLoopPolicy.get_child_watcherare deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in94597.)- The
~asyncio.get_event_loopmethod of the default event loop policy now emits aDeprecationWarningif there is no current event loop set and it decides to create one. (Contributed by Serhiy Storchaka and Guido van Rossum in100160.)
- The child watcher classes
-
email: Deprecated the isdst parameter inemail.utils.localtime. (Contributed by Alan Williams in72346.) -
importlib.abcdeprecated classes:!importlib.abc.ResourceReader!importlib.abc.Traversable!importlib.abc.TraversableResources
Use
importlib.resources.abcclasses instead:importlib.resources.abc.Traversableimportlib.resources.abc.TraversableResources
(Contributed by Jason R. Coombs and Hugo van Kemenade in
93963.) -
itertoolshad undocumented, inefficient, historically buggy, and inconsistent support for copy, deepcopy, and pickle operations. This will be removed in 3.14 for a significant reduction in code volume and maintenance burden. (Contributed by Raymond Hettinger in101588.) -
multiprocessing: The default start method will change to a safer one on Linux, BSDs, and other non-macOS POSIX platforms where'fork'is currently the default (84559). Adding a runtime warning about this was deemed too disruptive as the majority of code is not expected to care. Use the~multiprocessing.get_contextor~multiprocessing.set_start_methodAPIs to explicitly specify when your code requires'fork'. Seemultiprocessing-start-methods. -
pathlib:~pathlib.PurePath.is_relative_toand~pathlib.PurePath.relative_to: passing additional arguments is deprecated. -
pkgutil:!pkgutil.find_loaderand!pkgutil.get_loadernow raiseDeprecationWarning; useimportlib.util.find_specinstead. (Contributed by Nikita Sobolev in97850.) -
pty:master_open(): usepty.openpty.slave_open(): usepty.openpty.
-
sqlite3:!versionand!version_info.~sqlite3.Cursor.executeand~sqlite3.Cursor.executemanyifnamed placeholders <sqlite3-placeholders>are used and parameters is a sequence instead of adict.
-
urllib:!urllib.parse.Quoteris deprecated: it was not intended to be a public API. (Contributed by Gregory P. Smith in88168.)
Pending removal in Python 3.15
- The import system:
- Setting
__cached__on a module while failing to set__spec__.cached <importlib.machinery.ModuleSpec.cached>is deprecated. In Python 3.15,__cached__will cease to be set or take into consideration by the import system or standard library. (97879)
- Setting
ctypes:- The undocumented
!ctypes.SetPointerTypefunction has been deprecated since Python 3.13.
- The undocumented
http.server:- The obsolete and rarely used
!CGIHTTPRequestHandlerhas been deprecated since Python 3.13. No direct replacement exists. Anything is better than CGI to interface a web server with a request handler. - The
!--cgiflag to thepython -m http.servercommand-line interface has been deprecated since Python 3.13.
- The obsolete and rarely used
importlib:load_module()method: useexec_module()instead.
pathlib:!.PurePath.is_reservedhas been deprecated since Python 3.13. Useos.path.isreservedto detect reserved paths on Windows.
platform:!platform.java_verhas been deprecated since Python 3.13. This function is only useful for Jython support, has a confusing API, and is largely untested.
sysconfig:- The check_home argument of
sysconfig.is_python_buildhas been deprecated since Python 3.12.
- The check_home argument of
threading:~threading.RLockwill take no arguments in Python 3.15. Passing any arguments has been deprecated since Python 3.14, as the Python version does not permit any arguments, but the C version allows any number of positional or keyword arguments, ignoring every argument.
types:types.CodeType: Accessing!codeobject.co_lnotabwas deprecated in626since 3.10 and was planned to be removed in 3.12, but it only got a properDeprecationWarningin 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in101866.)
typing:- The undocumented keyword argument syntax for creating
~typing.NamedTupleclasses (for example,Point = NamedTuple("Point", x=int, y=int)) has been deprecated since Python 3.13. Use the class-based syntax or the functional syntax instead. - When using the functional syntax of
~typing.TypedDicts, failing to pass a value to the fields parameter (TD = TypedDict("TD")) or passingNone(TD = TypedDict("TD", None)) has been deprecated since Python 3.13. Useclass TD(TypedDict): passorTD = TypedDict("TD", {})to create a TypedDict with zero field. - The
!typing.no_type_check_decoratordecorator function has been deprecated since Python 3.13. After eight years in thetypingmodule, it has yet to be supported by any major type checker.
- The undocumented keyword argument syntax for creating
!sre_compile,!sre_constantsand!sre_parsemodules.wave:- The
getmark(),setmark()andgetmarkers()methods of the~wave.Wave_readand~wave.Wave_writeclasses have been deprecated since Python 3.13.
- The
zipimport:!zipimport.zipimporter.load_modulehas been deprecated since Python 3.10. Use~zipimport.zipimporter.exec_moduleinstead. (125746.)
Pending removal in Python 3.16
- The import system:
- Setting
~module.__loader__on a module while failing to set__spec__.loader <importlib.machinery.ModuleSpec.loader>is deprecated. In Python 3.16,!__loader__will cease to be set or taken into consideration by the import system or the standard library. - Setting
~module.__package__on a module while failing to set__spec__.parent <importlib.machinery.ModuleSpec.parent>is deprecated. In Python 3.16,!__package__will cease to be taken into consideration by the import system or standard library. (97879)
- Setting
- The bundled copy of
libmpdec. array:- The
'u'format code (wchar_t) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the'w'format code (Py_UCS4) for Unicode characters instead.
- The
asyncio:-
!asyncio.iscoroutinefunctionis deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunctioninstead. (Contributed by Jiahao Li and Kumar Aditya in122875.) -
asynciopolicy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:!asyncio.AbstractEventLoopPolicy!asyncio.DefaultEventLoopPolicy!asyncio.WindowsSelectorEventLoopPolicy!asyncio.WindowsProactorEventLoopPolicy!asyncio.get_event_loop_policy!asyncio.set_event_loop_policy
Users should use
asyncio.runorasyncio.Runnerwith loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)(Contributed by Kumar Aditya in
127949.)
-
builtins:- Bitwise inversion on boolean types,
~Trueor~Falsehas been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2and-1). Usenot xinstead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert tointexplicitly (~int(x)).
- Bitwise inversion on boolean types,
functools:- Calling the Python implementation of
functools.reducewith function or sequence as keyword arguments has been deprecated since Python 3.14.
- Calling the Python implementation of
logging:- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
115032.)
- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
mimetypes:- Valid extensions start with a '.' or are empty for
mimetypes.MimeTypes.add_type. Undotted extensions are deprecated and will raise aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in75223.)
- Valid extensions start with a '.' or are empty for
shutil:- The
!ExecErrorexception has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4, and is now an alias ofRuntimeError.
- The
symtable:- The
!symtable.Class.get_methodsmethod has been deprecated since Python 3.14.
- The
sys:- The
!_enablelegacywindowsfsencodingfunction has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
- The
sysconfig:- The
!sysconfig.expand_makefile_varsfunction has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead.
- The
tarfile:- The undocumented and unused
!TarInfo.tarfileattribute has been deprecated since Python 3.13.
- The undocumented and unused
Pending removal in Python 3.17
datetime:~datetime.datetime.strptimecalls using a format string containing%e(day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in70647.)
collections.abc:-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
encodings:- Passing non-ascii encoding names to
encodings.normalize_encodingis deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in136702.)
- Passing non-ascii encoding names to
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOS. (137586)
typing:-
Before Python 3.14, old-style unions were implemented using the private class
typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers liketyping.get_originandtyping.get_argsinstead of relying on private implementation details. -
typing.ByteString, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
tkinter:- The
!tkinter.Variablemethods!trace_variable,!trace(an alias of!trace_variable),!trace_vdeleteand!trace_vinfo, deprecated since Python 3.14, are scheduled for removal in Python 3.17. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)
- The
Pending removal in Python 3.19
builtins:- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.)
- Passing a complex number as the real or imag argument in the
ctypes:- Implicitly switching to the MSVC-compatible struct layout by setting
~ctypes.Structure._pack_but not~ctypes.Structure._layout_on non-Windows platforms.
- Implicitly switching to the MSVC-compatible struct layout by setting
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in various!hashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.
-
http.cookies:http.cookies.Morsel.js_outputis deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_outputis deprecated and will be removed in Python 3.19.
imaplib:-
Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.Before Python 3.14, this property was used to implement the corresponding
read()andreadline()methods for~imaplib.IMAP4but this is no longer the case since then.
-
tkinter:tkinter.filedialog.askopenfileshas been deprecated since Python 3.16. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.20
-
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling~object.__init__method on initialized~struct.Structobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.) -
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.) -
Deprecations defined by
829:- Warnings are produced for
importlines found in{name}.pthfiles. {name}.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in
148641.) - Warnings are produced for
-
ast:- Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.
- Creating instances of abstract AST nodes (such as
-
typing:-
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
Pending removal in Python 3.21
-
abc- Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively.
- Soft-deprecated since Python 3.3
-
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
- Classes
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodis deprecated since Python 3.16 and will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
-
struct:- Soft-deprecated since Python 3.15, using
'F'and'D'type codes are now deprecated. These codes will be removed in Python 3.21. Use instead two-letter forms'Zf'and'Zd'.
- Soft-deprecated since Python 3.15, using
-
tempfile:tempfile._TemporaryFileWrapperwill be removed in Python 3.21. Use the publictempfile.TemporaryFileWrapperinstead.
Pending removal in future versions
The following APIs will be removed in the future, although there is currently no date scheduled for their removal.
argparse:- Nesting argument groups and nesting mutually exclusive groups are deprecated.
- Passing the undocumented keyword argument prefix_chars to
~argparse.ArgumentParser.add_argument_groupis now deprecated. - The
argparse.FileTypetype converter is deprecated.
builtins:- Generators:
throw(type, exc, tb)andathrow(type, exc, tb)signature is deprecated: usethrow(exc)andathrow(exc)instead, the single argument signature. - Currently Python accepts numeric literals immediately followed by keywords, for example
0in x,1or x,0if 1else 2. It allows confusing and ambiguous expressions like[0x1for x in y](which can be interpreted as[0x1 for x in y]or[0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In a future release it will be changed to a syntax error. (87999) - Support for
__index__()and__int__()method returning non-int type: these methods will be required to return an instance of a strict subclass ofint. - Support for
__float__()method returning a strict subclass offloat: these methods will be required to return an instance offloat. - Support for
__complex__()method returning a strict subclass ofcomplex: these methods will be required to return an instance ofcomplex.
- Generators:
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.)codecs: useopeninstead ofcodecs.open. (133038)!codeobject.co_lnotab: use thecodeobject.co_linesmethod instead.datetime:~datetime.datetime.utcnow: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp: usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: Plural value must be an integer.importlib:~importlib.util.cache_from_sourcedebug_override parameter is deprecated: use the optimization parameter instead.
importlib.metadata:EntryPointstuple interface.- Implicit
Noneon return values.
logging: thewarn()method has been deprecated since Python 3.3, use~logging.warninginstead.mailbox: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.os: Callingos.register_at_forkin a multi-threaded process.os.path:os.path.commonprefixis deprecated, useos.path.commonpathfor path prefixes. Theos.path.commonprefixfunction is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.!pydoc.ErrorDuringImport: A tuple value for exc_info parameter is deprecated, use an exception instance.re: More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in91760.)shutil:~shutil.rmtree's onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:~ssl.SSLContext.set_npn_protocolsand!selected_npn_protocolare deprecated: use ALPN instead.ssl.OP_NO_SSL*optionsssl.OP_NO_TLS*optionsssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.TLSVersion.TLSv1_1
threadingmethods:!threading.Condition.notifyAll: use~threading.Condition.notify_all.!threading.Event.isSet: use~threading.Event.is_set.!threading.Thread.isDaemon,threading.Thread.setDaemon: usethreading.Thread.daemonattribute.!threading.Thread.getName,threading.Thread.setName: usethreading.Thread.nameattribute.!threading.currentThread: usethreading.current_thread.!threading.activeCount: usethreading.active_count.
typing.Text(92332).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in105499.) unittest.IsolatedAsyncioTestCase: it is deprecated to return a value that is notNonefrom a test case.urllib.parsedeprecated functions:~urllib.parse.urlparseinsteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partial writes.xml.etree.ElementTree: Testing the truth value of an~xml.etree.ElementTree.Elementis deprecated. In a future release it will always returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cacheis deprecated: usesys._clear_internal_cachesinstead.
Removed
asynchat and asyncore
- These two modules have been removed according to the schedule in
594, having been deprecated in Python 3.6. Useasyncioinstead. (Contributed by Nikita Sobolev in96580.)
configparser
- Several names deprecated in the
configparserway back in 3.2 have been removed per89336:configparser.ParsingErrorno longer has afilenameattribute or argument. Use thesourceattribute and argument instead.configparserno longer has aSafeConfigParserclass. Use the shorter~configparser.ConfigParsername instead.configparser.ConfigParserno longer has areadfpmethod. Use~configparser.ConfigParser.read_fileinstead.
distutils
- Remove the
!distutilspackage. It was deprecated in Python 3.10 by632"Deprecate distutils module". For projects still usingdistutilsand cannot be updated to something else, thesetuptoolsproject can be installed: it still providesdistutils. (Contributed by Victor Stinner in92584.)
ensurepip
-
Remove the bundled setuptools wheel from
ensurepip, and stop installing setuptools in environments created byvenv.pip (>= 22.1)does not require setuptools to be installed in the environment.setuptools-based (anddistutils-based) packages can still be used withpip install, since pip will providesetuptoolsin the build environment it uses for building a package.easy_install,pkg_resources,setuptoolsanddistutilsare no longer provided by default in environments created withvenvor bootstrapped withensurepip, since they are part of thesetuptoolspackage. For projects relying on these at runtime, thesetuptoolsproject should be declared as a dependency and installed separately (typically, using pip).(Contributed by Pradyun Gedam in
95299.)
enum
- Remove
enum'sEnumMeta.__getattr__, which is no longer needed for enum attribute access. (Contributed by Ethan Furman in95083.)
ftplib
- Remove
ftplib'sFTP_TLS.ssl_versionclass attribute: use the context parameter instead. (Contributed by Victor Stinner in94172.)
gzip
- Remove the
filenameattribute ofgzip'sgzip.GzipFile, deprecated since Python 2.6, use the~gzip.GzipFile.nameattribute instead. In write mode, thefilenameattribute added'.gz'file extension if it was not present. (Contributed by Victor Stinner in94196.)
hashlib
- Remove the pure Python implementation of
hashlib'shashlib.pbkdf2_hmac, deprecated in Python 3.10. Python 3.10 and newer requires OpenSSL 1.1.1 (644): this OpenSSL version provides a C implementation of~hashlib.pbkdf2_hmacwhich is faster. (Contributed by Victor Stinner in94199.)
importlib
- Many previously deprecated cleanups in
importlibhave now been completed:- References to, and support for
!module_reprhas been removed. (Contributed by Barry Warsaw in97850.) importlib.util.set_package,importlib.util.set_loaderandimportlib.util.module_for_loaderhave all been removed. (Contributed by Brett Cannon and Nikita Sobolev in65961and97850.)- Support for
find_loader()andfind_module()APIs have been removed. (Contributed by Barry Warsaw in98040.) importlib.abc.Finder,pkgutil.ImpImporter, andpkgutil.ImpLoaderhave been removed. (Contributed by Barry Warsaw in98040.)
- References to, and support for
imp
-
The
!impmodule has been removed. (Contributed by Barry Warsaw in98040.)To migrate, consult the following correspondence table:
imp importlib imp.NullImporterInsert Noneintosys.path_importer_cacheimp.cache_from_source()importlib.util.cache_from_sourceimp.find_module()importlib.util.find_specimp.get_magic()importlib.util.MAGIC_NUMBERimp.get_suffixes()importlib.machinery.SOURCE_SUFFIXES,importlib.machinery.EXTENSION_SUFFIXES, andimportlib.machinery.BYTECODE_SUFFIXESimp.get_tag()sys.implementation.cache_tag <sys.implementation>imp.load_module()importlib.import_moduleimp.new_module(name)types.ModuleType(name)imp.reload()importlib.reloadimp.source_from_cache()importlib.util.source_from_cacheimp.load_source()See below Replace
imp.load_source()with:import importlib.util import importlib.machinery def load_source(modname, filename): loader = importlib.machinery.SourceFileLoader(modname, filename) spec = importlib.util.spec_from_file_location(modname, filename, loader=loader) module = importlib.util.module_from_spec(spec) # The module is always executed and not cached in sys.modules. # Uncomment the following line to cache the module. # sys.modules[module.__name__] = module loader.exec_module(module) return module -
Remove
!impfunctions and attributes with no replacements:- Undocumented functions:
imp.init_builtin()imp.load_compiled()imp.load_dynamic()imp.load_package()
imp.lock_held(),imp.acquire_lock(),imp.release_lock(): the locking scheme has changed in Python 3.3 to per-module locks.imp.find_module()constants:SEARCH_ERROR,PY_SOURCE,PY_COMPILED,C_EXTENSION,PY_RESOURCE,PKG_DIRECTORY,C_BUILTIN,PY_FROZEN,PY_CODERESOURCE,IMP_HOOK.
- Undocumented functions:
io
- Remove
io'sio.OpenWrapperand_pyio.OpenWrapper, deprecated in Python 3.10: just useopeninstead. Theopen(io.open) function is a built-in function. Since Python 3.10,!_pyio.openis also a static method. (Contributed by Victor Stinner in94169.)
locale
- Remove
locale's!locale.formatfunction, deprecated in Python 3.7: uselocale.format_stringinstead. (Contributed by Victor Stinner in94226.)
smtpd
- The
smtpdmodule has been removed according to the schedule in594, having been deprecated in Python 3.4.7 and 3.5.4. Use theaiosmtpdPyPI module or any otherasyncio-based server instead. (Contributed by Oleg Iarygin in93243.)
sqlite3
-
The following undocumented
sqlite3features, deprecated in Python 3.10, are now removed:sqlite3.enable_shared_cache()sqlite3.OptimizedUnicode
If a shared cache must be used, open the database in URI mode using the
cache=sharedquery parameter.The
sqlite3.OptimizedUnicodetext factory has been an alias forstrsince Python 3.3. Code that previously set the text factory toOptimizedUnicodecan either usestrexplicitly, or rely on the default value which is alsostr.(Contributed by Erlend E. Aasland in
92548.)
ssl
- Remove
ssl's!ssl.RAND_pseudo_bytesfunction, deprecated in Python 3.6: useos.urandomorssl.RAND_bytesinstead. (Contributed by Victor Stinner in94199.) - Remove the
!ssl.match_hostnamefunction. It was deprecated in Python 3.7. OpenSSL performs hostname matching since Python 3.7, Python no longer uses the!ssl.match_hostnamefunction. (Contributed by Victor Stinner in94199.) - Remove the
!ssl.wrap_socketfunction, deprecated in Python 3.7: instead, create assl.SSLContextobject and call itsssl.SSLContext.wrap_socketmethod. Any package that still uses!ssl.wrap_socketis broken and insecure. The function neither sends a SNI TLS extension nor validates the server hostname. Code is subject to295(Improper Certificate Validation). (Contributed by Victor Stinner in94199.)
unittest
-
Remove many long-deprecated
unittestfeatures:-
A number of
~unittest.TestCasemethod aliases:Deprecated alias Method Name Deprecated in failUnless.assertTrue3.1 failIf.assertFalse3.1 failUnlessEqual.assertEqual3.1 failIfEqual.assertNotEqual3.1 failUnlessAlmostEqual.assertAlmostEqual3.1 failIfAlmostEqual.assertNotAlmostEqual3.1 failUnlessRaises.assertRaises3.1 assert_.assertTrue3.2 assertEquals.assertEqual3.2 assertNotEquals.assertNotEqual3.2 assertAlmostEquals.assertAlmostEqual3.2 assertNotAlmostEquals.assertNotAlmostEqual3.2 assertRegexpMatches.assertRegex3.2 assertRaisesRegexp.assertRaisesRegex3.2 assertNotRegexpMatches.assertNotRegex3.5 You can use https://github.com/isidentical/teyit to automatically modernise your unit tests.
-
Undocumented and broken
~unittest.TestCasemethodassertDictContainsSubset(deprecated in Python 3.2). -
Undocumented
TestLoader.loadTestsFromModule <unittest.TestLoader.loadTestsFromModule>parameter use_load_tests (deprecated and ignored since Python 3.5). -
An alias of the
~unittest.TextTestResultclass:_TextTestResult(deprecated in Python 3.2).
(Contributed by Serhiy Storchaka in
89325.) -
webbrowser
- Remove support for obsolete browsers from
webbrowser. The removed browsers include: Grail, Mosaic, Netscape, Galeon, Skipstone, Iceape, Firebird, and Firefox versions 35 and below (102871).
xml.etree.ElementTree
- Remove the
ElementTree.Element.copy()method of the pure Python implementation, deprecated in Python 3.10, use thecopy.copyfunction instead. The C implementation ofxml.etree.ElementTreehas nocopy()method, only a__copy__()method. (Contributed by Victor Stinner in94383.)
zipimport
- Remove
zipimport'sfind_loader()andfind_module()methods, deprecated in Python 3.10: use thefind_spec()method instead. See451for the rationale. (Contributed by Victor Stinner in94379.)
Others
- Remove the
suspiciousrule from the documentationMakefileandDoc/tools/rstlint.py, both in favor of sphinx-lint. (Contributed by Julien Palard in98179.) - Remove the keyfile and certfile parameters from the
ftplib,imaplib,poplibandsmtplibmodules, and the key_file, cert_file and check_hostname parameters from thehttp.clientmodule, all deprecated since Python 3.6. Use the context parameter (ssl_context inimaplib) instead. (Contributed by Victor Stinner in94172.) - Remove
Jythoncompatibility hacks from several stdlib modules and tests. (Contributed by Nikita Sobolev in99482.) - Remove
_use_broken_old_ctypes_structure_semantics_flag fromctypesmodule. (Contributed by Nikita Sobolev in99285.)
Porting to Python 3.12
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in the Python API
-
More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in
91760.) -
Remove
randrange()functionality deprecated since Python 3.10. Formerly,randrange(10.0)losslessly converted torandrange(10). Now, it raises aTypeError. Also, the exception raised for non-integer values such asrandrange(10.5)orrandrange('10')has been changed fromValueErrortoTypeError. This also prevents bugs whererandrange(1e25)would silently select from a larger range thanrandrange(10**25). (Originally suggested by Serhiy Storchaka86388.) -
argparse.ArgumentParserchanged encoding and error handler for reading arguments from file (e.g.fromfile_prefix_charsoption) from default text encoding (e.g.locale.getpreferredencoding(False) <locale.getpreferredencoding>) tofilesystem encoding and error handler. Argument files should be encoded in UTF-8 instead of ANSI Codepage on Windows. -
Remove the
asyncore-basedsmtpdmodule deprecated in Python 3.4.7 and 3.5.4. A recommended replacement is theasyncio-basedaiosmtpdPyPI module. -
shlex.split: PassingNonefor s argument now raises an exception, rather than readingsys.stdin. The feature was deprecated in Python 3.9. (Contributed by Victor Stinner in94352.) -
The
osmodule no longer accepts bytes-like paths, likebytearrayandmemoryviewtypes: only the exactbytestype is accepted for bytes strings. (Contributed by Victor Stinner in98393.) -
syslog.openlogandsyslog.closelognow fail if used in subinterpreters.syslog.syslogmay still be used in subinterpreters, but now only ifsyslog.openloghas already been called in the main interpreter. These new restrictions do not apply to the main interpreter, so only a very small set of users might be affected. This change helps with interpreter isolation. Furthermore,syslogis a wrapper around process-global resources, which are best managed from the main interpreter. (Contributed by Donghee Na in99127.) -
The undocumented locking behavior of
~functools.cached_propertyis removed, because it locked across all instances of the class, leading to high lock contention. This means that a cached property getter function could now run more than once for a single instance, if two threads race. For most simple cached properties (e.g. those that are idempotent and simply calculate a value based on other attributes of the instance) this will be fine. If synchronization is needed, implement locking within the cached property getter function or around multi-threaded access points. -
sys._current_exceptionsnow returns a mapping from thread-id to an exception instance, rather than to a(typ, exc, tb)tuple. (Contributed by Irit Katriel in103176.) -
When extracting tar files using
tarfileorshutil.unpack_archive, pass the filter argument to limit features that may be surprising or dangerous. Seetarfile-extraction-filterfor details. -
The output of the
tokenize.tokenizeandtokenize.generate_tokensfunctions is now changed due to the changes introduced in701. This means thatSTRINGtokens are not emitted any more for f-strings and the tokens described in701are now produced instead:FSTRING_START,FSTRING_MIDDLEandFSTRING_ENDare now emitted for f-string "string" parts in addition to the appropriate tokens for the tokenization in the expression components. For example for the f-stringf"start {1+1} end"the old version of the tokenizer emitted:1,0-1,18: STRING 'f"start {1+1} end"'while the new version emits:
1,0-1,2: FSTRING_START 'f"' 1,2-1,8: FSTRING_MIDDLE 'start ' 1,8-1,9: OP '{' 1,9-1,10: NUMBER '1' 1,10-1,11: OP '+' 1,11-1,12: NUMBER '1' 1,12-1,13: OP '}' 1,13-1,17: FSTRING_MIDDLE ' end' 1,17-1,18: FSTRING_END '"'Additionally, there may be some minor behavioral changes as a consequence of the changes required to support
701. Some of these changes include:- The
typeattribute of the tokens emitted when tokenizing some invalid Python characters such as!has changed fromERRORTOKENtoOP. - Incomplete single-line strings now also raise
tokenize.TokenErroras incomplete multiline strings do. - Some incomplete or invalid Python code now raises
tokenize.TokenErrorinstead of returning arbitraryERRORTOKENtokens when tokenizing it. - Mixing tabs and spaces as indentation in the same file is not supported anymore and will raise a
TabError.
- The
-
The
threadingmodule now expects the!_threadmodule to have an_is_main_interpreterattribute. It is a function with no arguments that returnsTrueif the current interpreter is the main interpreter.Any library or application that provides a custom
_threadmodule should provide_is_main_interpreter(). (See112826.)
Build Changes
-
Python no longer uses
setup.pyto build shared C extension modules. Build parameters like headers and libraries are detected inconfigurescript. Extensions are built byMakefile. Most extensions usepkg-configand fall back to manual detection. (Contributed by Christian Heimes in93939.) -
va_start()with two parameters, likeva_start(args, format),is now required to build Python.va_start()is no longer called with a single parameter. (Contributed by Kumar Aditya in93207.) -
CPython now uses the ThinLTO option as the default link time optimization policy if the Clang compiler accepts the flag. (Contributed by Donghee Na in
89536.) -
Add
COMPILEALL_OPTSvariable inMakefileto overridecompilealloptions (default:-j0) inmake install. Also merged the 3compileallcommands into a single command to build .pyc files for all optimization levels (0, 1, 2) at once. (Contributed by Victor Stinner in99289.) -
Add platform triplets for 64-bit LoongArch:
- loongarch64-linux-gnusf
- loongarch64-linux-gnuf32
- loongarch64-linux-gnu
(Contributed by Zhang Na in
90656.) -
PYTHON_FOR_REGENnow require Python 3.10 or newer. -
Autoconf 2.71 and aclocal 1.16.4 is now required to regenerate
configure. (Contributed by Christian Heimes in89886.) -
Windows builds and macOS installers from python.org now use OpenSSL 3.0.
C API Changes
New Features
-
697: Introduce theUnstable C API tier <unstable-c-api>, intended for low-level tools like debuggers and JIT compilers. This API may change in each minor release of CPython without deprecation warnings. Its contents are marked by thePyUnstable_prefix in names.Code object constructors:
PyUnstable_Code_New()(renamed fromPyCode_New)PyUnstable_Code_NewWithPosOnlyArgs()(renamed fromPyCode_NewWithPosOnlyArgs)
Extra storage for code objects (
523):PyUnstable_Eval_RequestCodeExtraIndex()(renamed from_PyEval_RequestCodeExtraIndex)PyUnstable_Code_GetExtra()(renamed from_PyCode_GetExtra)PyUnstable_Code_SetExtra()(renamed from_PyCode_SetExtra)
The original names will continue to be available until the respective API changes.
(Contributed by Petr Viktorin in
101101.) -
697: Add an API for extending types whose instance memory layout is opaque:PyType_Spec.basicsizecan be zero or negative to specify inheriting or extending the base class size.PyObject_GetTypeDataandPyType_GetTypeDataSizeadded to allow access to subclass-specific instance data.Py_TPFLAGS_ITEMS_AT_ENDandPyObject_GetItemDataadded to allow safely extending certain variable-sized types, includingPyType_Type.Py_RELATIVE_OFFSETadded to allow definingmembers <PyMemberDef>in terms of a subclass-specific struct.
(Contributed by Petr Viktorin in
103509.) -
Add the new
limited C API <limited-c-api>functionPyType_FromMetaclass, which generalizes the existingPyType_FromModuleAndSpecusing an additional metaclass argument. (Contributed by Wenzel Jakob in93012.) -
API for creating objects that can be called using
the vectorcall protocol <vectorcall>was added to theLimited API <stable>:Py_TPFLAGS_HAVE_VECTORCALLPyVectorcall_NARGSPyVectorcall_Callvectorcallfunc
The
Py_TPFLAGS_HAVE_VECTORCALLflag is now removed from a class when the class's~object.__call__method is reassigned. This makes vectorcall safe to use with mutable types (i.e. heap types without the immutable flag,Py_TPFLAGS_IMMUTABLETYPE). Mutable types that do not override~PyTypeObject.tp_callnow inherit thePy_TPFLAGS_HAVE_VECTORCALLflag. (Contributed by Petr Viktorin in93274.)The
Py_TPFLAGS_MANAGED_DICTandPy_TPFLAGS_MANAGED_WEAKREFflags have been added. This allows extensions classes to support object~object.__dict__and weakrefs with less bookkeeping, using less memory and with faster access. -
API for performing calls using
the vectorcall protocol <vectorcall>was added to theLimited API <stable>:PyObject_VectorcallPyObject_VectorcallMethodPY_VECTORCALL_ARGUMENTS_OFFSET
This means that both the incoming and outgoing ends of the vector call protocol are now available in the
Limited API <stable>. (Contributed by Wenzel Jakob in98586.) -
Add two new public functions,
PyEval_SetProfileAllThreadsandPyEval_SetTraceAllThreads, that allow to set tracing and profiling functions in all running threads in addition to the calling one. (Contributed by Pablo Galindo in93503.) -
Add new function
PyFunction_SetVectorcallto the C API which sets the vectorcall field of a givenPyFunctionObject. (Contributed by Andrew Frost in92257.) -
The C API now permits registering callbacks via
PyDict_AddWatcher,PyDict_Watchand related APIs to be called whenever a dictionary is modified. This is intended for use by optimizing interpreters, JIT compilers, or debuggers. (Contributed by Carl Meyer in91052.) -
Add
PyType_AddWatcherandPyType_WatchAPI to register callbacks to receive notification on changes to a type. (Contributed by Carl Meyer in91051.) -
Add
PyCode_AddWatcherandPyCode_ClearWatcherAPIs to register callbacks to receive notification on creation and destruction of code objects. (Contributed by Itamar Oren in91054.) -
Add
PyFrame_GetVarandPyFrame_GetVarStringfunctions to get a frame variable by its name. (Contributed by Victor Stinner in91248.) -
Add
PyErr_GetRaisedExceptionandPyErr_SetRaisedExceptionfor saving and restoring the current exception. These functions return and accept a single exception object, rather than the triple arguments of the now-deprecatedPyErr_FetchandPyErr_Restore. This is less error prone and a bit more efficient. (Contributed by Mark Shannon in101578.) -
Add
_PyErr_ChainExceptions1, which takes an exception instance, to replace the legacy-API_PyErr_ChainExceptions, which is now deprecated. (Contributed by Mark Shannon in101578.) -
Add
PyException_GetArgsandPyException_SetArgsas convenience functions for retrieving and modifying the~BaseException.argspassed to the exception's constructor. (Contributed by Mark Shannon in101578.) -
Add
PyErr_DisplayException, which takes an exception instance, to replace the legacy-api!PyErr_Display. (Contributed by Irit Katriel in102755).
-
683: Introduce Immortal Objects, which allows objects to bypass reference counts, and related changes to the C-API:_Py_IMMORTAL_REFCNT: The reference count that defines an object as immortal._Py_IsImmortalChecks if an object has the immortal reference count.PyObject_HEAD_INITThis will now initialize reference count to_Py_IMMORTAL_REFCNTwhen used withPy_BUILD_CORE.SSTATE_INTERNED_IMMORTALAn identifier for interned unicode objects that are immortal.SSTATE_INTERNED_IMMORTAL_STATICAn identifier for interned unicode objects that are immortal and staticsys.getunicodeinternedsizeThis returns the total number of unicode objects that have been interned. This is now needed forrefleak.pyto correctly track reference counts and allocated blocks
(Contributed by Eddie Elizondo in
84436.) -
684: Add the newPy_NewInterpreterFromConfigfunction andPyInterpreterConfig, which may be used to create sub-interpreters with their own GILs. (Seewhatsnew312-pep684for more info.) (Contributed by Eric Snow in104110.) -
In the limited C API version 3.12,
Py_INCREFandPy_DECREFfunctions are now implemented as opaque function calls to hide implementation details. (Contributed by Victor Stinner in105387.)
Porting to Python 3.12
-
Legacy Unicode APIs based on
Py_UNICODE*representation has been removed. Please migrate to APIs based on UTF-8 orwchar_t*. -
Argument parsing functions like
PyArg_ParseTupledoesn't supportPy_UNICODE*based format (e.g.u,Z) anymore. Please migrate to other formats for Unicode likes,z,es, andU. -
tp_weaklistfor all static builtin types is alwaysNULL. This is an internal-only field onPyTypeObjectbut we're pointing out the change in case someone happens to be accessing the field directly anyway. To avoid breakage, consider using the existing public C-API instead, or, if necessary, the (internal-only)_PyObject_GET_WEAKREFS_LISTPTR()macro. -
This internal-only
PyTypeObject.tp_subclassesmay now not be a valid object pointer. Its type was changed tovoid *to reflect this. We mention this in case someone happens to be accessing the internal-only field directly.To get a list of subclasses, call the Python method
~type.__subclasses__(usingPyObject_CallMethod, for example). -
Add support of more formatting options (left aligning, octals, uppercase hexadecimals,
intmax_t,ptrdiff_t,wchar_tC strings, variable width and precision) inPyUnicode_FromFormatandPyUnicode_FromFormatV. (Contributed by Serhiy Storchaka in98836.) -
An unrecognized format character in
PyUnicode_FromFormatandPyUnicode_FromFormatVnow sets aSystemError. In previous versions it caused all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded. (Contributed by Serhiy Storchaka in95781.) -
Fix wrong sign placement in
PyUnicode_FromFormatandPyUnicode_FromFormatV. (Contributed by Philip Georgi in95504.) -
Extension classes wanting to add a
~object.__dict__or weak reference slot should usePy_TPFLAGS_MANAGED_DICTandPy_TPFLAGS_MANAGED_WEAKREFinstead oftp_dictoffsetandtp_weaklistoffset, respectively. The use oftp_dictoffsetandtp_weaklistoffsetis still supported, but does not fully support multiple inheritance (95589), and performance may be worse. Classes declaringPy_TPFLAGS_MANAGED_DICTmust call!_PyObject_VisitManagedDictand!_PyObject_ClearManagedDictto traverse and clear their instance's dictionaries. To clear weakrefs, callPyObject_ClearWeakRefs, as before. -
The
PyUnicode_FSDecoderfunction no longer accepts bytes-like paths, likebytearrayandmemoryviewtypes: only the exactbytestype is accepted for bytes strings. (Contributed by Victor Stinner in98393.) -
The
Py_CLEAR,Py_SETREFandPy_XSETREFmacros now only evaluate their arguments once. If an argument has side effects, these side effects are no longer duplicated. (Contributed by Victor Stinner in98724.) -
The interpreter's error indicator is now always normalized. This means that
PyErr_SetObject,PyErr_SetStringand the other functions that set the error indicator now normalize the exception before storing it. (Contributed by Mark Shannon in101578.) -
_Py_RefTotalis no longer authoritative and only kept around for ABI compatibility. Note that it is an internal global and only available on debug builds. If you happen to be using it then you'll need to start using_Py_GetGlobalRefTotal(). -
The following functions now select an appropriate metaclass for the newly created type:
PyType_FromSpecPyType_FromSpecWithBasesPyType_FromModuleAndSpec
Creating classes whose metaclass overrides
~PyTypeObject.tp_newis deprecated, and in Python 3.14+ it will be disallowed. Note that these functions ignoretp_newof the metaclass, possibly allowing incomplete initialization.Note that
PyType_FromMetaclass(added in Python 3.12) already disallows creating classes whose metaclass overridestp_new(~object.__new__in Python).Since
tp_newoverrides almost everythingPyType_From*functions do, the two are incompatible with each other. The existing behavior -- ignoring the metaclass for several steps of type creation -- is unsafe in general, since (meta)classes assume thattp_newwas called. There is no simple general workaround. One of the following may work for you:- If you control the metaclass, avoid using
tp_newin it:- If initialization can be skipped, it can be done in
~PyTypeObject.tp_initinstead. - If the metaclass doesn't need to be instantiated from Python, set its
tp_newtoNULLusing thePy_TPFLAGS_DISALLOW_INSTANTIATIONflag. This makes it acceptable forPyType_From*functions.
- If initialization can be skipped, it can be done in
- Avoid
PyType_From*functions: if you don't need C-specific features (slots or setting the instance size), create types bycalling <call>the metaclass. - If you know the
tp_newcan be skipped safely, filter the deprecation warning out usingwarnings.catch_warningsfrom Python.
-
PyOS_InputHookandPyOS_ReadlineFunctionPointerare no longer called insubinterpreters <sub-interpreter-support>. This is because clients generally rely on process-wide global state (since these callbacks have no way of recovering extension module state).This also avoids situations where extensions may find themselves running in a subinterpreter that they don't support (or haven't yet been loaded in). See
104668for more info. -
PyLongObjecthas had its internals changed for better performance. Although the internals ofPyLongObjectare private, they are used by some extension modules. The internal fields should no longer be accessed directly, instead the API functions beginningPyLong_...should be used instead. Two new unstable API functions are provided for efficient access to the value ofPyLongObjects which fit into a single machine word:PyUnstable_Long_IsCompactPyUnstable_Long_CompactValue
-
Custom allocators, set via
PyMem_SetAllocator, are now required to be thread-safe, regardless of memory domain. Allocators that don't have their own state, including "hooks", are not affected. If your custom allocator is not already thread-safe and you need guidance then please create a new GitHub issue and CC@ericsnowcurrently.
Deprecated
-
In accordance with
699, thema_version_tagfield inPyDictObjectis deprecated for extension modules. Accessing this field will generate a compiler warning at compile time. This field will be removed in Python 3.14. (Contributed by Ramvikrams and Kumar Aditya in101193. PEP by Ken Jin.) -
Deprecate global configuration variable:
!Py_DebugFlag: usePyConfig.parser_debug!Py_VerboseFlag: usePyConfig.verbose!Py_QuietFlag: usePyConfig.quiet!Py_InteractiveFlag: usePyConfig.interactive!Py_InspectFlag: usePyConfig.inspect!Py_OptimizeFlag: usePyConfig.optimization_level!Py_NoSiteFlag: usePyConfig.site_import!Py_BytesWarningFlag: usePyConfig.bytes_warning!Py_FrozenFlag: usePyConfig.pathconfig_warnings!Py_IgnoreEnvironmentFlag: usePyConfig.use_environment!Py_DontWriteBytecodeFlag: usePyConfig.write_bytecode!Py_NoUserSiteDirectory: usePyConfig.user_site_directory!Py_UnbufferedStdioFlag: usePyConfig.buffered_stdio!Py_HashRandomizationFlag: usePyConfig.use_hash_seedandPyConfig.hash_seed!Py_IsolatedFlag: usePyConfig.isolated!Py_LegacyWindowsFSEncodingFlag: usePyPreConfig.legacy_windows_fs_encoding!Py_LegacyWindowsStdioFlag: usePyConfig.legacy_windows_stdio!Py_FileSystemDefaultEncoding: usePyConfig.filesystem_encoding!Py_HasFileSystemDefaultEncoding: usePyConfig.filesystem_encoding!Py_FileSystemDefaultEncodeErrors: usePyConfig.filesystem_errors!Py_UTF8Mode: usePyPreConfig.utf8_mode(seePy_PreInitialize)
The
Py_InitializeFromConfigAPI should be used withPyConfiginstead. (Contributed by Victor Stinner in77782.) -
Creating
immutable types <Py_TPFLAGS_IMMUTABLETYPE>with mutable bases is deprecated and will be disabled in Python 3.14. (95388) -
The
structmember.hheader is deprecated, though it continues to be available and there are no plans to remove it.Its contents are now available just by including
Python.h, with aPyprefix added if it was missing:PyMemberDef,PyMember_GetOneandPyMember_SetOne- Type macros like
Py_T_INT,Py_T_DOUBLE, etc. (previouslyT_INT,T_DOUBLE, etc.) - The flags
Py_READONLY(previouslyREADONLY) andPy_AUDIT_READ(previously all uppercase)
Several items are not exposed from
Python.h:T_OBJECT(usePy_T_OBJECT_EX)T_NONE(previously undocumented, and pretty quirky)- The macro
WRITE_RESTRICTEDwhich does nothing. - The macros
RESTRICTEDandREAD_RESTRICTED, equivalents ofPy_AUDIT_READ. - In some configurations,
<stddef.h>is not included fromPython.h. It should be included manually when usingoffsetof().
The deprecated header continues to provide its original contents under the original names. Your old code can stay unchanged, unless the extra include and non-namespaced macros bother you greatly.
(Contributed in
47146by Petr Viktorin, based on earlier work by Alexander Belopolsky and Matthias Braun.) -
PyErr_FetchandPyErr_Restoreare deprecated. UsePyErr_GetRaisedExceptionandPyErr_SetRaisedExceptioninstead. (Contributed by Mark Shannon in101578.) -
!PyErr_Displayis deprecated. UsePyErr_DisplayExceptioninstead. (Contributed by Irit Katriel in102755). -
_PyErr_ChainExceptionsis deprecated. Use_PyErr_ChainExceptions1instead. (Contributed by Irit Katriel in102192.) -
Using
PyType_FromSpec,PyType_FromSpecWithBasesorPyType_FromModuleAndSpecto create a class whose metaclass overrides~PyTypeObject.tp_newis deprecated. Call the metaclass instead.
Pending removal in Python 3.14
- The
ma_version_tagfield inPyDictObjectfor extension modules (699;101193). - Creating
immutable types <Py_TPFLAGS_IMMUTABLETYPE>with mutable bases (95388).
Pending removal in Python 3.15
-
The
!PyImport_ImportModuleNoBlock: UsePyImport_ImportModuleinstead. -
!PyWeakref_GetObjectand!PyWeakref_GET_OBJECT: UsePyWeakref_GetRefinstead. The pythoncapi-compat project can be used to getPyWeakref_GetRefon Python 3.12 and older. -
!PyUnicode_AsDecodedObject: UsePyCodec_Decodeinstead. -
!PyUnicode_AsDecodedUnicode: UsePyCodec_Decodeinstead; Note that some codecs (for example, "base64") may return a type other thanstr, such asbytes. -
!PyUnicode_AsEncodedObject: UsePyCodec_Encodeinstead. -
!PyUnicode_AsEncodedUnicode: UsePyCodec_Encodeinstead; Note that some codecs (for example, "base64") may return a type other thanbytes, such asstr. -
Python initialization functions, deprecated in Python 3.13:
!Py_GetPath: UsePyConfig_Get("module_search_paths") <PyConfig_Get>(sys.path) instead.!Py_GetPrefix: UsePyConfig_Get("base_prefix") <PyConfig_Get>(sys.base_prefix) instead. UsePyConfig_Get("prefix") <PyConfig_Get>(sys.prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetExecPrefix: UsePyConfig_Get("base_exec_prefix") <PyConfig_Get>(sys.base_exec_prefix) instead. UsePyConfig_Get("exec_prefix") <PyConfig_Get>(sys.exec_prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetProgramFullPath: UsePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetProgramName: UsePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetPythonHome: UsePyConfig_Get("home") <PyConfig_Get>or thePYTHONHOMEenvironment variable instead.
The pythoncapi-compat project can be used to get
PyConfig_Geton Python 3.13 and older.
Pending removal in Python 3.16
-
Functions to configure Python's initialization, deprecated in Python 3.11:
!PySys_SetArgvEx(): SetPyConfig.argvinstead.!PySys_SetArgv(): SetPyConfig.argvinstead.!Py_SetProgramName(): SetPyConfig.program_nameinstead.!Py_SetPythonHome(): SetPyConfig.homeinstead.
The
Py_InitializeFromConfigAPI should be used withPyConfiginstead. -
Global configuration variables:
!Py_DebugFlag: UsePyConfig.parser_debugorPyConfig_Get("parser_debug") <PyConfig_Get>instead.!Py_VerboseFlag: UsePyConfig.verboseorPyConfig_Get("verbose") <PyConfig_Get>instead.!Py_QuietFlag: UsePyConfig.quietorPyConfig_Get("quiet") <PyConfig_Get>instead.!Py_InteractiveFlag: UsePyConfig.interactiveorPyConfig_Get("interactive") <PyConfig_Get>instead.!Py_InspectFlag: UsePyConfig.inspectorPyConfig_Get("inspect") <PyConfig_Get>instead.!Py_OptimizeFlag: UsePyConfig.optimization_levelorPyConfig_Get("optimization_level") <PyConfig_Get>instead.!Py_NoSiteFlag: UsePyConfig.site_importorPyConfig_Get("site_import") <PyConfig_Get>instead.!Py_BytesWarningFlag: UsePyConfig.bytes_warningorPyConfig_Get("bytes_warning") <PyConfig_Get>instead.!Py_FrozenFlag: UsePyConfig.pathconfig_warningsorPyConfig_Get("pathconfig_warnings") <PyConfig_Get>instead.!Py_IgnoreEnvironmentFlag: UsePyConfig.use_environmentorPyConfig_Get("use_environment") <PyConfig_Get>instead.!Py_DontWriteBytecodeFlag: UsePyConfig.write_bytecodeorPyConfig_Get("write_bytecode") <PyConfig_Get>instead.!Py_NoUserSiteDirectory: UsePyConfig.user_site_directoryorPyConfig_Get("user_site_directory") <PyConfig_Get>instead.!Py_UnbufferedStdioFlag: UsePyConfig.buffered_stdioorPyConfig_Get("buffered_stdio") <PyConfig_Get>instead.!Py_HashRandomizationFlag: UsePyConfig.use_hash_seedandPyConfig.hash_seedorPyConfig_Get("hash_seed") <PyConfig_Get>instead.!Py_IsolatedFlag: UsePyConfig.isolatedorPyConfig_Get("isolated") <PyConfig_Get>instead.!Py_LegacyWindowsFSEncodingFlag: UsePyPreConfig.legacy_windows_fs_encodingorPyConfig_Get("legacy_windows_fs_encoding") <PyConfig_Get>instead.!Py_LegacyWindowsStdioFlag: UsePyConfig.legacy_windows_stdioorPyConfig_Get("legacy_windows_stdio") <PyConfig_Get>instead.!Py_FileSystemDefaultEncoding,!Py_HasFileSystemDefaultEncoding: UsePyConfig.filesystem_encodingorPyConfig_Get("filesystem_encoding") <PyConfig_Get>instead.!Py_FileSystemDefaultEncodeErrors: UsePyConfig.filesystem_errorsorPyConfig_Get("filesystem_errors") <PyConfig_Get>instead.!Py_UTF8Mode: UsePyPreConfig.utf8_modeorPyConfig_Get("utf8_mode") <PyConfig_Get>instead. (seePy_PreInitialize)
The
Py_InitializeFromConfigAPI should be used withPyConfigto set these options. OrPyConfig_Getcan be used to get these options at runtime. -
Py_UNICODEwhich was deprecated by393.
Pending removal in future versions
The following APIs are deprecated and will be removed, although there is currently no date scheduled for their removal.
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch: UsePyErr_GetRaisedExceptioninstead.PyErr_NormalizeException: UsePyErr_GetRaisedExceptioninstead.PyErr_Restore: UsePyErr_SetRaisedExceptioninstead.PyOS_AfterFork: UsePyOS_AfterFork_Childinstead.PySlice_GetIndicesEx: UsePySlice_UnpackandPySlice_AdjustIndicesinstead.PyUnicode_READY: Unneeded since Python 3.12!PyErr_Display: UsePyErr_DisplayExceptioninstead.!_PyErr_ChainExceptions: Use!_PyErr_ChainExceptions1instead.!PyBytesObject.ob_shashmember: callPyObject_Hashinstead.- Thread Local Storage (TLS) API:
PyThread_create_key: UsePyThread_tss_allocinstead.PyThread_delete_key: UsePyThread_tss_freeinstead.PyThread_set_key_value: UsePyThread_tss_setinstead.PyThread_get_key_value: UsePyThread_tss_getinstead.PyThread_delete_key_value: UsePyThread_tss_deleteinstead.PyThread_ReInitTLS: Unneeded since Python 3.7.
Removed
- Remove the
token.hheader file. There was never any public tokenizer C API. Thetoken.hheader file was only designed to be used by Python internals. (Contributed by Victor Stinner in92651.) - Legacy Unicode APIs have been removed. See
623for detail.!PyUnicode_WCHAR_KIND!PyUnicode_AS_UNICODE!PyUnicode_AsUnicode!PyUnicode_AsUnicodeAndSize!PyUnicode_AS_DATA!PyUnicode_FromUnicode!PyUnicode_GET_SIZE!PyUnicode_GetSize!PyUnicode_GET_DATA_SIZE
- Remove the
PyUnicode_InternImmortal()function macro. (Contributed by Victor Stinner in85858.)
What's New In Python 3.13
Editors
Adam Turner and Thomas Wouters
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the issue number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the VCS log when researching a change.
This article explains the new features in Python 3.13, compared to 3.12. Python 3.13 was released on October 7, 2024. For full details, see the changelog <changelog>.
719 -- Python 3.13 Release Schedule
Summary -- Release Highlights
Python 3.13 is a stable release of the Python programming language, with a mix of changes to the language, the implementation and the standard library. The biggest changes include a new interactive interpreter, experimental support for running in a free-threaded mode (703), and a Just-In-Time compiler (744).
Error messages continue to improve, with tracebacks now highlighted in color by default. The locals builtin now has defined semantics <whatsnew313-locals-semantics> for changing the returned mapping, and type parameters now support default values.
The library changes contain removal of deprecated APIs and modules, as well as the usual improvements in user-friendliness and correctness. Several legacy standard library modules have now been removed following their deprecation in Python 3.11 (594).
This article doesn't attempt to provide a complete specification of all new features, but instead gives a convenient overview. For full details refer to the documentation, such as the Library Reference <library-index> and Language Reference <reference-index>. To understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented. See Porting to Python 3.13 for guidance on upgrading from earlier versions of Python.
Interpreter improvements:
- A greatly improved
interactive interpreter <whatsnew313-better-interactive-interpreter>andimproved error messages <whatsnew313-improved-error-messages>. 667: Thelocalsbuiltin now hasdefined semantics <whatsnew313-locals-semantics>when mutating the returned mapping. Python debuggers and similar tools may now more reliably update local variables in optimized scopes even during concurrent code execution.703: CPython 3.13 has experimental support for running with theglobal interpreter lockdisabled. SeeFree-threaded CPython <whatsnew313-free-threaded-cpython>for more details.744: A basicJIT compiler <whatsnew313-jit-compiler>was added. It is currently disabled by default (though we may turn it on later). Performance improvements are modest -- we expect to improve this over the next few releases.- Color support in the new
interactive interpreter <whatsnew313-better-interactive-interpreter>, as well as intracebacks <whatsnew313-improved-error-messages>anddoctest <whatsnew313-doctest>output. This can be disabled through thePYTHON_COLORSand |NO_COLOR| environment variables.
Python data model improvements:
~type.__static_attributes__stores the names of attributes accessed throughself.Xin any function in a class body.~type.__firstlineno__records the first line number of a class definition.
Significant improvements in the standard library:
- Add a new
PythonFinalizationErrorexception, raised when an operation is blocked duringfinalization <interpreter shutdown>. - The
argparsemodule now supports deprecating command-line options, positional arguments, and subcommands. - The new functions
base64.z85encodeandbase64.z85decodesupport encoding and decoding Z85 data. - The
copymodule now has acopy.replacefunction, with support for many builtin types and any class defining the~object.__replace__method. - The new
dbm.sqlite3module is now the defaultdbmbackend. - The
osmodule has asuite of new functions <os-timerfd>for working with Linux's timer notification file descriptors. - The
randommodule now has acommand-line interface <random-cli>.
Security improvements:
ssl.create_default_contextsetsssl.VERIFY_X509_PARTIAL_CHAINandssl.VERIFY_X509_STRICTas default flags.
C API improvements:
- The
Py_mod_gilslot is now used to indicate that an extension module supports running with theGILdisabled. - The
PyTime C API </c-api/time>has been added, providing access to system clocks. PyMutexis a new lightweight mutex that occupies a single byte.- There is a new
suite of functions <c-api-monitoring>for generating669monitoring events in the C API.
New typing features:
696: Type parameters (typing.TypeVar,typing.ParamSpec, andtyping.TypeVarTuple) now support defaults.702: The newwarnings.deprecateddecorator adds support for marking deprecations in the type system and at runtime.705:typing.ReadOnlycan be used to mark an item of atyping.TypedDictas read-only for type checkers.742:typing.TypeIsprovides more intuitive type narrowing behavior, as an alternative totyping.TypeGuard.
Platform support:
730: Apple's iOS is now anofficially supported platform <whatsnew313-platform-support>, attier 3 <11#tier-3>.738: Android is now anofficially supported platform <whatsnew313-platform-support>, attier 3 <11#tier-3>.wasm32-wasiis now supported as atier 2 <11#tier-2>platform.wasm32-emscriptenis no longer an officially supported platform.
Important removals:
PEP 594 <whatsnew313-pep594>: The remaining 19 "dead batteries" (legacy stdlib modules) have been removed from the standard library:!aifc,!audioop,!cgi,!cgitb,!chunk,!crypt,!imghdr,!mailcap,!msilib,!nis,!nntplib,!ossaudiodev,!pipes,!sndhdr,!spwd,!sunau,!telnetlib,!uuand!xdrlib.- Remove the
2to3tool and!lib2to3module (deprecated in Python 3.11). - Remove the
!tkinter.tixmodule (deprecated in Python 3.6). - Remove the
!locale.resetlocalefunction. - Remove the
!typing.ioand!typing.renamespaces. - Remove chained
classmethoddescriptors.
Release schedule changes:
602 ("Annual Release Cycle for Python") has been updated to extend the full support ('bugfix') period for new releases to two years. This updated policy means that:
- Python 3.9--3.12 have one and a half years of full support, followed by three and a half years of security fixes.
- Python 3.13 and later have two years of full support, followed by three years of security fixes.
New Features
A better interactive interpreter
Python now uses a new interactive shell by default, based on code from the PyPy project. When the user starts the REPL from an interactive terminal, the following new features are now supported:
- Multiline editing with history preservation.
- Direct support for REPL-specific commands like
help,exit, andquit, without the need to call them as functions. - Prompts and tracebacks with
color enabled by default <using-on-controlling-color>. - Interactive help browsing using
F1with a separate command history. - History browsing using
F2that skips output as well as the>>>and...prompts. - "Paste mode" with
F3that makes pasting larger blocks of code easier (pressF3again to return to the regular prompt).
To disable the new interactive shell, set the PYTHON_BASIC_REPL environment variable. For more on interactive mode, see tut-interac.
(Contributed by Pablo Galindo Salgado, Łukasz Langa, and Lysandros Nikolaou in 111201 based on code from the PyPy project. Windows support contributed by Dino Viehland and Anthony Shaw.)
Improved error messages
-
The interpreter now uses color by default when displaying tracebacks in the terminal. This feature
can be controlled <using-on-controlling-color>via the newPYTHON_COLORSenvironment variable as well as the canonical |NO_COLOR| and |FORCE_COLOR| environment variables. (Contributed by Pablo Galindo Salgado in112730.) -
A common mistake is to write a script with the same name as a standard library module. When this results in errors, we now display a more helpful error message:
$ python random.py Traceback (most recent call last): File "/home/me/random.py", line 1, in <module> import random File "/home/me/random.py", line 3, in <module> print(random.randint(5)) ^^^^^^^^^^^^^^ AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/me/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)Similarly, if a script has the same name as a third-party module that it attempts to import and this results in errors, we also display a more helpful error message:
$ python numpy.py Traceback (most recent call last): File "/home/me/numpy.py", line 1, in <module> import numpy as np File "/home/me/numpy.py", line 3, in <module> np.array([1, 2, 3]) ^^^^^^^^ AttributeError: module 'numpy' has no attribute 'array' (consider renaming '/home/me/numpy.py' if it has the same name as a library you intended to import)(Contributed by Shantanu Jain in
95754.) -
The error message now tries to suggest the correct keyword argument when an incorrect keyword argument is passed to a function.
>>> "Better error messages!".split(max_split=1) Traceback (most recent call last): File "<python-input-0>", line 1, in <module> "Better error messages!".split(max_split=1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^ TypeError: split() got an unexpected keyword argument 'max_split'. Did you mean 'maxsplit'?(Contributed by Pablo Galindo Salgado and Shantanu Jain in
107944.)
Free-threaded CPython
CPython now has experimental support for running in a free-threaded mode, with the global interpreter lock (GIL) disabled. This is an experimental feature and therefore is not enabled by default. The free-threaded mode requires a different executable, usually called python3.13t or python3.13t.exe. Pre-built binaries marked as free-threaded can be installed as part of the official Windows <install-freethreaded-windows> and macOS <install-freethreaded-macos> installers, or CPython can be built from source with the --disable-gil option.
Free-threaded execution allows for full utilization of the available processing power by running threads in parallel on available CPU cores. While not all software will benefit from this automatically, programs designed with threading in mind will run faster on multi-core hardware. The free-threaded mode is experimental and work is ongoing to improve it: expect some bugs and a substantial single-threaded performance hit. Free-threaded builds of CPython support optionally running with the GIL enabled at runtime using the environment variable PYTHON_GIL or the command-line option -X gil=1.
To check if the current interpreter supports free-threading, python -VV <-V> and sys.version contain "experimental free-threading build". The new !sys._is_gil_enabled function can be used to check whether the GIL is actually disabled in the running process.
C-API extension modules need to be built specifically for the free-threaded build. Extensions that support running with the GIL disabled should use the Py_mod_gil slot. Extensions using single-phase init should use PyUnstable_Module_SetGIL to indicate whether they support running with the GIL disabled. Importing C extensions that don't use these mechanisms will cause the GIL to be enabled, unless the GIL was explicitly disabled with the PYTHON_GIL environment variable or the -X gil=0 option. pip 24.1 or newer is required to install packages with C extensions in the free-threaded build.
This work was made possible thanks to many individuals and organizations, including the large community of contributors to Python and third-party projects to test and enable free-threading support. Notable contributors include: Sam Gross, Ken Jin, Donghee Na, Itamar Oren, Matt Page, Brett Simmers, Dino Viehland, Carl Meyer, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, and many others. Many of these contributors are employed by Meta, which has provided significant engineering resources to support this project.
703 "Making the Global Interpreter Lock Optional in CPython" contains rationale and information surrounding this work.
Porting Extension Modules to Support Free-Threading: A community-maintained porting guide for extension authors.
An experimental just-in-time (JIT) compiler
When CPython is configured and built using the !--enable-experimental-jit option, a just-in-time (JIT) compiler is added which may speed up some Python programs. On Windows, use PCbuild/build.bat --experimental-jit to enable the JIT or --experimental-jit-interpreter to enable the Tier 2 interpreter. Build requirements and further supporting information are contained at Tools/jit/README.md.
The !--enable-experimental-jit option takes these (optional) values, defaulting to yes if !--enable-experimental-jit is present without the optional value.
no: Disable the entire Tier 2 and JIT pipeline.yes: Enable the JIT. To disable the JIT at runtime, pass the environment variablePYTHON_JIT=0.yes-off: Build the JIT but disable it by default. To enable the JIT at runtime, pass the environment variablePYTHON_JIT=1.interpreter: Enable the Tier 2 interpreter but disable the JIT. The interpreter can be disabled by running withPYTHON_JIT=0.
The internal architecture is roughly as follows:
- We start with specialized Tier 1 bytecode. See
What's new in 3.11 <whatsnew311-pep659>for details. - When the Tier 1 bytecode gets hot enough, it gets translated to a new purely internal intermediate representation (IR), called the Tier 2 IR, and sometimes referred to as micro-ops ("uops").
- The Tier 2 IR uses the same stack-based virtual machine as Tier 1, but the instruction format is better suited to translation to machine code.
- We have several optimization passes for Tier 2 IR, which are applied before it is interpreted or translated to machine code.
- There is a Tier 2 interpreter, but it is mostly intended for debugging the earlier stages of the optimization pipeline. The Tier 2 interpreter can be enabled by configuring Python with
--enable-experimental-jit=interpreter. - When the JIT is enabled, the optimized Tier 2 IR is translated to machine code, which is then executed.
- The machine code translation process uses a technique called copy-and-patch. It has no runtime dependencies, but there is a new build-time dependency on LLVM.
744
(JIT by Brandt Bucher, inspired by a paper by Haoran Xu and Fredrik Kjolstad. Tier 2 IR by Mark Shannon and Guido van Rossum. Tier 2 optimizer by Ken Jin.)
Defined mutation semantics for locals
Historically, the expected result of mutating the return value of locals has been left to individual Python implementations to define. Starting from Python 3.13, 667 standardises the historical behavior of CPython for most code execution scopes, but changes optimized scopes <optimized scope> (functions, generators, coroutines, comprehensions, and generator expressions) to explicitly return independent snapshots of the currently assigned local variables, including locally referenced nonlocal variables captured in closures.
This change to the semantics of locals in optimized scopes also affects the default behavior of code execution functions that implicitly target !locals if no explicit namespace is provided (such as exec and eval). In previous versions, whether or not changes could be accessed by calling !locals after calling the code execution function was implementation-dependent. In CPython specifically, such code would typically appear to work as desired, but could sometimes fail in optimized scopes based on other code (including debuggers and code execution tracing tools) potentially resetting the shared snapshot in that scope. Now, the code will always run against an independent snapshot of the local variables in optimized scopes, and hence the changes will never be visible in subsequent calls to !locals. To access the changes made in these cases, an explicit namespace reference must now be passed to the relevant function. Alternatively, it may make sense to update affected code to use a higher level code execution API that returns the resulting code execution namespace (e.g. runpy.run_path when executing Python files from disk).
To ensure debuggers and similar tools can reliably update local variables in scopes affected by this change, FrameType.f_locals <frame.f_locals> now returns a write-through proxy to the frame's local and locally referenced nonlocal variables in these scopes, rather than returning an inconsistently updated shared dict instance with undefined runtime semantics.
See 667 for more details, including related C API changes and deprecations. Porting notes are also provided below for the affected Python APIs <pep667-porting-notes-py> and C APIs <pep667-porting-notes-c>.
(PEP and implementation contributed by Mark Shannon and Tian Gao in 74929. Documentation updates provided by Guido van Rossum and Alyssa Coghlan.)
Support for mobile platforms
730: iOS is now a 11 supported platform, with the arm64-apple-ios and arm64-apple-ios-simulator targets at tier 3 (iPhone and iPad devices released after 2013 and the Xcode iOS simulator running on Apple silicon hardware, respectively). x86_64-apple-ios-simulator (the Xcode iOS simulator running on older x86_64 hardware) is not a tier 3 supported platform, but will have best-effort support. (PEP written and implementation contributed by Russell Keith-Magee in 114099.)
738: Android is now a 11 supported platform, with the aarch64-linux-android and x86_64-linux-android targets at tier 3. The 32-bit targets arm-linux-androideabi and i686-linux-android are not tier 3 supported platforms, but will have best-effort support. (PEP written and implementation contributed by Malcolm Smith in 116622.)
730, 738
Other Language Changes
-
The compiler now strips common leading whitespace from every line in a docstring. This reduces the size of the
bytecode cache <bytecode>(such as.pycfiles), with reductions in file size of around 5%, for example in!sqlalchemy.orm.sessionfrom SQLAlchemy 2.0. This change affects tools that use docstrings, such asdoctest.>>> def spam(): ... """ ... This is a docstring with ... leading whitespace. ... ... It even has multiple paragraphs! ... """ ... >>> spam.__doc__ 'nThis is a docstring withn leading whitespace.nnIt even has multiple paragraphs!n'
(Contributed by Inada Naoki in
81283.) -
Annotation scopes <annotation-scopes>within class scopes can now contain lambdas and comprehensions. Comprehensions that are located within class scopes are not inlined into their parent scope.class C[T]: type Alias = lambda: T(Contributed by Jelle Zijlstra in
109118and118160.) -
Future statements <future>are no longer triggered by relative imports of the__future__module, meaning that statements of the formfrom .__future__ import ...are now simply standard relative imports, with no special features activated. (Contributed by Jeremiah Gabriel Pascual in118216.) -
globaldeclarations are now permitted inexceptblocks when that global is used in theelseblock. Previously this raised an erroneousSyntaxError. (Contributed by Irit Katriel in111123.) -
Add
PYTHON_FROZEN_MODULES, a new environment variable that determines whether frozen modules are ignored by the import machinery, equivalent to the-X frozen_modules <-X>command-line option. (Contributed by Yilei Yang in111374.) -
Add
support for the perf profiler <perf_profiling>working without frame pointers through the new environment variablePYTHON_PERF_JIT_SUPPORTand command-line option-X perf_jit <-X>. (Contributed by Pablo Galindo in118518.) -
The location of a
.python_historyfile can be changed via the newPYTHON_HISTORYenvironment variable. (Contributed by Levi Sabah, Zackery Spytz and Hugo van Kemenade in73965.) -
Classes have a new
~type.__static_attributes__attribute. This is populated by the compiler with a tuple of the class's attribute names which are assigned throughself.<name>from any function in its body. (Contributed by Irit Katriel in115775.) -
The compiler now creates a
!__firstlineno__attribute on classes with the line number of the first line of the class definition. (Contributed by Serhiy Storchaka in118465.) -
The
execandevalbuiltins now accept the globals and locals arguments as keywords. (Contributed by Raphael Gaschignard in105879) -
The
compilebuiltin now accepts a new flag,ast.PyCF_OPTIMIZED_AST, which is similar toast.PyCF_ONLY_ASTexcept that the returned AST is optimized according to the value of the optimize argument. (Contributed by Irit Katriel in108113). -
Add a
~property.__name__attribute onpropertyobjects. (Contributed by Eugene Toder in101860.) -
Add
PythonFinalizationError, a new exception derived fromRuntimeErrorand used to signal when operations are blocked duringfinalization <interpreter shutdown>. The following callables now raise!PythonFinalizationError, instead ofRuntimeError:_thread.start_new_threados.forkos.forkptysubprocess.Popen
(Contributed by Victor Stinner in
114570.) -
Allow the count argument of
str.replaceto be a keyword. (Contributed by Hugo van Kemenade in106487.) -
Many functions now emit a warning if a boolean value is passed as a file descriptor argument. This can help catch some errors earlier. (Contributed by Serhiy Storchaka in
82626.) -
Added
!nameand!modeattributes for compressed and archived file-like objects in thebz2,lzma,tarfile, andzipfilemodules. (Contributed by Serhiy Storchaka in115961.)
New Modules
dbm.sqlite3: An SQLite backend fordbm. (Contributed by Raymond Hettinger and Erlend E. Aasland in100414.)
Improved Modules
argparse
- Add the deprecated parameter to the
~argparse.ArgumentParser.add_argumentand!add_parsermethods, to enable deprecating command-line options, positional arguments, and subcommands. (Contributed by Serhiy Storchaka in83648.)
array
- Add the
'w'type code (Py_UCS4) for Unicode characters. It should be used instead of the deprecated'u'type code. (Contributed by Inada Naoki in80480.) - Register
array.arrayas a~collections.abc.MutableSequenceby implementing the~array.array.clearmethod. (Contributed by Mike Zimin in114894.)
ast
-
The constructors of node types in the
astmodule are now stricter in the arguments they accept, with more intuitive behavior when arguments are omitted.If an optional field on an AST node is not included as an argument when constructing an instance, the field will now be set to
None. Similarly, if a list field is omitted, that field will now be set to an empty list, and if an!expr_contextfield is omitted, it defaults toLoad() <ast.Load>. (Previously, in all cases, the attribute would be missing on the newly constructed AST node instance.)In all other cases, where a required argument is omitted, the node constructor will emit a
DeprecationWarning. This will raise an exception in Python 3.15. Similarly, passing a keyword argument to the constructor that does not map to a field on the AST node is now deprecated, and will raise an exception in Python 3.15.These changes do not apply to user-defined subclasses of
ast.ASTunless the class opts in to the new behavior by defining the.AST._field_typesmapping.(Contributed by Jelle Zijlstra in
105858,117486, and118851.) -
ast.parsenow accepts an optional argument optimize which is passed on tocompile. This makes it possible to obtain an optimized AST. (Contributed by Irit Katriel in108113.)
asyncio
-
asyncio.as_completednow returns an object that is both anasynchronous iteratorand a plainiteratorofawaitables <awaitable>. The awaitables yielded by asynchronous iteration include original task or future objects that were passed in, making it easier to associate results with the tasks being completed. (Contributed by Justin Arthur in77714.) -
asyncio.loop.create_unix_serverwill now automatically remove the Unix socket when the server is closed. (Contributed by Pierre Ossman in111246.) -
.DatagramTransport.sendtowill now send zero-length datagrams if called with an empty bytes object. The transport flow control also now accounts for the datagram header when calculating the buffer size. (Contributed by Jamie Phan in115199.) -
Add
Queue.shutdown <asyncio.Queue.shutdown>and~asyncio.QueueShutDownto manage queue termination. (Contributed by Laurie Opperman and Yves Duprat in104228.) -
Add the
.Server.close_clientsand.Server.abort_clientsmethods, which more forcefully close an asyncio server. (Contributed by Pierre Ossman in113538.) -
Accept a tuple of separators in
.StreamReader.readuntil, stopping when any one of them is encountered. (Contributed by Bruce Merry in81322.) -
Improve the behavior of
~asyncio.TaskGroupwhen an external cancellation collides with an internal cancellation. For example, when two task groups are nested and both experience an exception in a child task simultaneously, it was possible that the outer task group would hang, because its internal cancellation was swallowed by the inner task group.In the case where a task group is cancelled externally and also must raise an
ExceptionGroup, it will now call the parent task's~asyncio.Task.cancelmethod. This ensures that a~asyncio.CancelledErrorwill be raised at the nextawait, so the cancellation is not lost.An added benefit of these changes is that task groups now preserve the cancellation count (
~asyncio.Task.cancelling).In order to handle some corner cases,
~asyncio.Task.uncancelmay now reset the undocumented_must_cancelflag when the cancellation count reaches zero.(Inspired by an issue reported by Arthur Tacca in
116720.) -
When
.TaskGroup.create_taskis called on an inactive~asyncio.TaskGroup, the given coroutine will be closed (which prevents aRuntimeWarningabout the given coroutine being never awaited). (Contributed by Arthur Tacca and Jason Zhang in115957.) -
The function and methods named
create_taskhave received a new**kwargsargument that is passed through to the task constructor. This change was accidentally added in 3.13.3, and broke the API contract for custom task factories. Several third-party task factories implemented workarounds for this. In 3.13.4 and later releases the old factory contract is honored once again (until 3.14). To keep the workarounds working, the extra**kwargsargument still allows passing additional keyword arguments to~asyncio.Taskand to custom task factories.This affects the following function and methods:
asyncio.create_task,asyncio.loop.create_task,asyncio.TaskGroup.create_task. (Contributed by Thomas Grainger in128307.)
base64
- Add
~base64.z85encodeand~base64.z85decodefunctions for encodingbytesas Z85 data and decoding Z85-encoded data to!bytes. (Contributed by Matan Perelman in75299.)
compileall
- The default number of worker threads and processes is now selected using
os.process_cpu_countinstead ofos.cpu_count. (Contributed by Victor Stinner in109649.)
concurrent.futures
- The default number of worker threads and processes is now selected using
os.process_cpu_countinstead ofos.cpu_count. (Contributed by Victor Stinner in109649.)
configparser
~configparser.ConfigParsernow has support for unnamed sections, which allows for top-level key-value pairs. This can be enabled with the new allow_unnamed_section parameter. (Contributed by Pedro Sousa Lacerda in66449.)
copy
-
The new
~copy.replacefunction and thereplace protocol <object.__replace__>make creating modified copies of objects much simpler. This is especially useful when working with immutable objects. The following types support the~copy.replacefunction and implement the replace protocol:collections.namedtupledataclasses.dataclassdatetime.datetime,datetime.date,datetime.timeinspect.Signature,inspect.Parametertypes.SimpleNamespacecode objects <code-objects>
Any user-defined class can also support
copy.replaceby defining the~object.__replace__method. (Contributed by Serhiy Storchaka in108751.)
ctypes
-
As a consequence of necessary internal refactoring, initialization of internal metaclasses now happens in
__init__rather than in__new__. This affects projects that subclass these internal metaclasses to provide custom initialization. Generally:- Custom logic that was done in
__new__after callingsuper().__new__should be moved to__init__. - To create a class, call the metaclass, not only the metaclass's
__new__method.
See
124520for discussion and links to changes in some affected projects. - Custom logic that was done in
-
ctypes.Structureobjects have a new~ctypes.Structure._align_attribute which allows the alignment of the structure being packed to/from memory to be specified explicitly. (Contributed by Matt Sanderson in112433)
dbm
- Add
dbm.sqlite3, a new module which implements an SQLite backend, and make it the default!dbmbackend. (Contributed by Raymond Hettinger and Erlend E. Aasland in100414.) - Allow removing all items from the database through the new
!clearmethods of the GDBM and NDBM database objects. (Contributed by Donghee Na in107122.)
dis
- Change the output of
dismodule functions to show logical labels for jump targets and exception handlers, rather than offsets. The offsets can be added with the new-O <dis --show-offsets>command-line option or the show_offsets argument. (Contributed by Irit Katriel in112137.) ~dis.get_instructionsno longer represents cache entries as separate instructions. Instead, it returns them as part of the~dis.Instruction, in the new cache_info field. The show_caches argument to~dis.get_instructionsis deprecated and no longer has any effect. (Contributed by Irit Katriel in112962.)
doctest
doctestoutput is now colored by default. This can be controlled via the newPYTHON_COLORSenvironment variable as well as the canonical |NO_COLOR| and |FORCE_COLOR| environment variables. See alsousing-on-controlling-color. (Contributed by Hugo van Kemenade in117225.)- The
.DocTestRunner.runmethod now counts the number of skipped tests. Add the.DocTestRunner.skipsand.TestResults.skippedattributes. (Contributed by Victor Stinner in108794.)
- Headers with embedded newlines are now quoted on output. The
~email.generatorwill now refuse to serialize (write) headers that are improperly folded or delimited, such that they would be parsed as multiple headers or joined with adjacent data. If you need to turn this safety feature off, set~email.policy.Policy.verify_generated_headers. (Contributed by Bas Bloemsaat and Petr Viktorin in121650.) ~email.utils.getaddressesand~email.utils.parseaddrnow return('', '')pairs in more situations where invalid email addresses are encountered instead of potentially inaccurate values. The two functions have a new optional strict parameter (defaultTrue). To get the old behavior (accepting malformed input), usestrict=False.getattr(email.utils, 'supports_strict_parsing', False)can be used to check if the strict parameter is available. (Contributed by Thomas Dwyer and Victor Stinner for102988to improve the2023-27043fix.)
enum
~enum.EnumDicthas been made public to better support subclassing~enum.EnumType.
fractions
~fractions.Fractionobjects now support the standardformat specification mini-language <formatspec>rules for fill, alignment, sign handling, minimum width, and grouping. (Contributed by Mark Dickinson in111320.)
glob
- Add
~glob.translate, a function to convert a path specification with shell-style wildcards to a regular expression. (Contributed by Barney Gale in72904.)
importlib
-
The following functions in
importlib.resourcesnow allow accessing a directory (or tree) of resources, using multiple positional arguments (the encoding and errors arguments in the text-reading functions are now keyword-only):~importlib.resources.is_resource~importlib.resources.open_binary~importlib.resources.open_text~importlib.resources.path~importlib.resources.read_binary~importlib.resources.read_text
These functions are no longer deprecated and are not scheduled for removal. (Contributed by Petr Viktorin in
116608.) -
~importlib.resources.contentsremains deprecated in favor of the fully-featured~importlib.resources.abc.TraversableAPI. However, there is now no plan to remove it. (Contributed by Petr Viktorin in116608.)
io
- The
~io.IOBasefinalizer now logs any errors raised by the~io.IOBase.closemethod withsys.unraisablehook. Previously, errors were ignored silently by default, and only logged inPython Development Mode <devmode>or when using aPython debug build <debug-build>. (Contributed by Victor Stinner in62948.)
ipaddress
- Add the
.IPv4Address.ipv6_mappedproperty, which returns the IPv4-mapped IPv6 address. (Contributed by Charles Machalow in109466.) - Fix
is_globalandis_privatebehavior in~ipaddress.IPv4Address,~ipaddress.IPv6Address,~ipaddress.IPv4Network, and~ipaddress.IPv6Network. (Contributed by Jakub Stasiak in113171.)
itertools
~itertools.batchedhas a new strict parameter, which raises aValueErrorif the final batch is shorter than the specified batch size. (Contributed by Raymond Hettinger in113202.)
marshal
- Add the allow_code parameter in module functions. Passing
allow_code=Falseprevents serialization and de-serialization of code objects which are incompatible between Python versions. (Contributed by Serhiy Storchaka in113626.)
math
- The new function
~math.fmaperforms fused multiply-add operations. This computesx * y + zwith only a single round, and so avoids any intermediate loss of precision. It wraps thefma()function provided by C99, and follows the specification of the IEEE 754 "fusedMultiplyAdd" operation for special cases. (Contributed by Mark Dickinson and Victor Stinner in73468.)
mimetypes
- Add the
~mimetypes.guess_file_typefunction to guess a MIME type from a filesystem path. Using paths with~mimetypes.guess_typeis nowsoft deprecated. (Contributed by Serhiy Storchaka in66543.)
mmap
~mmap.mmapis now protected from crashing on Windows when the mapped memory is inaccessible due to file system errors or access violations. (Contributed by Jannis Weigend in118209.)~mmap.mmaphas a new~mmap.mmap.seekablemethod that can be used when a seekable file-like object is required. The~mmap.mmap.seekmethod now returns the new absolute position. (Contributed by Donghee Na and Sylvie Liberman in111835.)- The new UNIX-only trackfd parameter for
~mmap.mmapcontrols file descriptor duplication; if false, the file descriptor specified by fileno will not be duplicated. (Contributed by Zackery Spytz and Petr Viktorin in78502.)
multiprocessing
- The default number of worker threads and processes is now selected using
os.process_cpu_countinstead ofos.cpu_count. (Contributed by Victor Stinner in109649.)
os
- Add
~os.process_cpu_countfunction to get the number of logical CPU cores usable by the calling thread of the current process. (Contributed by Victor Stinner in109649.) ~os.cpu_countand~os.process_cpu_countcan be overridden through the new environment variablePYTHON_CPU_COUNTor the new command-line option-X cpu_count <-X>. This option is useful for users who need to limit CPU resources of a container system without having to modify application code or the container itself. (Contributed by Donghee Na in109595.)- Add a
low level interface <os-timerfd>to Linux'stimer file descriptors <timerfd_create(2)>via~os.timerfd_create,~os.timerfd_settime,~os.timerfd_settime_ns,~os.timerfd_gettime,~os.timerfd_gettime_ns,~os.TFD_NONBLOCK,~os.TFD_CLOEXEC,~os.TFD_TIMER_ABSTIME, and~os.TFD_TIMER_CANCEL_ON_SET(Contributed by Masaru Tsuchiyama in108277.) ~os.lchmodand the follow_symlinks argument of~os.chmodare both now available on Windows. Note that the default value of follow_symlinks in!lchmodisFalseon Windows. (Contributed by Serhiy Storchaka in59616.)~os.fchmodand support for file descriptors in~os.chmodare both now available on Windows. (Contributed by Serhiy Storchaka in113191.)- On Windows,
~os.mkdirand~os.makedirsnow support passing a mode value of0o700to apply access control to the new directory. This implicitly affectstempfile.mkdtempand is a mitigation for2024-4030. Other values for mode continue to be ignored. (Contributed by Steve Dower in118486.) ~os.posix_spawnnow acceptsNonefor the env argument, which makes the newly spawned process use the current process environment. (Contributed by Jakub Kulik in113119.)~os.posix_spawncan now use the~os.POSIX_SPAWN_CLOSEFROMattribute in the file_actions parameter on platforms that support!posix_spawn_file_actions_addclosefrom_np. (Contributed by Jakub Kulik in113117.)
os.path
- Add
~os.path.isreservedto check if a path is reserved on the current system. This function is only available on Windows. (Contributed by Barney Gale in88569.) - On Windows,
~os.path.isabsno longer considers paths starting with exactly one slash (\or/) to be absolute. (Contributed by Barney Gale and Jon Foster in44626.) ~os.path.realpathnow resolves MS-DOS style file names even if the file is not accessible. (Contributed by Moonsik Park in82367.)
pathlib
- Add
~pathlib.UnsupportedOperation, which is raised instead ofNotImplementedErrorwhen a path operation isn't supported. (Contributed by Barney Gale in89812.) - Add a new constructor for creating
~pathlib.Pathobjects from 'file' URIs (file:///),.Path.from_uri. (Contributed by Barney Gale in107465.) - Add
.PurePath.full_matchfor matching paths with shell-style wildcards, including the recursive wildcard "**". (Contributed by Barney Gale in73435.) - Add the
.PurePath.parserclass attribute to store the implementation ofos.pathused for low-level path parsing and joining. This will be either!posixpathor!ntpath. - Add recurse_symlinks keyword-only argument to
.Path.globand~pathlib.Path.rglob. (Contributed by Barney Gale in77609.) .Path.globand~pathlib.Path.rglobnow return files and directories when given a pattern that ends with "**". Previously, only directories were returned. (Contributed by Barney Gale in70303.)- Add the follow_symlinks keyword-only argument to
Path.is_file <pathlib.Path.is_file>,Path.is_dir <pathlib.Path.is_dir>,.Path.owner, and.Path.group. (Contributed by Barney Gale in105793and Kamil Turek in107962.)
pdb
breakpointand~pdb.set_tracenow enter the debugger immediately rather than on the next line of code to be executed. This change prevents the debugger from breaking outside of the context when!breakpointis positioned at the end of the context. (Contributed by Tian Gao in118579.)sys.path[0]is no longer replaced by the directory of the script being debugged whensys.flags.safe_pathis set. (Contributed by Tian Gao and Christian Walther in111762.)zipappis now supported as a debugging target. (Contributed by Tian Gao in118501.)- Add ability to move between chained exceptions during post-mortem debugging in
~pdb.pmusing the newexceptions [exc_number] <exceptions>command for Pdb. (Contributed by Matthias Bussonnier in106676.) - Expressions and statements whose prefix is a pdb command are now correctly identified and executed. (Contributed by Tian Gao in
108464.)
queue
- Add
Queue.shutdown <queue.Queue.shutdown>and~queue.ShutDownto manage queue termination. (Contributed by Laurie Opperman and Yves Duprat in104750.)
random
- Add a
command-line interface <random-cli>. (Contributed by Hugo van Kemenade in118131.)
re
- Rename
!re.errorto~re.PatternErrorfor improved clarity.!re.erroris kept for backward compatibility.
shutil
- Support the dir_fd and follow_symlinks keyword arguments in
~shutil.chown. (Contributed by Berker Peksag and Tahia K in62308)
site
.pthfiles are now decoded using UTF-8 first, and then with thelocale encodingif UTF-8 decoding fails. (Contributed by Inada Naoki in117802.)
sqlite3
- A
ResourceWarningis now emitted if a~sqlite3.Connectionobject is notclosed <sqlite3.Connection.close>explicitly. (Contributed by Erlend E. Aasland in105539.) - Add the filter keyword-only parameter to
.Connection.iterdumpfor filtering database objects to dump. (Contributed by Mariusz Felisiak in91602.)
ssl
-
The
~ssl.create_default_contextAPI now includes~ssl.VERIFY_X509_PARTIAL_CHAINand~ssl.VERIFY_X509_STRICTin its default flags.[!NOTE]
~ssl.VERIFY_X509_STRICTmay reject pre-5280or malformed certificates that the underlying OpenSSL implementation might otherwise accept. Whilst disabling this is not recommended, you can do so using:import ssl ctx = ssl.create_default_context() ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT(Contributed by William Woodruff in
112389.)
statistics
- Add
~statistics.kdefor kernel density estimation. This makes it possible to estimate a continuous probability density function from a fixed number of discrete samples. (Contributed by Raymond Hettinger in115863.) - Add
~statistics.kde_randomfor sampling from an estimated probability density function created by~statistics.kde. (Contributed by Raymond Hettinger in115863.)
subprocess
-
The
subprocessmodule now uses the~os.posix_spawnfunction in more situations.Notably, when close_fds is
True(the default),~os.posix_spawnwill be used when the C library provides!posix_spawn_file_actions_addclosefrom_np, which includes recent versions of Linux, FreeBSD, and Solaris. On Linux, this should perform similarly to the existing Linux!vforkbased code.A private control knob
!subprocess._USE_POSIX_SPAWNcan be set toFalseif you need to forcesubprocessto never use~os.posix_spawn. Please report your reason and platform details in theissue tracker <using-the-tracker>if you set this so that we can improve our API selection logic for everyone. (Contributed by Jakub Kulik in113117.)
sys
- Add the
~sys._is_internedfunction to test if a string was interned. This function is not guaranteed to exist in all implementations of Python. (Contributed by Serhiy Storchaka in78573.)
tempfile
- On Windows, the default mode
0o700used bytempfile.mkdtempnow limits access to the new directory due to changes toos.mkdir. This is a mitigation for2024-4030. (Contributed by Steve Dower in118486.)
time
- On Windows,
~time.monotonicnow uses theQueryPerformanceCounter()clock for a resolution of 1 microsecond, instead of theGetTickCount64()clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in88494.) - On Windows,
~time.timenow uses theGetSystemTimePreciseAsFileTime()clock for a resolution of 1 microsecond, instead of theGetSystemTimeAsFileTime()clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in63207.)
tkinter
- Add
tkinterwidget methods:!tk_busy_hold,!tk_busy_configure,!tk_busy_cget,!tk_busy_forget,!tk_busy_current, and!tk_busy_status. (Contributed by Miguel, klappnase and Serhiy Storchaka in72684.) - The
tkinterwidget method!wm_attributesnow accepts the attribute name without the minus prefix to get window attributes, for examplew.wm_attributes('alpha')and allows specifying attributes and values to set as keyword arguments, for examplew.wm_attributes(alpha=0.5). (Contributed by Serhiy Storchaka in43457.) !wm_attributescan now return attributes as adict, by using the new optional keyword-only parameter return_python_dict. (Contributed by Serhiy Storchaka in43457.)!Text.countcan now return a simpleintwhen the new optional keyword-only parameter return_ints is used. Otherwise, the single count is returned as a 1-tuple orNone. (Contributed by Serhiy Storchaka in97928.)- Support the "vsapi" element type in the
~tkinter.ttk.Style.element_createmethod oftkinter.ttk.Style. (Contributed by Serhiy Storchaka in68166.) - Add the
!after_infomethod for Tkinter widgets. (Contributed by Cheryl Sabella in77020.) - Add a new
!copy_replacemethod to!PhotoImageto copy a region from one image to another, possibly with pixel zooming, subsampling, or both. (Contributed by Serhiy Storchaka in118225.) - Add from_coords parameter to the
!PhotoImagemethods!copy,!zoomand!subsample. Add zoom and subsample parameters to the!PhotoImagemethod!copy. (Contributed by Serhiy Storchaka in118225.) - Add the
!PhotoImagemethods!readto read an image from a file and!datato get the image data. Add background and grayscale parameters to the!writemethod. (Contributed by Serhiy Storchaka in118271.)
traceback
- Add the
~traceback.TracebackException.exc_type_strattribute to~traceback.TracebackException, which holds a string display of the exc_type. Deprecate the~traceback.TracebackException.exc_typeattribute, which holds the type object itself. Add parameter save_exc_type (defaultTrue) to indicate whetherexc_typeshould be saved. (Contributed by Irit Katriel in112332.) - Add a new show_group keyword-only parameter to
.TracebackException.format_exception_onlyto (recursively) format the nested exceptions of aBaseExceptionGroupinstance. (Contributed by Irit Katriel in105292.)
types
~types.SimpleNamespacecan now take a single positional argument to initialise the namespace's arguments. This argument must either be a mapping or an iterable of key-value pairs. (Contributed by Serhiy Storchaka in108191.)
typing
705: Add~typing.ReadOnly, a special typing construct to mark a~typing.TypedDictitem as read-only for type checkers.742: Add~typing.TypeIs, a typing construct that can be used to instruct a type checker how to narrow a type.- Add
~typing.NoDefault, a sentinel object used to represent the defaults of some parameters in thetypingmodule. (Contributed by Jelle Zijlstra in116126.) - Add
~typing.get_protocol_membersto return the set of members defining atyping.Protocol. (Contributed by Jelle Zijlstra in104873.) - Add
~typing.is_protocolto check whether a class is a~typing.Protocol. (Contributed by Jelle Zijlstra in104873.) ~typing.ClassVarcan now be nested in~typing.Final, and vice versa. (Contributed by Mehdi Drissi in89547.)
unicodedata
- Update the Unicode database to version 15.1.0. (Contributed by James Gerity in
109559.)
venv
- Add support for creating source control management (SCM) ignore files in a virtual environment's directory. By default, Git is supported. This is implemented as opt-in via the API, which can be extended to support other SCMs (
~venv.EnvBuilderand~venv.create), and opt-out via the CLI, using!--without-scm-ignore-files. (Contributed by Brett Cannon in108125.)
warnings
702: The newwarnings.deprecateddecorator provides a way to communicate deprecations to astatic type checkerand to warn on usage of deprecated classes and functions. ADeprecationWarningmay also be emitted when a decorated function or class is used at runtime. (Contributed by Jelle Zijlstra in104003.)
xml
-
Allow controlling Expat >=2.6.0 reparse deferral (
2023-52425) by adding five new methods:xml.etree.ElementTree.XMLParser.flushxml.etree.ElementTree.XMLPullParser.flushxml.parsers.expat.xmlparser.GetReparseDeferralEnabledxml.parsers.expat.xmlparser.SetReparseDeferralEnabled!xml.sax.expatreader.ExpatParser.flush
(Contributed by Sebastian Pipping in
115623.) -
Add the
!closemethod for the iterator returned by~xml.etree.ElementTree.iterparsefor explicit cleanup. (Contributed by Serhiy Storchaka in69893.)
zipimport
- Add support for ZIP64 format files. Everybody loves huge data, right? (Contributed by Tim Hatch in
94146.)
Optimizations
- Several standard library modules have had their import times significantly improved. For example, the import time of the
typingmodule has been reduced by around a third by removing dependencies onreandcontextlib. Other modules to enjoy import-time speedups includeemail.utils,enum,functools,importlib.metadata, andthreading. (Contributed by Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas, and others in109653.) textwrap.indentis now around 30% faster than before for large input. (Contributed by Inada Naoki in107369.)- The
subprocessmodule now uses the~os.posix_spawnfunction in more situations, including when close_fds isTrue(the default) on many modern platforms. This should provide a notable performance increase when launching processes on FreeBSD and Solaris. See thesubprocess <whatsnew313-subprocess>section above for details. (Contributed by Jakub Kulik in113117.)
Removed Modules And APIs
PEP 594: Remove "dead batteries" from the standard library
594 proposed removing 19 modules from the standard library, colloquially referred to as 'dead batteries' due to their historic, obsolete, or insecure status. All of the following modules were deprecated in Python 3.11, and are now removed:
!aifcstandard-aifc: Use the redistribution ofaifclibrary from PyPI.
!audioopaudioop-lts: Useaudioop-ltslibrary from PyPI.
!chunkstandard-chunk: Use the redistribution ofchunklibrary from PyPI.
!cgiand!cgitb-
!cgi.FieldStoragecan typically be replaced withurllib.parse.parse_qslforGETandHEADrequests, and theemail.messagemodule or themultipartlibrary forPOSTandPUTrequests. -
!cgi.parsecan be replaced by callingurllib.parse.parse_qsdirectly on the desired query string, unless the input ismultipart/form-data, which should be replaced as described below for!cgi.parse_multipart. -
!cgi.parse_headercan be replaced with the functionality in theemailpackage, which implements the same MIME RFCs. For example, withemail.message.EmailMessage:from email.message import EmailMessage msg = EmailMessage() msg['content-type'] = 'application/json; charset="utf8"' main, params = msg.get_content_type(), msg['content-type'].params -
!cgi.parse_multipartcan be replaced with the functionality in theemailpackage, which implements the same MIME RFCs, or with themultipartlibrary. For example, theemail.message.EmailMessageandemail.message.Messageclasses. -
standard-cgi: andstandard-cgitb: Use the redistribution ofcgiandcgitblibrary from PyPI.
-
!cryptand the private!_cryptextension. Thehashlibmodule may be an appropriate replacement when simply hashing a value is required. Otherwise, various third-party libraries on PyPI are available:bcrypt: Modern password hashing for your software and your servers.argon2-cffi: The secure Argon2 password hashing algorithm.legacycrypt:ctypeswrapper to the POSIX crypt library call and associated functionality.crypt_r: Fork of the!cryptmodule, wrapper to thecrypt_r(3)library call and associated functionality.standard-cryptanddeprecated-crypt-alternative: Use the redistribution ofcryptand reimplementation of_cryptlibraries from PyPI.
!imghdr: Thefiletype,puremagic, orpython-magiclibraries should be used as replacements. For example, the!puremagic.whatfunction can be used to replace the!imghdr.whatfunction for all file formats that were supported by!imghdr.standard-imghdr: Use the redistribution ofimghdrlibrary from PyPI.
!mailcap: Use themimetypesmodule instead.standard-mailcap: Use the redistribution ofmailcaplibrary from PyPI.
!msilib!nis!nntplib: Use thepynntplibrary from PyPI instead.standard-nntplib: Use the redistribution ofnntpliblibrary from PyPI.
!ossaudiodev: For audio playback, use thepygamelibrary from PyPI instead.!pipes: Use thesubprocessmodule instead. Useshlex.quoteto replace the undocumentedpipes.quotefunction.standard-pipes: Use the redistribution ofpipeslibrary from PyPI.
!sndhdr: Thefiletype,puremagic, orpython-magiclibraries should be used as replacements.standard-sndhdr: Use the redistribution ofsndhdrlibrary from PyPI.
!spwd: Use thepython-pamlibrary from PyPI instead.!sunaustandard-sunau: Use the redistribution ofsunaulibrary from PyPI.
!telnetlib, Use thetelnetlib3orExscriptlibraries from PyPI instead.standard-telnetlib: Use the redistribution oftelnetliblibrary from PyPI.
!uu: Use thebase64module instead, as a modern alternative.standard-uu: Use the redistribution ofuulibrary from PyPI.
!xdrlibstandard-xdrlib: Use the redistribution ofxdrliblibrary from PyPI.
(Contributed by Victor Stinner and Zachary Ware in 104773 and 104780.)
2to3
- Remove the
2to3program and the!lib2to3module, previously deprecated in Python 3.11. (Contributed by Victor Stinner in104780.)
builtins
- Remove support for chained
classmethoddescriptors (introduced in63272). These can no longer be used to wrap other descriptors, such asproperty. The core design of this feature was flawed and led to several problems. To "pass-through" aclassmethod, consider using the!__wrapped__attribute that was added in Python 3.10. (Contributed by Raymond Hettinger in89519.) - Raise a
RuntimeErrorwhen callingframe.clearon a suspended frame (as has always been the case for an executing frame). (Contributed by Irit Katriel in79932.)
configparser
- Remove the undocumented
!LegacyInterpolationclass, deprecated in the docstring since Python 3.2, and at runtime since Python 3.11. (Contributed by Hugo van Kemenade in104886.)
importlib.metadata
- Remove deprecated subscript (
~object.__getitem__) access forEntryPoint <entry-points>objects. (Contributed by Jason R. Coombs in113175.)
locale
- Remove the
!locale.resetlocalefunction, deprecated in Python 3.11. Uselocale.setlocale(locale.LC_ALL, "")instead. (Contributed by Victor Stinner in104783.)
opcode
- Move
!opcode.ENABLE_SPECIALIZATIONto!_opcode.ENABLE_SPECIALIZATION. This field was added in 3.12, it was never documented, and is not intended for external use. (Contributed by Irit Katriel in105481.) - Remove
!opcode.is_pseudo,!opcode.MIN_PSEUDO_OPCODE, and!opcode.MAX_PSEUDO_OPCODE, which were added in Python 3.12, but were neither documented nor exposed throughdis, and were not intended to be used externally. (Contributed by Irit Katriel in105481.)
optparse
- This module is no longer considered
soft deprecated. Whileargparseremains preferred for new projects that aren't using a third party command line argument processing library, there are aspects of the wayargparseworks that mean the lower leveloptparsemodule may provide a better foundation for writing argument processing libraries, and for implementing command line applications which adhere more strictly thanargparsedoes to various Unix command line processing conventions that originate in the behaviour of the C!getoptfunction . (Contributed by Alyssa Coghlan and Serhiy Storchaka in126180.)
pathlib
- Remove the ability to use
~pathlib.Pathobjects as context managers. This functionality was deprecated and has had no effect since Python 3.9. (Contributed by Barney Gale in83863.)
re
- Remove the undocumented, deprecated, and broken
!re.templatefunction and!re.TEMPLATE/!re.Tflag. (Contributed by Serhiy Storchaka and Nikita Sobolev in105687.)
tkinter.tix
- Remove the
!tkinter.tixmodule, deprecated in Python 3.6. The third-party Tix library which the module wrapped is unmaintained. (Contributed by Zachary Ware in75552.)
turtle
- Remove the
!RawTurtle.settiltanglemethod, deprecated in the documentation since Python 3.1 and at runtime since Python 3.11. (Contributed by Hugo van Kemenade in104876.)
typing
- Remove the
!typing.ioand!typing.renamespaces, deprecated since Python 3.8. The items in those namespaces can be imported directly from thetypingmodule. (Contributed by Sebastian Rittau in92871.) - Remove the keyword-argument method of creating
~typing.TypedDicttypes, deprecated in Python 3.11. (Contributed by Tomas Roun in104786.)
unittest
-
Remove the following
unittestfunctions, deprecated in Python 3.11:!unittest.findTestCases!unittest.makeSuite!unittest.getTestCaseNames
Use
~unittest.TestLoadermethods instead:~unittest.TestLoader.loadTestsFromModule~unittest.TestLoader.loadTestsFromTestCase~unittest.TestLoader.getTestCaseNames
(Contributed by Hugo van Kemenade in
104835.) -
Remove the untested and undocumented
!TestProgram.usageExitmethod, deprecated in Python 3.11. (Contributed by Hugo van Kemenade in104992.)
urllib
- Remove the cafile, capath, and cadefault parameters of the
urllib.request.urlopenfunction, deprecated in Python 3.6. Use the context parameter instead with an~ssl.SSLContextinstance. Thessl.SSLContext.load_verify_locationsmethod can be used to load specific CA certificates, or letssl.create_default_contextselect the operating system's trusted certificate authority (CA) certificates. (Contributed by Victor Stinner in105382.)
webbrowser
- Remove the untested and undocumented
!MacOSXclass, deprecated in Python 3.11. Use the!MacOSXOSAScriptclass (introduced in Python 3.2) instead. (Contributed by Hugo van Kemenade in104804.) - Remove the deprecated
!MacOSXOSAScript._nameattribute. Use theMacOSXOSAScript.name <webbrowser.controller.name>attribute instead. (Contributed by Nikita Sobolev in105546.)
New Deprecations
User-defined functions <user-defined-funcs>:- Deprecate assignment to a function's
~function.__code__attribute, where the new code object's type does not match the function's type. The different types are: plain function, generator, async generator, and coroutine. (Contributed by Irit Katriel in81137.)
- Deprecate assignment to a function's
array:- Deprecate the
'u'format code (wchar_t) at runtime. This format code has been deprecated in documentation since Python 3.3, and will be removed in Python 3.16. Use the'w'format code (Py_UCS4) for Unicode characters instead. (Contributed by Hugo van Kemenade in80480.)
- Deprecate the
ctypes:- Deprecate the undocumented
!SetPointerTypefunction, to be removed in Python 3.15. (Contributed by Victor Stinner in105733.) Soft-deprecate <soft deprecated>the~ctypes.ARRAYfunction in favour oftype * lengthmultiplication. (Contributed by Victor Stinner in105733.)
- Deprecate the undocumented
decimal:- Deprecate the non-standard and undocumented
~decimal.Decimalformat specifier'N', which is only supported in the!decimalmodule's C implementation. Scheduled to be removed in Python 3.18. (Contributed by Serhiy Storchaka in89902.)
- Deprecate the non-standard and undocumented
dis:- Deprecate the
!HAVE_ARGUMENTseparator. Check membership in~dis.hasarginstead. (Contributed by Irit Katriel in109319.)
- Deprecate the
gettext:- Deprecate non-integer numbers as arguments to functions and methods that consider plural forms in the
!gettextmodule, even if no translation was found. (Contributed by Serhiy Storchaka in88434.)
- Deprecate non-integer numbers as arguments to functions and methods that consider plural forms in the
glob:- Deprecate the undocumented
!glob0and!glob1functions. Use~glob.globand pass apath-like objectspecifying the root directory to the root_dir parameter instead. (Contributed by Barney Gale in117337.)
- Deprecate the undocumented
http.server:- Deprecate
!CGIHTTPRequestHandler, to be removed in Python 3.15. Process-based CGI HTTP servers have been out of favor for a very long time. This code was outdated, unmaintained, and rarely used. It has a high potential for both security and functionality bugs. (Contributed by Gregory P. Smith in109096.) - Deprecate the
!--cgiflag to thepython -m http.servercommand-line interface, to be removed in Python 3.15. (Contributed by Gregory P. Smith in109096.)
- Deprecate
mimetypes:Soft-deprecate <soft deprecated>file path arguments to~mimetypes.guess_type, use~mimetypes.guess_file_typeinstead. (Contributed by Serhiy Storchaka in66543.)
re:- Deprecate passing the optional maxsplit, count, or flags arguments as positional arguments to the module-level
~re.split,~re.sub, and~re.subnfunctions. These parameters will becomekeyword-only <keyword-only_parameter>in a future version of Python. (Contributed by Serhiy Storchaka in56166.)
- Deprecate passing the optional maxsplit, count, or flags arguments as positional arguments to the module-level
pathlib:- Deprecate
!.PurePath.is_reserved, to be removed in Python 3.15. Useos.path.isreservedto detect reserved paths on Windows. (Contributed by Barney Gale in88569.)
- Deprecate
platform:- Deprecate
!platform.java_ver, to be removed in Python 3.15. This function is only useful for Jython support, has a confusing API, and is largely untested. (Contributed by Nikita Sobolev in116349.)
- Deprecate
pydoc:- Deprecate the undocumented
!ispackagefunction. (Contributed by Zackery Spytz in64020.)
- Deprecate the undocumented
sqlite3:- Deprecate passing more than one positional argument to the
~sqlite3.connectfunction and the~sqlite3.Connectionconstructor. The remaining parameters will become keyword-only in Python 3.15. (Contributed by Erlend E. Aasland in107948.) - Deprecate passing name, number of arguments, and the callable as keyword arguments for
.Connection.create_functionand.Connection.create_aggregateThese parameters will become positional-only in Python 3.15. (Contributed by Erlend E. Aasland in108278.) - Deprecate passing the callback callable by keyword for the
~sqlite3.Connection.set_authorizer,~sqlite3.Connection.set_progress_handler, and~sqlite3.Connection.set_trace_callback~sqlite3.Connectionmethods. The callback callables will become positional-only in Python 3.15. (Contributed by Erlend E. Aasland in108278.)
- Deprecate passing more than one positional argument to the
sys:- Deprecate the
!_enablelegacywindowsfsencodingfunction, to be removed in Python 3.16. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead. (Contributed by Inada Naoki in73427.)
- Deprecate the
tarfile:- Deprecate the undocumented and unused
!TarInfo.tarfileattribute, to be removed in Python 3.16. (Contributed in115256.)
- Deprecate the undocumented and unused
traceback:- Deprecate the
.TracebackException.exc_typeattribute. Use.TracebackException.exc_type_strinstead. (Contributed by Irit Katriel in112332.)
- Deprecate the
typing:- Deprecate the undocumented keyword argument syntax for creating
~typing.NamedTupleclasses (e.g.Point = NamedTuple("Point", x=int, y=int)), to be removed in Python 3.15. Use the class-based syntax or the functional syntax instead. (Contributed by Alex Waygood in105566.) - Deprecate omitting the fields parameter when creating a
~typing.NamedTupleortyping.TypedDictclass, and deprecate passingNoneto the fields parameter of both types. Python 3.15 will require a valid sequence for the fields parameter. To create a NamedTuple class with zero fields, useclass NT(NamedTuple): passorNT = NamedTuple("NT", ()). To create a TypedDict class with zero fields, useclass TD(TypedDict): passorTD = TypedDict("TD", {}). (Contributed by Alex Waygood in105566and105570.) - Deprecate the
!typing.no_type_check_decoratordecorator function, to be removed in Python 3.15. After eight years in thetypingmodule, it has yet to be supported by any major type checker. (Contributed by Alex Waygood in106309.) - Deprecate
typing.AnyStr. In Python 3.16, it will be removed fromtyping.__all__, and aDeprecationWarningwill be emitted at runtime when it is imported or accessed. It will be removed entirely in Python 3.18. Use the newtype parameter syntax <type-params>instead. (Contributed by Michael The in107116.)
- Deprecate the undocumented keyword argument syntax for creating
wave:- Deprecate the
getmark(),setmark()andgetmarkers()methods of the~wave.Wave_readand~wave.Wave_writeclasses, to be removed in Python 3.15. (Contributed by Victor Stinner in105096.)
- Deprecate the
Pending removal in Python 3.14
-
argparse: The type, choices, and metavar parameters of!argparse.BooleanOptionalActionare deprecated and will be removed in 3.14. (Contributed by Nikita Sobolev in92248.) -
ast: The following features have been deprecated in documentation since Python 3.8, now cause aDeprecationWarningto be emitted at runtime when they are accessed or used, and will be removed in Python 3.14:!ast.Num!ast.Str!ast.Bytes!ast.NameConstant!ast.Ellipsis
Use
ast.Constantinstead. (Contributed by Serhiy Storchaka in90953.) -
asyncio:- The child watcher classes
!asyncio.MultiLoopChildWatcher,!asyncio.FastChildWatcher,!asyncio.AbstractChildWatcherand!asyncio.SafeChildWatcherare deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in94597.) !asyncio.set_child_watcher,!asyncio.get_child_watcher,!asyncio.AbstractEventLoopPolicy.set_child_watcherand!asyncio.AbstractEventLoopPolicy.get_child_watcherare deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in94597.)- The
~asyncio.get_event_loopmethod of the default event loop policy now emits aDeprecationWarningif there is no current event loop set and it decides to create one. (Contributed by Serhiy Storchaka and Guido van Rossum in100160.)
- The child watcher classes
-
email: Deprecated the isdst parameter inemail.utils.localtime. (Contributed by Alan Williams in72346.) -
importlib.abcdeprecated classes:!importlib.abc.ResourceReader!importlib.abc.Traversable!importlib.abc.TraversableResources
Use
importlib.resources.abcclasses instead:importlib.resources.abc.Traversableimportlib.resources.abc.TraversableResources
(Contributed by Jason R. Coombs and Hugo van Kemenade in
93963.) -
itertoolshad undocumented, inefficient, historically buggy, and inconsistent support for copy, deepcopy, and pickle operations. This will be removed in 3.14 for a significant reduction in code volume and maintenance burden. (Contributed by Raymond Hettinger in101588.) -
multiprocessing: The default start method will change to a safer one on Linux, BSDs, and other non-macOS POSIX platforms where'fork'is currently the default (84559). Adding a runtime warning about this was deemed too disruptive as the majority of code is not expected to care. Use the~multiprocessing.get_contextor~multiprocessing.set_start_methodAPIs to explicitly specify when your code requires'fork'. Seemultiprocessing-start-methods. -
pathlib:~pathlib.PurePath.is_relative_toand~pathlib.PurePath.relative_to: passing additional arguments is deprecated. -
pkgutil:!pkgutil.find_loaderand!pkgutil.get_loadernow raiseDeprecationWarning; useimportlib.util.find_specinstead. (Contributed by Nikita Sobolev in97850.) -
pty:master_open(): usepty.openpty.slave_open(): usepty.openpty.
-
sqlite3:!versionand!version_info.~sqlite3.Cursor.executeand~sqlite3.Cursor.executemanyifnamed placeholders <sqlite3-placeholders>are used and parameters is a sequence instead of adict.
-
urllib:!urllib.parse.Quoteris deprecated: it was not intended to be a public API. (Contributed by Gregory P. Smith in88168.)
Pending removal in Python 3.15
- The import system:
- Setting
__cached__on a module while failing to set__spec__.cached <importlib.machinery.ModuleSpec.cached>is deprecated. In Python 3.15,__cached__will cease to be set or take into consideration by the import system or standard library. (97879)
- Setting
ctypes:- The undocumented
!ctypes.SetPointerTypefunction has been deprecated since Python 3.13.
- The undocumented
http.server:- The obsolete and rarely used
!CGIHTTPRequestHandlerhas been deprecated since Python 3.13. No direct replacement exists. Anything is better than CGI to interface a web server with a request handler. - The
!--cgiflag to thepython -m http.servercommand-line interface has been deprecated since Python 3.13.
- The obsolete and rarely used
importlib:load_module()method: useexec_module()instead.
pathlib:!.PurePath.is_reservedhas been deprecated since Python 3.13. Useos.path.isreservedto detect reserved paths on Windows.
platform:!platform.java_verhas been deprecated since Python 3.13. This function is only useful for Jython support, has a confusing API, and is largely untested.
sysconfig:- The check_home argument of
sysconfig.is_python_buildhas been deprecated since Python 3.12.
- The check_home argument of
threading:~threading.RLockwill take no arguments in Python 3.15. Passing any arguments has been deprecated since Python 3.14, as the Python version does not permit any arguments, but the C version allows any number of positional or keyword arguments, ignoring every argument.
types:types.CodeType: Accessing!codeobject.co_lnotabwas deprecated in626since 3.10 and was planned to be removed in 3.12, but it only got a properDeprecationWarningin 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in101866.)
typing:- The undocumented keyword argument syntax for creating
~typing.NamedTupleclasses (for example,Point = NamedTuple("Point", x=int, y=int)) has been deprecated since Python 3.13. Use the class-based syntax or the functional syntax instead. - When using the functional syntax of
~typing.TypedDicts, failing to pass a value to the fields parameter (TD = TypedDict("TD")) or passingNone(TD = TypedDict("TD", None)) has been deprecated since Python 3.13. Useclass TD(TypedDict): passorTD = TypedDict("TD", {})to create a TypedDict with zero field. - The
!typing.no_type_check_decoratordecorator function has been deprecated since Python 3.13. After eight years in thetypingmodule, it has yet to be supported by any major type checker.
- The undocumented keyword argument syntax for creating
!sre_compile,!sre_constantsand!sre_parsemodules.wave:- The
getmark(),setmark()andgetmarkers()methods of the~wave.Wave_readand~wave.Wave_writeclasses have been deprecated since Python 3.13.
- The
zipimport:!zipimport.zipimporter.load_modulehas been deprecated since Python 3.10. Use~zipimport.zipimporter.exec_moduleinstead. (125746.)
Pending removal in Python 3.16
- The import system:
- Setting
~module.__loader__on a module while failing to set__spec__.loader <importlib.machinery.ModuleSpec.loader>is deprecated. In Python 3.16,!__loader__will cease to be set or taken into consideration by the import system or the standard library. - Setting
~module.__package__on a module while failing to set__spec__.parent <importlib.machinery.ModuleSpec.parent>is deprecated. In Python 3.16,!__package__will cease to be taken into consideration by the import system or standard library. (97879)
- Setting
- The bundled copy of
libmpdec. array:- The
'u'format code (wchar_t) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the'w'format code (Py_UCS4) for Unicode characters instead.
- The
asyncio:-
!asyncio.iscoroutinefunctionis deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunctioninstead. (Contributed by Jiahao Li and Kumar Aditya in122875.) -
asynciopolicy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:!asyncio.AbstractEventLoopPolicy!asyncio.DefaultEventLoopPolicy!asyncio.WindowsSelectorEventLoopPolicy!asyncio.WindowsProactorEventLoopPolicy!asyncio.get_event_loop_policy!asyncio.set_event_loop_policy
Users should use
asyncio.runorasyncio.Runnerwith loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)(Contributed by Kumar Aditya in
127949.)
-
builtins:- Bitwise inversion on boolean types,
~Trueor~Falsehas been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2and-1). Usenot xinstead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert tointexplicitly (~int(x)).
- Bitwise inversion on boolean types,
functools:- Calling the Python implementation of
functools.reducewith function or sequence as keyword arguments has been deprecated since Python 3.14.
- Calling the Python implementation of
logging:- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
115032.)
- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
mimetypes:- Valid extensions start with a '.' or are empty for
mimetypes.MimeTypes.add_type. Undotted extensions are deprecated and will raise aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in75223.)
- Valid extensions start with a '.' or are empty for
shutil:- The
!ExecErrorexception has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4, and is now an alias ofRuntimeError.
- The
symtable:- The
!symtable.Class.get_methodsmethod has been deprecated since Python 3.14.
- The
sys:- The
!_enablelegacywindowsfsencodingfunction has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
- The
sysconfig:- The
!sysconfig.expand_makefile_varsfunction has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead.
- The
tarfile:- The undocumented and unused
!TarInfo.tarfileattribute has been deprecated since Python 3.13.
- The undocumented and unused
Pending removal in Python 3.17
datetime:~datetime.datetime.strptimecalls using a format string containing%e(day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in70647.)
collections.abc:-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
encodings:- Passing non-ascii encoding names to
encodings.normalize_encodingis deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in136702.)
- Passing non-ascii encoding names to
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOS. (137586)
typing:-
Before Python 3.14, old-style unions were implemented using the private class
typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers liketyping.get_originandtyping.get_argsinstead of relying on private implementation details. -
typing.ByteString, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
tkinter:- The
!tkinter.Variablemethods!trace_variable,!trace(an alias of!trace_variable),!trace_vdeleteand!trace_vinfo, deprecated since Python 3.14, are scheduled for removal in Python 3.17. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)
- The
Pending removal in Python 3.18
-
No longer accept a boolean value when a file descriptor is expected. (Contributed by Serhiy Storchaka in
82626.) -
decimal:- The non-standard and undocumented
~decimal.Decimalformat specifier'N', which is only supported in the!decimalmodule's C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in89902.)
- The non-standard and undocumented
-
Deprecations defined by
829:importlines in{name}.pthfiles are silently ignored.
(Contributed by Barry Warsaw in
148641.)
Pending removal in Python 3.19
builtins:- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.)
- Passing a complex number as the real or imag argument in the
ctypes:- Implicitly switching to the MSVC-compatible struct layout by setting
~ctypes.Structure._pack_but not~ctypes.Structure._layout_on non-Windows platforms.
- Implicitly switching to the MSVC-compatible struct layout by setting
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in various!hashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.
-
http.cookies:http.cookies.Morsel.js_outputis deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_outputis deprecated and will be removed in Python 3.19.
imaplib:-
Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.Before Python 3.14, this property was used to implement the corresponding
read()andreadline()methods for~imaplib.IMAP4but this is no longer the case since then.
-
tkinter:tkinter.filedialog.askopenfileshas been deprecated since Python 3.16. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.20
-
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling~object.__init__method on initialized~struct.Structobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.) -
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.) -
Deprecations defined by
829:- Warnings are produced for
importlines found in{name}.pthfiles. {name}.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in
148641.) - Warnings are produced for
-
ast:- Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.
- Creating instances of abstract AST nodes (such as
-
typing:-
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
Pending removal in Python 3.21
-
abc- Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively.
- Soft-deprecated since Python 3.3
-
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
- Classes
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodis deprecated since Python 3.16 and will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
-
struct:- Soft-deprecated since Python 3.15, using
'F'and'D'type codes are now deprecated. These codes will be removed in Python 3.21. Use instead two-letter forms'Zf'and'Zd'.
- Soft-deprecated since Python 3.15, using
-
tempfile:tempfile._TemporaryFileWrapperwill be removed in Python 3.21. Use the publictempfile.TemporaryFileWrapperinstead.
Pending removal in future versions
The following APIs will be removed in the future, although there is currently no date scheduled for their removal.
argparse:- Nesting argument groups and nesting mutually exclusive groups are deprecated.
- Passing the undocumented keyword argument prefix_chars to
~argparse.ArgumentParser.add_argument_groupis now deprecated. - The
argparse.FileTypetype converter is deprecated.
builtins:- Generators:
throw(type, exc, tb)andathrow(type, exc, tb)signature is deprecated: usethrow(exc)andathrow(exc)instead, the single argument signature. - Currently Python accepts numeric literals immediately followed by keywords, for example
0in x,1or x,0if 1else 2. It allows confusing and ambiguous expressions like[0x1for x in y](which can be interpreted as[0x1 for x in y]or[0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In a future release it will be changed to a syntax error. (87999) - Support for
__index__()and__int__()method returning non-int type: these methods will be required to return an instance of a strict subclass ofint. - Support for
__float__()method returning a strict subclass offloat: these methods will be required to return an instance offloat. - Support for
__complex__()method returning a strict subclass ofcomplex: these methods will be required to return an instance ofcomplex.
- Generators:
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.)codecs: useopeninstead ofcodecs.open. (133038)!codeobject.co_lnotab: use thecodeobject.co_linesmethod instead.datetime:~datetime.datetime.utcnow: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp: usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: Plural value must be an integer.importlib:~importlib.util.cache_from_sourcedebug_override parameter is deprecated: use the optimization parameter instead.
importlib.metadata:EntryPointstuple interface.- Implicit
Noneon return values.
logging: thewarn()method has been deprecated since Python 3.3, use~logging.warninginstead.mailbox: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.os: Callingos.register_at_forkin a multi-threaded process.os.path:os.path.commonprefixis deprecated, useos.path.commonpathfor path prefixes. Theos.path.commonprefixfunction is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.!pydoc.ErrorDuringImport: A tuple value for exc_info parameter is deprecated, use an exception instance.re: More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in91760.)shutil:~shutil.rmtree's onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:~ssl.SSLContext.set_npn_protocolsand!selected_npn_protocolare deprecated: use ALPN instead.ssl.OP_NO_SSL*optionsssl.OP_NO_TLS*optionsssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.TLSVersion.TLSv1_1
threadingmethods:!threading.Condition.notifyAll: use~threading.Condition.notify_all.!threading.Event.isSet: use~threading.Event.is_set.!threading.Thread.isDaemon,threading.Thread.setDaemon: usethreading.Thread.daemonattribute.!threading.Thread.getName,threading.Thread.setName: usethreading.Thread.nameattribute.!threading.currentThread: usethreading.current_thread.!threading.activeCount: usethreading.active_count.
typing.Text(92332).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in105499.) unittest.IsolatedAsyncioTestCase: it is deprecated to return a value that is notNonefrom a test case.urllib.parsedeprecated functions:~urllib.parse.urlparseinsteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partial writes.xml.etree.ElementTree: Testing the truth value of an~xml.etree.ElementTree.Elementis deprecated. In a future release it will always returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cacheis deprecated: usesys._clear_internal_cachesinstead.
CPython Bytecode Changes
- The oparg of
YIELD_VALUEis now1if the yield is part of a yield-from or await, and0otherwise. The oparg ofRESUMEwas changed to add a bit indicating if the except-depth is 1, which is needed to optimize closing of generators. (Contributed by Irit Katriel in111354.)
C API Changes
New Features
-
Add the
PyMonitoring C API <c-api-monitoring>for generating669monitoring events:PyMonitoringStatePyMonitoring_FirePyStartEventPyMonitoring_FirePyResumeEventPyMonitoring_FirePyReturnEventPyMonitoring_FirePyYieldEventPyMonitoring_FireCallEventPyMonitoring_FireLineEventPyMonitoring_FireJumpEventPyMonitoring_FireBranchEventPyMonitoring_FireCReturnEventPyMonitoring_FirePyThrowEventPyMonitoring_FireRaiseEventPyMonitoring_FireCRaiseEventPyMonitoring_FireReraiseEventPyMonitoring_FireExceptionHandledEventPyMonitoring_FirePyUnwindEventPyMonitoring_FireStopIterationEventPyMonitoring_EnterScopePyMonitoring_ExitScope
(Contributed by Irit Katriel in
111997). -
Add
PyMutex, a lightweight mutex that occupies a single byte, and the newPyMutex_LockandPyMutex_Unlockfunctions.!PyMutex_Lockwill release theGIL(if currently held) if the operation needs to block. (Contributed by Sam Gross in108724.) -
Add the
PyTime C API <c-api-time>to provide access to system clocks:PyTime_t.PyTime_MINandPyTime_MAX.PyTime_AsSecondsDouble.PyTime_Monotonic.PyTime_MonotonicRaw.PyTime_PerfCounter.PyTime_PerfCounterRaw.PyTime_Time.PyTime_TimeRaw.
(Contributed by Victor Stinner and Petr Viktorin in
110850.) -
Add the
PyDict_ContainsStringfunction with the same behavior asPyDict_Contains, but key is specified as aconst char*UTF-8 encoded bytes string, rather than aPyObject*. (Contributed by Victor Stinner in108314.) -
Add the
PyDict_GetItemRefandPyDict_GetItemStringReffunctions, which behave similarly toPyDict_GetItemWithError, but return astrong referenceinstead of aborrowed reference. Moreover, these functions return-1on error, removing the need to check!PyErr_Occurred. (Contributed by Victor Stinner in106004.) -
Add the
PyDict_SetDefaultReffunction, which behaves similarly toPyDict_SetDefault, but returns astrong referenceinstead of aborrowed reference. This function returns-1on error,0on insertion, and1if the key was already present in the dictionary. (Contributed by Sam Gross in112066.) -
Add the
PyDict_PopandPyDict_PopStringfunctions to remove a key from a dictionary and optionally return the removed value. This is similar todict.pop, though there is no default value, andKeyErroris not raised for missing keys. (Contributed by Stefan Behnel and Victor Stinner in111262.) -
Add the
PyMapping_GetOptionalItemandPyMapping_GetOptionalItemStringfunctions as alternatives toPyObject_GetItemandPyMapping_GetItemStringrespectively. The new functions do not raiseKeyErrorif the requested key is missing from the mapping. These variants are more convenient and faster if a missing key should not be treated as a failure. (Contributed by Serhiy Storchaka in106307.) -
Add the
PyObject_GetOptionalAttrandPyObject_GetOptionalAttrStringfunctions as alternatives toPyObject_GetAttrandPyObject_GetAttrStringrespectively. The new functions do not raiseAttributeErrorif the requested attribute is not found on the object. These variants are more convenient and faster if the missing attribute should not be treated as a failure. (Contributed by Serhiy Storchaka in106521.) -
Add the
PyErr_FormatUnraisablefunction as an extension toPyErr_WriteUnraisablethat allows customizing the warning message. (Contributed by Serhiy Storchaka in108082.) -
Add new functions that return a
strong referenceinstead of aborrowed referencefor frame locals, globals, and builtins, as part ofPEP 667 <whatsnew313-locals-semantics>:PyEval_GetFrameBuiltinsreplacesPyEval_GetBuiltinsPyEval_GetFrameGlobalsreplacesPyEval_GetGlobalsPyEval_GetFrameLocalsreplacesPyEval_GetLocals
(Contributed by Mark Shannon and Tian Gao in
74929.) -
Add the
Py_GetConstantandPy_GetConstantBorrowedfunctions to getstrong <strong reference>orborrowed <borrowed reference>references to constants. For example,Py_GetConstant(Py_CONSTANT_ZERO)returns a strong reference to the constant zero. (Contributed by Victor Stinner in115754.) -
Add the
PyImport_AddModuleReffunction as a replacement forPyImport_AddModulethat returns astrong referenceinstead of aborrowed reference. (Contributed by Victor Stinner in105922.) -
Add the
Py_IsFinalizingfunction to check whether the main Python interpreter isshutting down <interpreter shutdown>. (Contributed by Victor Stinner in108014.) -
Add the
PyList_GetItemReffunction as a replacement forPyList_GetItemthat returns astrong referenceinstead of aborrowed reference. (Contributed by Sam Gross in114329.) -
Add the
PyList_ExtendandPyList_Clearfunctions, mirroring the Pythonlist.extendandlist.clearmethods. (Contributed by Victor Stinner in111138.) -
Add the
PyLong_AsIntfunction. It behaves similarly toPyLong_AsLong, but stores the result in a Cintinstead of a Clong. (Contributed by Victor Stinner in108014.) -
Add the
PyLong_AsNativeBytes,PyLong_FromNativeBytes, andPyLong_FromUnsignedNativeBytesfunctions to simplify converting between native integer types and Pythonintobjects. (Contributed by Steve Dower in111140.) -
Add
PyModule_Addfunction, which is similar toPyModule_AddObjectRefandPyModule_AddObject, but always steals a reference to the value. (Contributed by Serhiy Storchaka in86493.) -
Add the
PyObject_GenericHashfunction that implements the default hashing function of a Python object. (Contributed by Serhiy Storchaka in113024.) -
Add the
Py_HashPointerfunction to hash a raw pointer. (Contributed by Victor Stinner in111545.) -
Add the
PyObject_VisitManagedDictandPyObject_ClearManagedDictfunctions. which must be called by the traverse and clear functions of a type using thePy_TPFLAGS_MANAGED_DICTflag. The pythoncapi-compat project can be used to use these functions with Python 3.11 and 3.12. (Contributed by Victor Stinner in107073.) -
Add the
PyRefTracer_SetTracerandPyRefTracer_GetTracerfunctions, which enable tracking object creation and destruction in the same way that thetracemallocmodule does. (Contributed by Pablo Galindo in93502.) -
Add the
PySys_AuditTuplefunction as an alternative toPySys_Auditthat takes event arguments as a Pythontupleobject. (Contributed by Victor Stinner in85283.) -
Add the
PyThreadState_GetUnchecked()function as an alternative toPyThreadState_Get()that doesn't kill the process with a fatal error if it isNULL. The caller is responsible for checking if the result isNULL. (Contributed by Victor Stinner in108867.) -
Add the
PyType_GetFullyQualifiedNamefunction to get the type's fully qualified name. The module name is prepended iftype.__module__is a string and is not equal to either'builtins'or'__main__'. (Contributed by Victor Stinner in111696.) -
Add the
PyType_GetModuleNamefunction to get the type's module name. This is equivalent to getting thetype.__module__attribute. (Contributed by Eric Snow and Victor Stinner in111696.) -
Add the
PyUnicode_EqualToUTF8AndSizeandPyUnicode_EqualToUTF8functions to compare a Unicode object with aconst char*UTF-8 encoded string and1if they are equal or0otherwise. These functions do not raise exceptions. (Contributed by Serhiy Storchaka in110289.) -
Add the
PyWeakref_GetReffunction as an alternative to!PyWeakref_GetObjectthat returns astrong referenceorNULLif the referent is no longer live. (Contributed by Victor Stinner in105927.) -
Add fixed variants of functions which silently ignore errors:
PyObject_HasAttrWithErrorreplacesPyObject_HasAttr.PyObject_HasAttrStringWithErrorreplacesPyObject_HasAttrString.PyMapping_HasKeyWithErrorreplacesPyMapping_HasKey.PyMapping_HasKeyStringWithErrorreplacesPyMapping_HasKeyString.
The new functions return
-1for errors and the standard1for true and0for false.(Contributed by Serhiy Storchaka in
108511.)
Changed C APIs
-
The keywords parameter of
PyArg_ParseTupleAndKeywordsandPyArg_VaParseTupleAndKeywordsnow has typechar * const *in C andconst char * const *in C++, instead ofchar **. In C++, this makes these functions compatible with arguments of typeconst char * const *,const char **, orchar * const *without an explicit type cast. In C, the functions only support arguments of typechar * const *. This can be overridden with thePY_CXX_CONSTmacro. (Contributed by Serhiy Storchaka in65210.) -
PyArg_ParseTupleAndKeywordsnow supports non-ASCII keyword parameter names. (Contributed by Serhiy Storchaka in110815.) -
The
!PyCode_GetFirstFreefunction is now unstable API and is now namedPyUnstable_Code_GetFirstFree. (Contributed by Bogdan Romanyuk in115781.) -
The
PyDict_GetItem,PyDict_GetItemString,PyMapping_HasKey,PyMapping_HasKeyString,PyObject_HasAttr,PyObject_HasAttrString, andPySys_GetObjectfunctions, each of which clears all errors which occurred when calling them now reports these errors usingsys.unraisablehook. You may replace them with other functions as recommended in the documentation. (Contributed by Serhiy Storchaka in106672.) -
Add support for the
%T,%#T,%Nand%#Nformats toPyUnicode_FromFormat:%T: Get the fully qualified name of an object type%#T: As above, but use a colon as the separator%N: Get the fully qualified name of a type%#N: As above, but use a colon as the separator
See
737for more information. (Contributed by Victor Stinner in111696.) -
You no longer have to define the
PY_SSIZE_T_CLEANmacro before includingPython.hwhen using#formats informat codes <arg-parsing-string-and-buffers>. APIs accepting the format codes always usePy_ssize_tfor#formats. (Contributed by Inada Naoki in104922.) -
If Python is built in
debug mode <debug-build>orwith assertions <--with-assertions>,PyTuple_SET_ITEMandPyList_SET_ITEMnow check the index argument with an assertion. (Contributed by Victor Stinner in106168.)
Limited C API Changes
-
The following functions are now included in the Limited C API:
PyMem_RawMallocPyMem_RawCallocPyMem_RawReallocPyMem_RawFreePySys_AuditPySys_AuditTuplePyType_GetModuleByDef
(Contributed by Victor Stinner in
85283and116936.) -
Python built with
--with-trace-refs(tracing references) now supports theLimited API <limited-c-api>. (Contributed by Victor Stinner in108634.)
Removed C APIs
-
Remove several functions, macros, variables, etc with names prefixed by
_Pyor_PY(which are considered private). If your project is affected by one of these removals and you believe that the removed API should remain available, pleaseopen a new issue <using-the-tracker>to request a public C API and addcc: @vstinnerto the issue to notify Victor Stinner. (Contributed by Victor Stinner in106320.) -
Remove old buffer protocols deprecated in Python 3.0. Use
bufferobjectsinstead.-
!PyObject_CheckReadBuffer: UsePyObject_CheckBufferto test whether the object supports the buffer protocol. Note thatPyObject_CheckBufferdoesn't guarantee thatPyObject_GetBufferwill succeed. To test if the object is actually readable, see the next example ofPyObject_GetBuffer. -
!PyObject_AsCharBuffer,!PyObject_AsReadBuffer: UsePyObject_GetBufferandPyBuffer_Releaseinstead:Py_buffer view; if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) { return NULL; } // Use `view.buf` and `view.len` to read from the buffer. // You may need to cast buf as `(const char*)view.buf`. PyBuffer_Release(&view); -
!PyObject_AsWriteBuffer: UsePyObject_GetBufferandPyBuffer_Releaseinstead:Py_buffer view; if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) { return NULL; } // Use `view.buf` and `view.len` to write to the buffer. PyBuffer_Release(&view);
(Contributed by Inada Naoki in
85275.) -
-
Remove various functions deprecated in Python 3.9:
-
!PyEval_CallObject,!PyEval_CallObjectWithKeywords: UsePyObject_CallNoArgsorPyObject_Callinstead.[!WARNING] In
PyObject_Call, positional arguments must be atupleand must not beNULL, and keyword arguments must be adictorNULL, whereas the removed functions checked argument types and acceptedNULLpositional and keyword arguments. To replacePyEval_CallObjectWithKeywords(func, NULL, kwargs)withPyObject_Call, pass an empty tuple as positional arguments usingPyTuple_New(0) <PyTuple_New>. -
!PyEval_CallFunction: UsePyObject_CallFunctioninstead. -
!PyEval_CallMethod: UsePyObject_CallMethodinstead. -
!PyCFunction_Call: UsePyObject_Callinstead.
(Contributed by Victor Stinner in
105107.) -
-
Remove the following old functions to configure the Python initialization, deprecated in Python 3.11:
!PySys_AddWarnOptionUnicode: UsePyConfig.warnoptionsinstead.!PySys_AddWarnOption: UsePyConfig.warnoptionsinstead.!PySys_AddXOption: UsePyConfig.xoptionsinstead.!PySys_HasWarnOptions: UsePyConfig.warnoptionsinstead.!PySys_SetPath: SetPyConfig.module_search_pathsinstead.!Py_SetPath: SetPyConfig.module_search_pathsinstead.!Py_SetStandardStreamEncoding: SetPyConfig.stdio_encodinginstead, and set also maybePyConfig.legacy_windows_stdio(on Windows).!_Py_SetProgramFullPath: SetPyConfig.executableinstead.
Use the new
PyConfigAPI of thePython Initialization Configuration <init-config>instead (587), added to Python 3.8. (Contributed by Victor Stinner in105145.) -
Remove
!PyEval_AcquireLockand!PyEval_ReleaseLockfunctions, deprecated in Python 3.2. They didn't update the current thread state. They can be replaced with:PyEval_SaveThreadandPyEval_RestoreThread;- low-level
PyEval_AcquireThreadandPyEval_ReleaseThread; - or
PyGILState_EnsureandPyGILState_Release.
(Contributed by Victor Stinner in
105182.) -
Remove the
!PyEval_ThreadsInitializedfunction, deprecated in Python 3.9. Since Python 3.7,!Py_Initializealways creates the GIL: calling!PyEval_InitThreadsdoes nothing and!PyEval_ThreadsInitializedalways returns non-zero. (Contributed by Victor Stinner in105182.) -
Remove the
!_PyInterpreterState_Getalias toPyInterpreterState_Get()which was kept for backward compatibility with Python 3.8. The pythoncapi-compat project can be used to getPyInterpreterState_Get()on Python 3.8 and older. (Contributed by Victor Stinner in106320.) -
Remove the private
!_PyObject_FastCallfunction: use!PyObject_Vectorcallwhich is available since Python 3.8 (590). (Contributed by Victor Stinner in106023.) -
Remove the
cpython/pytime.hheader file, which only contained private functions. (Contributed by Victor Stinner in106316.) -
Remove the undocumented
PY_TIMEOUT_MAXconstant from the limited C API. (Contributed by Victor Stinner in110014.) -
Remove the old trashcan macros
Py_TRASHCAN_SAFE_BEGINandPy_TRASHCAN_SAFE_END. Replace both with the new macrosPy_TRASHCAN_BEGINandPy_TRASHCAN_END. (Contributed by Irit Katriel in105111.)
Deprecated C APIs
-
Deprecate old Python initialization functions:
!PySys_ResetWarnOptions: Clearsys.warnoptionsand!warnings.filtersinstead.!Py_GetExecPrefix: Getsys.exec_prefixinstead.!Py_GetPath: Getsys.pathinstead.!Py_GetPrefix: Getsys.prefixinstead.!Py_GetProgramFullPath: Getsys.executableinstead.!Py_GetProgramName: Getsys.executableinstead.!Py_GetPythonHome: GetPyConfig.homeor thePYTHONHOMEenvironment variable instead.
(Contributed by Victor Stinner in
105145.) -
Soft deprecate <soft deprecated>thePyEval_GetBuiltins,PyEval_GetGlobals, andPyEval_GetLocalsfunctions, which return aborrowed reference. (Soft deprecated as part of667.) -
Deprecate the
!PyImport_ImportModuleNoBlockfunction, which is just an alias toPyImport_ImportModulesince Python 3.3. (Contributed by Victor Stinner in105396.) -
Soft deprecate <soft deprecated>thePyModule_AddObjectfunction. It should be replaced withPyModule_AddorPyModule_AddObjectRef. (Contributed by Serhiy Storchaka in86493.) -
Deprecate the old
Py_UNICODEandPY_UNICODE_TYPEtypes and the!Py_UNICODE_WIDEdefine. Use thewchar_ttype directly instead. Since Python 3.3,Py_UNICODEandPY_UNICODE_TYPEare just aliases to!wchar_t. (Contributed by Victor Stinner in105156.) -
Deprecate the
!PyWeakref_GetObjectand!PyWeakref_GET_OBJECTfunctions, which return aborrowed reference. Replace them with the newPyWeakref_GetReffunction, which returns astrong reference. The pythoncapi-compat project can be used to getPyWeakref_GetRefon Python 3.12 and older. (Contributed by Victor Stinner in105927.)
Pending removal in Python 3.14
- The
ma_version_tagfield inPyDictObjectfor extension modules (699;101193). - Creating
immutable types <Py_TPFLAGS_IMMUTABLETYPE>with mutable bases (95388).
Pending removal in Python 3.15
-
The
!PyImport_ImportModuleNoBlock: UsePyImport_ImportModuleinstead. -
!PyWeakref_GetObjectand!PyWeakref_GET_OBJECT: UsePyWeakref_GetRefinstead. The pythoncapi-compat project can be used to getPyWeakref_GetRefon Python 3.12 and older. -
!PyUnicode_AsDecodedObject: UsePyCodec_Decodeinstead. -
!PyUnicode_AsDecodedUnicode: UsePyCodec_Decodeinstead; Note that some codecs (for example, "base64") may return a type other thanstr, such asbytes. -
!PyUnicode_AsEncodedObject: UsePyCodec_Encodeinstead. -
!PyUnicode_AsEncodedUnicode: UsePyCodec_Encodeinstead; Note that some codecs (for example, "base64") may return a type other thanbytes, such asstr. -
Python initialization functions, deprecated in Python 3.13:
!Py_GetPath: UsePyConfig_Get("module_search_paths") <PyConfig_Get>(sys.path) instead.!Py_GetPrefix: UsePyConfig_Get("base_prefix") <PyConfig_Get>(sys.base_prefix) instead. UsePyConfig_Get("prefix") <PyConfig_Get>(sys.prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetExecPrefix: UsePyConfig_Get("base_exec_prefix") <PyConfig_Get>(sys.base_exec_prefix) instead. UsePyConfig_Get("exec_prefix") <PyConfig_Get>(sys.exec_prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetProgramFullPath: UsePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetProgramName: UsePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetPythonHome: UsePyConfig_Get("home") <PyConfig_Get>or thePYTHONHOMEenvironment variable instead.
The pythoncapi-compat project can be used to get
PyConfig_Geton Python 3.13 and older.
Pending removal in Python 3.16
-
Functions to configure Python's initialization, deprecated in Python 3.11:
!PySys_SetArgvEx(): SetPyConfig.argvinstead.!PySys_SetArgv(): SetPyConfig.argvinstead.!Py_SetProgramName(): SetPyConfig.program_nameinstead.!Py_SetPythonHome(): SetPyConfig.homeinstead.
The
Py_InitializeFromConfigAPI should be used withPyConfiginstead. -
Global configuration variables:
!Py_DebugFlag: UsePyConfig.parser_debugorPyConfig_Get("parser_debug") <PyConfig_Get>instead.!Py_VerboseFlag: UsePyConfig.verboseorPyConfig_Get("verbose") <PyConfig_Get>instead.!Py_QuietFlag: UsePyConfig.quietorPyConfig_Get("quiet") <PyConfig_Get>instead.!Py_InteractiveFlag: UsePyConfig.interactiveorPyConfig_Get("interactive") <PyConfig_Get>instead.!Py_InspectFlag: UsePyConfig.inspectorPyConfig_Get("inspect") <PyConfig_Get>instead.!Py_OptimizeFlag: UsePyConfig.optimization_levelorPyConfig_Get("optimization_level") <PyConfig_Get>instead.!Py_NoSiteFlag: UsePyConfig.site_importorPyConfig_Get("site_import") <PyConfig_Get>instead.!Py_BytesWarningFlag: UsePyConfig.bytes_warningorPyConfig_Get("bytes_warning") <PyConfig_Get>instead.!Py_FrozenFlag: UsePyConfig.pathconfig_warningsorPyConfig_Get("pathconfig_warnings") <PyConfig_Get>instead.!Py_IgnoreEnvironmentFlag: UsePyConfig.use_environmentorPyConfig_Get("use_environment") <PyConfig_Get>instead.!Py_DontWriteBytecodeFlag: UsePyConfig.write_bytecodeorPyConfig_Get("write_bytecode") <PyConfig_Get>instead.!Py_NoUserSiteDirectory: UsePyConfig.user_site_directoryorPyConfig_Get("user_site_directory") <PyConfig_Get>instead.!Py_UnbufferedStdioFlag: UsePyConfig.buffered_stdioorPyConfig_Get("buffered_stdio") <PyConfig_Get>instead.!Py_HashRandomizationFlag: UsePyConfig.use_hash_seedandPyConfig.hash_seedorPyConfig_Get("hash_seed") <PyConfig_Get>instead.!Py_IsolatedFlag: UsePyConfig.isolatedorPyConfig_Get("isolated") <PyConfig_Get>instead.!Py_LegacyWindowsFSEncodingFlag: UsePyPreConfig.legacy_windows_fs_encodingorPyConfig_Get("legacy_windows_fs_encoding") <PyConfig_Get>instead.!Py_LegacyWindowsStdioFlag: UsePyConfig.legacy_windows_stdioorPyConfig_Get("legacy_windows_stdio") <PyConfig_Get>instead.!Py_FileSystemDefaultEncoding,!Py_HasFileSystemDefaultEncoding: UsePyConfig.filesystem_encodingorPyConfig_Get("filesystem_encoding") <PyConfig_Get>instead.!Py_FileSystemDefaultEncodeErrors: UsePyConfig.filesystem_errorsorPyConfig_Get("filesystem_errors") <PyConfig_Get>instead.!Py_UTF8Mode: UsePyPreConfig.utf8_modeorPyConfig_Get("utf8_mode") <PyConfig_Get>instead. (seePy_PreInitialize)
The
Py_InitializeFromConfigAPI should be used withPyConfigto set these options. OrPyConfig_Getcan be used to get these options at runtime. -
Py_UNICODEwhich was deprecated by393.
Pending removal in Python 3.18
-
The following private functions are deprecated and planned for removal in Python 3.18:
!_PyBytes_Join: usePyBytes_Join.!_PyDict_GetItemStringWithError: usePyDict_GetItemStringRef.!_PyDict_Pop(): usePyDict_Pop.!_PyLong_Sign(): usePyLong_GetSign.!_PyLong_FromDigitsand!_PyLong_New: usePyLongWriter_Create.!_PyThreadState_UncheckedGet: usePyThreadState_GetUnchecked.!_PyUnicode_AsString: usePyUnicode_AsUTF8.!_PyUnicodeWriter_Init: replace_PyUnicodeWriter_Init(&writer)withwriter = PyUnicodeWriter_Create(0) <PyUnicodeWriter_Create>.!_PyUnicodeWriter_Finish: replace_PyUnicodeWriter_Finish(&writer)withPyUnicodeWriter_Finish(writer) <PyUnicodeWriter_Finish>.!_PyUnicodeWriter_Dealloc: replace_PyUnicodeWriter_Dealloc(&writer)withPyUnicodeWriter_Discard(writer) <PyUnicodeWriter_Discard>.!_PyUnicodeWriter_WriteChar: replace_PyUnicodeWriter_WriteChar(&writer, ch)withPyUnicodeWriter_WriteChar(writer, ch) <PyUnicodeWriter_WriteChar>.!_PyUnicodeWriter_WriteStr: replace_PyUnicodeWriter_WriteStr(&writer, str)withPyUnicodeWriter_WriteStr(writer, str) <PyUnicodeWriter_WriteStr>.!_PyUnicodeWriter_WriteSubstring: replace_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)withPyUnicodeWriter_WriteSubstring(writer, str, start, end) <PyUnicodeWriter_WriteSubstring>.!_PyUnicodeWriter_WriteASCIIString: replace_PyUnicodeWriter_WriteASCIIString(&writer, str, size)withPyUnicodeWriter_WriteASCII(writer, str, size) <PyUnicodeWriter_WriteASCII>.!_PyUnicodeWriter_WriteLatin1String: replace_PyUnicodeWriter_WriteLatin1String(&writer, str, size)by decoding the string withPyUnicode_DecodeLatin1, writing the result withPyUnicodeWriter_WriteStr, and releasing the result withPy_DECREF.!_PyUnicodeWriter_Prepare: (no replacement).!_PyUnicodeWriter_PrepareKind: (no replacement).!_Py_HashPointer: usePy_HashPointer.!_Py_fopen_obj: usePy_fopen.PyGen_New: (no replacement).PyGen_NewWithQualName: (no replacement).PyCoro_New: (no replacement).PyAsyncGen_New: (no replacement).
The pythoncapi-compat project can be used to get these new public functions on Python 3.13 and older. (Contributed by Victor Stinner in
128863.)
Pending removal in future versions
The following APIs are deprecated and will be removed, although there is currently no date scheduled for their removal.
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch: UsePyErr_GetRaisedExceptioninstead.PyErr_NormalizeException: UsePyErr_GetRaisedExceptioninstead.PyErr_Restore: UsePyErr_SetRaisedExceptioninstead.PyOS_AfterFork: UsePyOS_AfterFork_Childinstead.PySlice_GetIndicesEx: UsePySlice_UnpackandPySlice_AdjustIndicesinstead.PyUnicode_READY: Unneeded since Python 3.12!PyErr_Display: UsePyErr_DisplayExceptioninstead.!_PyErr_ChainExceptions: Use!_PyErr_ChainExceptions1instead.!PyBytesObject.ob_shashmember: callPyObject_Hashinstead.- Thread Local Storage (TLS) API:
PyThread_create_key: UsePyThread_tss_allocinstead.PyThread_delete_key: UsePyThread_tss_freeinstead.PyThread_set_key_value: UsePyThread_tss_setinstead.PyThread_get_key_value: UsePyThread_tss_getinstead.PyThread_delete_key_value: UsePyThread_tss_deleteinstead.PyThread_ReInitTLS: Unneeded since Python 3.7.
Build Changes
arm64-apple-iosandarm64-apple-ios-simulatorare both now11tier 3 platforms. (PEP 730 <whatsnew313-platform-support>written and implementation contributed by Russell Keith-Magee in114099.)aarch64-linux-androidandx86_64-linux-androidare both now11tier 3 platforms. (PEP 738 <whatsnew313-platform-support>written and implementation contributed by Malcolm Smith in116622.)wasm32-wasiis now a11tier 2 platform. (Contributed by Brett Cannon in115192.)wasm32-emscriptenis no longer a11supported platform. (Contributed by Brett Cannon in115192.)- Building CPython now requires a compiler with support for the C11 atomic library, GCC built-in atomic functions, or MSVC interlocked intrinsics.
- Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate the
configurescript. (Contributed by Christian Heimes in89886and by Victor Stinner in112090.) - SQLite 3.15.2 or newer is required to build the
sqlite3extension module. (Contributed by Erlend Aasland in105875.) - CPython now bundles the mimalloc library by default. It is licensed under the MIT license; see
mimalloc license <mimalloc-license>. The bundled mimalloc has custom changes, see113141for details. (Contributed by Dino Viehland in109914.) - The
configureoption!--with-system-libmpdecnow defaults toyes. The bundled copy oflibmpdecwill be removed in Python 3.16. - Python built with
configure--with-trace-refs(tracing references) is now ABI compatible with the Python release build anddebug build <debug-build>. (Contributed by Victor Stinner in108634.) - On POSIX systems, the pkg-config (
.pc) filenames now include the ABI flags. For example, the free-threaded build generatespython-3.13t.pcand the debug build generatespython-3.13d.pc. - The
errno,fcntl,grp,md5,pwd,resource,termios,winsound,_ctypes_test,_multiprocessing.posixshmem,_scproxy,_stat,_statistics,_testconsole,_testimportmultipleand_uuidC extensions are now built with thelimited C API <limited-c-api>. (Contributed by Victor Stinner in85283.)
Porting to Python 3.13
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in the Python API
-
PEP 667 <whatsnew313-locals-semantics>introduces several changes to the semantics oflocalsandf_locals <frame.f_locals>:- Calling
localsin anoptimized scopenow produces an independent snapshot on each call, and hence no longer implicitly updates previously returned references. Obtaining the legacy CPython behavior now requires explicit calls to update the initially returned dictionary with the results of subsequent calls to!locals. Code execution functions that implicitly target!locals(such asexecandeval) must be passed an explicit namespace to access their results in an optimized scope. (Changed as part of667.) - Calling
localsfrom a comprehension at module or class scope (including viaexecoreval) once more behaves as if the comprehension were running as an independent nested function (i.e. the local variables from the containing scope are not included). In Python 3.12, this had changed to include the local variables from the containing scope when implementing709. (Changed as part of667.) - Accessing
FrameType.f_locals <frame.f_locals>in anoptimized scopenow returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly withdictor the proxy's.copy()method. (Changed as part of667.)
- Calling
-
functools.partialnow emits aFutureWarningwhen used as a method. The behavior will change in future Python versions. Wrap it instaticmethodif you want to preserve the old behavior. (Contributed by Serhiy Storchaka in121027.) -
An
OSErroris now raised bygetpass.getuserfor any failure to retrieve a username, instead ofImportErroron non-Unix platforms orKeyErroron Unix platforms where the password database is empty. -
The value of the
!modeattribute ofgzip.GzipFileis now a string ('rb'or'wb') instead of an integer (1or2). The value of the!modeattribute of the readable file-like object returned byzipfile.ZipFile.openis now'rb'instead of'r'. (Contributed by Serhiy Storchaka in115961.) -
mailbox.Maildirnow ignores files with a leading dot (.). (Contributed by Zackery Spytz in65559.) -
pathlib.Path.globand~pathlib.Path.rglobnow return both files and directories if a pattern that ends with "**" is given, rather than directories only. Add a trailing slash to keep the previous behavior and only match directories. -
The
threadingmodule now expects the!_threadmodule to have an!_is_main_interpreterfunction. This function takes no arguments and returnsTrueif the current interpreter is the main interpreter.Any library or application that provides a custom
!_threadmodule must provide!_is_main_interpreter, just like the module's other "private" attributes. (112826.)
Changes in the C API
-
Python.hno longer includes the<ieeefp.h>standard header. It was included for the!finitefunction which is now provided by the<math.h>header. It should now be included explicitly if needed. Remove also theHAVE_IEEEFP_Hmacro. (Contributed by Victor Stinner in108765.) -
Python.hno longer includes these standard header files:<time.h>,<sys/select.h>and<sys/time.h>. If needed, they should now be included explicitly. For example,<time.h>provides the!clockand!gmtimefunctions,<sys/select.h>provides the!selectfunction, and<sys/time.h>provides the!futimes,!gettimeofdayand!setitimerfunctions. (Contributed by Victor Stinner in108765.) -
On Windows,
Python.hno longer includes the<stddef.h>standard header file. If needed, it should now be included explicitly. For example, it provides!offsetoffunction, andsize_tandptrdiff_ttypes. Including<stddef.h>explicitly was already needed by all other platforms, theHAVE_STDDEF_Hmacro is only defined on Windows. (Contributed by Victor Stinner in108765.) -
If the
Py_LIMITED_APImacro is defined,!Py_BUILD_CORE,!Py_BUILD_CORE_BUILTINand!Py_BUILD_CORE_MODULEmacros are now undefined by<Python.h>. (Contributed by Victor Stinner in85283.) -
The old trashcan macros
Py_TRASHCAN_SAFE_BEGINandPy_TRASHCAN_SAFE_ENDwere removed. They should be replaced by the new macrosPy_TRASHCAN_BEGINandPy_TRASHCAN_END.A
tp_deallocfunction that has the old macros, such as:static void mytype_dealloc(mytype *p) { PyObject_GC_UnTrack(p); Py_TRASHCAN_SAFE_BEGIN(p); ... Py_TRASHCAN_SAFE_END(p) }should migrate to the new macros as follows:
static void mytype_dealloc(mytype *p) { PyObject_GC_UnTrack(p); Py_TRASHCAN_BEGIN(p, mytype_dealloc) ... Py_TRASHCAN_END }Note that
Py_TRASHCAN_BEGINhas a second argument which should be the deallocation function it is in. The new macros were added in Python 3.8 and the old macros were deprecated in Python 3.11. (Contributed by Irit Katriel in105111.)
-
PEP 667 <whatsnew313-locals-semantics>introduces several changes to frame-related functions:- The effects of mutating the dictionary returned from
PyEval_GetLocalsin anoptimized scopehave changed. New dict entries added this way will now only be visible to subsequentPyEval_GetLocalscalls in that frame, asPyFrame_GetLocals,locals, andFrameType.f_locals <frame.f_locals>no longer access the same underlying cached dictionary. Changes made to entries for actual variable names and names added via the write-through proxy interfaces will be overwritten on subsequent calls toPyEval_GetLocalsin that frame. The recommended code update depends on how the function was being used, so refer to the deprecation notice on the function for details. - Calling
PyFrame_GetLocalsin anoptimized scopenow returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly, or by calling the newPyEval_GetFrameLocalsAPI. !PyFrame_FastToLocalsand!PyFrame_FastToLocalsWithErrorno longer have any effect. Calling these functions has been redundant since Python 3.11, whenPyFrame_GetLocalswas first introduced.!PyFrame_LocalsToFastno longer has any effect. Calling this function is redundant now thatPyFrame_GetLocalsreturns a write-through proxy foroptimized scopes <optimized scope>.
- The effects of mutating the dictionary returned from
-
Python 3.13 removed many private functions. Some of them can be replaced using these alternatives:
_PyDict_Pop():PyDict_PoporPyDict_PopString;_PyDict_GetItemWithError():PyDict_GetItemRef;_PyErr_WriteUnraisableMsg():PyErr_FormatUnraisable;_PyEval_SetTrace():PyEval_SetTraceorPyEval_SetTraceAllThreads;_PyList_Extend():PyList_Extend;_PyLong_AsInt():PyLong_AsInt;_PyMem_RawStrdup():strdup();_PyMem_Strdup():strdup();_PyObject_ClearManagedDict():PyObject_ClearManagedDict;_PyObject_VisitManagedDict():PyObject_VisitManagedDict;_PyThreadState_UncheckedGet():PyThreadState_GetUnchecked();_PyTime_AsSecondsDouble():PyTime_AsSecondsDouble;_PyTime_GetMonotonicClock():PyTime_MonotonicorPyTime_MonotonicRaw;_PyTime_GetPerfCounter():PyTime_PerfCounterorPyTime_PerfCounterRaw;_PyTime_GetSystemClock():PyTime_TimeorPyTime_TimeRaw;_PyTime_MAX:PyTime_MAX;_PyTime_MIN:PyTime_MIN;_PyTime_t:PyTime_t;_Py_HashPointer():Py_HashPointer;_Py_IsFinalizing():Py_IsFinalizing.
The pythoncapi-compat project can be used to get most of these new functions on Python 3.12 and older.
Regression Test Changes
- Python built with
configure--with-pydebugnow supports a-X presite=package.module <-X>command-line option. If used, it specifies a module that should be imported early in the lifecycle of the interpreter, beforesite.pyis executed. (Contributed by Łukasz Langa in110769.)
What's new in Python 3.14
Editors
Adam Turner and Hugo van Kemenade
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the issue number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the VCS log when researching a change.
This article explains the new features in Python 3.14, compared to 3.13. Python 3.14 was released on 7 October 2025. For full details, see the changelog <changelog>.
745 -- Python 3.14 release schedule
Summary -- Release highlights
Python 3.14 is a stable release of the Python programming language, with a mix of changes to the language, the implementation, and the standard library. The biggest changes include template string literals <whatsnew314-template-string-literals>, deferred evaluation of annotations <whatsnew314-deferred-annotations>, and support for subinterpreters <whatsnew314-multiple-interpreters> in the standard library.
The library changes include significantly improved capabilities for introspection in asyncio <whatsnew314-asyncio-introspection>, support for Zstandard <whatsnew314-zstandard> via a new compression.zstd module, syntax highlighting in the REPL, as well as the usual deprecations and removals, and improvements in user-friendliness and correctness.
This article doesn't attempt to provide a complete specification of all new features, but instead gives a convenient overview. For full details refer to the documentation, such as the Library Reference <library-index> and Language Reference <reference-index>. To understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented. See Porting to Python 3.14 for guidance on upgrading from earlier versions of Python.
Interpreter improvements:
649and749:Deferred evaluation of annotations <whatsnew314-deferred-annotations>734:Multiple interpreters in the standard library <whatsnew314-multiple-interpreters>750:Template strings <whatsnew314-template-string-literals>758:Allow except and except* expressions without brackets <whatsnew314-bracketless-except>765:Control flow in finally blocks <whatsnew314-finally-syntaxwarning>768:Safe external debugger interface for CPython <whatsnew314-remote-debugging>A new type of interpreter <whatsnew314-tail-call-interpreter>Free-threaded mode improvements <whatsnew314-free-threaded-cpython>Improved error messages <whatsnew314-improved-error-messages>Incremental garbage collection <whatsnew314-incremental-gc>
Significant improvements in the standard library:
784:Zstandard support in the standard library <whatsnew314-zstandard>whatsnew314-asyncio-introspectionwhatsnew314-concurrent-warnings-controlSyntax highlighting in the default interactive shell <whatsnew314-pyrepl-highlighting>, and color output in several standard library CLIs
C API improvements:
741:Python configuration C API <whatsnew314-capi-config>
Platform support:
776: Emscripten is now anofficially supported platform <whatsnew314-build-changes>, attier 3 <11#tier-3>.
Release changes:
779:Free-threaded Python is officially supported <whatsnew314-free-threaded-now-supported>761:PGP signatures have been discontinued for official releases <whatsnew314-no-more-pgp>Windows and macOS binary releases now support the experimental just-in-time compiler <whatsnew314-jit-compiler>Binary releases for Android are now provided <whatsnew314-build-changes>
New features
649 & 749: Deferred evaluation of annotations
The annotations <annotation> on functions, classes, and modules are no longer evaluated eagerly. Instead, annotations are stored in special-purpose annotate functions <annotate function> and evaluated only when necessary (except if from __future__ import annotations is used).
This change is designed to improve performance and usability of annotations in Python in most circumstances. The runtime cost for defining annotations is minimized, but it remains possible to introspect annotations at runtime. It is no longer necessary to enclose annotations in strings if they contain forward references.
The new annotationlib module provides tools for inspecting deferred annotations. Annotations may be evaluated in the ~annotationlib.Format.VALUE format (which evaluates annotations to runtime values, similar to the behavior in earlier Python versions), the ~annotationlib.Format.FORWARDREF format (which replaces undefined names with special markers), and the ~annotationlib.Format.STRING format (which returns annotations as strings).
This example shows how these formats behave:
>>> from annotationlib import get_annotations, Format >>> def func(arg: Undefined): ... pass >>> get_annotations(func, format=Format.VALUE) Traceback (most recent call last): ... NameError: name 'Undefined' is not defined >>> get_annotations(func, format=Format.FORWARDREF) {'arg': ForwardRef('Undefined', owner=<function func at 0x...>)} >>> get_annotations(func, format=Format.STRING) {'arg': 'Undefined'}
The porting <whatsnew314-porting-annotations> section contains guidance on changes that may be needed due to these changes, though in the majority of cases, code will continue working as-is.
(Contributed by Jelle Zijlstra in 749 and 119180; 649 was written by Larry Hastings.)
649
Deferred Evaluation Of Annotations Using Descriptors
749
Implementing PEP 649
734: Multiple interpreters in the standard library
The CPython runtime supports running multiple copies of Python in the same process simultaneously and has done so for over 20 years. Each of these separate copies is called an 'interpreter'. However, the feature had been available only through the C-API <sub-interpreter-support>.
That limitation is removed in Python 3.14, with the new concurrent.interpreters module.
There are at least two notable reasons why using multiple interpreters has significant benefits:
- they support a new (to Python), human-friendly concurrency model
- true multi-core parallelism
For some use cases, concurrency in software improves efficiency and can simplify design, at a high level. At the same time, implementing and maintaining all but the simplest concurrency is often a struggle for the human brain. That especially applies to plain threads (for example, threading), where all memory is shared between all threads.
With multiple isolated interpreters, you can take advantage of a class of concurrency models, like Communicating Sequential Processes (CSP) or the actor model, that have found success in other programming languages, like Smalltalk, Erlang, Haskell, and Go. Think of multiple interpreters as threads but with opt-in sharing.
Regarding multi-core parallelism: as of Python 3.12, interpreters are now sufficiently isolated from one another to be used in parallel (see 684). This unlocks a variety of CPU-intensive use cases for Python that were limited by the GIL.
Using multiple interpreters is similar in many ways to multiprocessing, in that they both provide isolated logical "processes" that can run in parallel, with no sharing by default. However, when using multiple interpreters, an application will use fewer system resources and will operate more efficiently (since it stays within the same process). Think of multiple interpreters as having the isolation of processes with the efficiency of threads.
While the feature has been around for decades, multiple interpreters have not been used widely, due to low awareness and the lack of a standard library module. Consequently, they currently have several notable limitations, which are expected to improve significantly now that the feature is going mainstream.
Current limitations:
- starting each interpreter has not been optimized yet
- each interpreter uses more memory than necessary (work continues on extensive internal sharing between interpreters)
- there aren't many options yet for truly sharing objects or other data between interpreters (other than
memoryview) - many third-party extension modules on PyPI are not yet compatible with multiple interpreters (all standard library extension modules are compatible)
- the approach to writing applications that use multiple isolated interpreters is mostly unfamiliar to Python users, for now
The impact of these limitations will depend on future CPython improvements, how interpreters are used, and what the community solves through PyPI packages. Depending on the use case, the limitations may not have much impact, so try it out!
Furthermore, future CPython releases will reduce or eliminate overhead and provide utilities that are less appropriate on PyPI. In the meantime, most of the limitations can also be addressed through extension modules, meaning PyPI packages can fill any gap for 3.14, and even back to 3.12 where interpreters were finally properly isolated and stopped sharing the GIL. Likewise, libraries on PyPI are expected to emerge for high-level abstractions on top of interpreters.
Regarding extension modules, work is in progress to update some PyPI projects, as well as tools like Cython, pybind11, nanobind, and PyO3. The steps for isolating an extension module are found at isolating-extensions-howto. Isolating a module has a lot of overlap with what is required to support free-threading <whatsnew314-free-threaded-cpython>, so the ongoing work in the community in that area will help accelerate support for multiple interpreters.
Also added in 3.14: concurrent.futures.InterpreterPoolExecutor <whatsnew314-concurrent-futures-interp-pool>.
(Contributed by Eric Snow in 134939.)
734
750: Template string literals
Template strings are a new mechanism for custom string processing. They share the familiar syntax of f-strings but, unlike f-strings, return an object representing the static and interpolated parts of the string, instead of a simple str.
To write a t-string, use a 't' prefix instead of an 'f':
>>> variety = 'Stilton' >>> template = t'Try some {variety} cheese!' >>> type(template) <class 'string.templatelib.Template'>
~string.templatelib.Template objects provide access to the static and interpolated (in curly braces) parts of a string before they are combined. Iterate over !Template instances to access their parts in order:
variety = 'Stilton' template = t'Try some {variety} cheese!'
>>> list(template) ['Try some ', Interpolation('Stilton', 'variety', None, ''), ' cheese!']
It's easy to write (or call) code to process !Template instances. For example, here's a function that renders static parts lowercase and ~string.templatelib.Interpolation instances uppercase:
from string.templatelib import Interpolation
def lower_upper(template):
"""Render static parts lowercase and interpolations uppercase."""
parts = []
for part in template:
if isinstance(part, Interpolation):
parts.append(str(part.value).upper())
else:
parts.append(part.lower())
return ''.join(parts)
name = 'Wenslydale'
template = t'Mister {name}'
assert lower_upper(template) == 'mister WENSLYDALE'
Because !Template instances distinguish between static strings and interpolations at runtime, they can be useful for sanitising user input. Writing a !html function that escapes user input in HTML is an exercise left to the reader! Template processing code can provide improved flexibility. For instance, a more advanced !html function could accept a !dict of HTML attributes directly in the template:
attributes = {'src': 'limburger.jpg', 'alt': 'lovely cheese'}
template = t'<img {attributes}>'
assert html(template) == '<img src="limburger.jpg" alt="lovely cheese" />'
Of course, template processing code does not need to return a string-like result. An even more advanced !html could return a custom type representing a DOM-like structure.
With t-strings in place, developers can write systems that sanitise SQL, make safe shell operations, improve logging, tackle modern ideas in web development (HTML, CSS, and so on), and implement lightweight custom business DSLs.
(Contributed by Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono, Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran, and Pablo Galindo Salgado in 132661.)
750.
768: Safe external debugger interface
Python 3.14 introduces a zero-overhead debugging interface that allows debuggers and profilers to safely attach to running Python processes without stopping or restarting them. This is a significant enhancement to Python's debugging capabilities, meaning that unsafe alternatives are no longer required.
The new interface provides safe execution points for attaching debugger code without modifying the interpreter's normal execution path or adding any overhead at runtime. Due to this, tools can now inspect and interact with Python applications in real-time, which is a crucial capability for high-availability systems and production environments.
For convenience, this interface is implemented in the sys.remote_exec function. For example:
import os, sys
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
script_path = f.name
f.write(f'import my_debugger; my_debugger.connect({os.getpid()})')
# Execute in process with PID 1234
print('Behold! An offering:')
sys.remote_exec(1234, script_path)
This function allows sending Python code to be executed in a target process at the next safe execution point. However, tool authors can also implement the protocol directly as described in the PEP, which details the underlying mechanisms used to safely attach to running processes.
The debugging interface has been carefully designed with security in mind and includes several mechanisms to control access:
- A
PYTHON_DISABLE_REMOTE_DEBUGenvironment variable. - A
-X disable-remote-debugcommand-line option. - A
--without-remote-debugconfigure flag to completely disable the feature at build time.
(Contributed by Pablo Galindo Salgado, Matt Wozniski, and Ivona Stojanovic in 131591.)
768.
A new type of interpreter
A new type of interpreter has been added to CPython. It uses tail calls between small C functions that implement individual Python opcodes, rather than one large C case statement. For certain newer compilers, this interpreter provides significantly better performance. Preliminary benchmarks suggest a geometric mean of 3-5% faster on the standard pyperformance benchmark suite, depending on platform and architecture. The baseline is Python 3.14 built with Clang 19, without this new interpreter.
This interpreter currently only works with Clang 19 and newer on x86-64 and AArch64 architectures. However, a future release of GCC is expected to support this as well.
This feature is opt-in for now. Enabling profile-guided optimization is highly recommended when using the new interpreter as it is the only configuration that has been tested and validated for improved performance. For further information, see --with-tail-call-interp.
[!NOTE] This is not to be confused with tail call optimization of Python functions, which is currently not implemented in CPython.
This new interpreter type is an internal implementation detail of the CPython interpreter. It doesn't change the visible behavior of Python programs at all. It can improve their performance, but doesn't change anything else.
(Contributed by Ken Jin in 128563, with ideas on how to implement this in CPython by Mark Shannon, Garrett Gu, Haoran Xu, and Josh Haberman.)
Free-threaded mode improvements
CPython's free-threaded mode (703), initially added in 3.13, has been significantly improved in Python 3.14. The implementation described in PEP 703 has been finished, including C API changes, and temporary workarounds in the interpreter were replaced with more permanent solutions. The specializing adaptive interpreter (659) is now enabled in free-threaded mode, which along with many other optimizations greatly improves its performance. The performance penalty on single-threaded code in free-threaded mode is now roughly 5-10%, depending on the platform and C compiler used.
From Python 3.14, when compiling extension modules for the free-threaded build of CPython on Windows, the preprocessor variable Py_GIL_DISABLED now needs to be specified by the build backend, as it will no longer be determined automatically by the C compiler. For a running interpreter, the setting that was used at compile time can be found using sysconfig.get_config_var.
The new -X context_aware_warnings <-X> flag controls if concurrent safe warnings control <whatsnew314-concurrent-warnings-control> is enabled. The flag defaults to true for the free-threaded build and false for the GIL-enabled build.
A new ~sys.flags.thread_inherit_context flag has been added, which if enabled means that threads created with threading.Thread start with a copy of the ~contextvars.Context() of the caller of ~threading.Thread.start. Most significantly, this makes the warning filtering context established by ~warnings.catch_warnings be "inherited" by threads (or asyncio tasks) started within that context. It also affects other modules that use context variables, such as the decimal context manager. This flag defaults to true for the free-threaded build and false for the GIL-enabled build.
(Contributed by Sam Gross, Matt Page, Neil Schemenauer, Thomas Wouters, Donghee Na, Kirill Podoprigora, Ken Jin, Itamar Oren, Brett Simmers, Dino Viehland, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, Kumar Aditya, Edgar Margffoy, and many others. Some of these contributors are employed by Meta, which has continued to provide significant engineering resources to support this project.)
Improved error messages
-
The interpreter now provides helpful suggestions when it detects typos in Python keywords. When a word that closely resembles a Python keyword is encountered, the interpreter will suggest the correct keyword in the error message. This feature helps programmers quickly identify and fix common typing mistakes. For example:
>>> whille True: ... pass Traceback (most recent call last): File "<stdin>", line 1 whille True: ^^^^^^ SyntaxError: invalid syntax. Did you mean 'while'?While the feature focuses on the most common cases, some variations of misspellings may still result in regular syntax errors. (Contributed by Pablo Galindo in
132449.) -
elifstatements that follow anelseblock now have a specific error message. (Contributed by Steele Farnsworth in129902.)>>> if who == "me": ... print("It's me!") ... else: ... print("It's not me!") ... elif who is None: ... print("Who is it?") File "<stdin>", line 5 elif who is None: ^^^^ SyntaxError: 'elif' block follows an 'else' block -
If a statement is passed to the
if_exprafterelse, or one ofpass,break, orcontinueis passed beforeif, then the error message highlights where the~python-grammar:expressionis required. (Contributed by Sergey Miryanov in129515.)>>> x = 1 if True else pass Traceback (most recent call last): File "<string>", line 1 x = 1 if True else pass ^^^^ SyntaxError: expected expression after 'else', but statement is given >>> x = continue if True else break Traceback (most recent call last): File "<string>", line 1 x = continue if True else break ^^^^^^^^ SyntaxError: expected expression before 'if', but statement is given -
When incorrectly closed strings are detected, the error message suggests that the string may be intended to be part of the string. (Contributed by Pablo Galindo in
88535.)>>> "The interesting object "The important object" is very important" Traceback (most recent call last): SyntaxError: invalid syntax. Is this intended to be part of the string? -
When strings have incompatible prefixes, the error now shows which prefixes are incompatible. (Contributed by Nikita Sobolev in
133197.)>>> ub'abc' File "<python-input-0>", line 1 ub'abc' ^^ SyntaxError: 'u' and 'b' prefixes are incompatible -
Improved error messages when using
aswith incompatible targets in:- Imports:
import ... as ... - From imports:
from ... import ... as ... - Except handlers:
except ... as ... - Pattern-match cases:
case ... as ...
(Contributed by Nikita Sobolev in
123539,123562, and123440.) - Imports:
-
Improved error message when trying to add an instance of an unhashable type to a
dictorset. (Contributed by CF Bolz-Tereick and Victor Stinner in132828.)>>> s = set() >>> s.add({'pages': 12, 'grade': 'A'}) Traceback (most recent call last): File "<python-input-1>", line 1, in <module> s.add({'pages': 12, 'grade': 'A'}) ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: cannot use 'dict' as a set element (unhashable type: 'dict') >>> d = {} >>> l = [1, 2, 3] >>> d[l] = 12 Traceback (most recent call last): File "<python-input-4>", line 1, in <module> d[l] = 12 ~^^^ TypeError: cannot use 'list' as a dict key (unhashable type: 'list') -
Improved error message when an object supporting the synchronous context manager protocol is entered using
async withinstead ofwith, and vice versa for the asynchronous context manager protocol. (Contributed by Bénédikt Tran in128398.)
784: Zstandard support in the standard library
The new compression package contains modules !compression.lzma, !compression.bz2, !compression.gzip and !compression.zlib which re-export the lzma, bz2, gzip and zlib modules respectively. The new import names under !compression are the preferred names for importing these compression modules from Python 3.14. However, the existing modules names have not been deprecated. Any deprecation or removal of the existing compression modules will occur no sooner than five years after the release of 3.14.
The new compression.zstd module provides compression and decompression APIs for the Zstandard format via bindings to Meta's zstd library. Zstandard is a widely adopted, highly efficient, and fast compression format. In addition to the APIs introduced in !compression.zstd, support for reading and writing Zstandard compressed archives has been added to the tarfile, zipfile, and shutil modules.
Here's an example of using the new module to compress some data:
from compression import zstd
import math
data = str(math.pi).encode() * 20
compressed = zstd.compress(data)
ratio = len(compressed) / len(data)
print(f"Achieved compression ratio of {ratio}")
As can be seen, the API is similar to the APIs of the !lzma and !bz2 modules.
(Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun, Victor Stinner, and Rogdham in 132983.)
784.
Asyncio introspection capabilities
Added a new command-line interface to inspect running Python processes using asynchronous tasks, available via python -m asyncio ps PID or python -m asyncio pstree PID.
The ps subcommand inspects the given process ID (PID) and displays information about currently running asyncio tasks. It outputs a task table: a flat listing of all tasks, their names, their coroutine stacks, and which tasks are awaiting them.
The pstree subcommand fetches the same information, but instead renders a visual async call tree, showing coroutine relationships in a hierarchical format. This command is particularly useful for debugging long-running or stuck asynchronous programs. It can help developers quickly identify where a program is blocked, what tasks are pending, and how coroutines are chained together.
For example given this code:
import asyncio
async def play_track(track):
await asyncio.sleep(5)
print(f'🎵 Finished: {track}')
async def play_album(name, tracks):
async with asyncio.TaskGroup() as tg:
for track in tracks:
tg.create_task(play_track(track), name=track)
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(
play_album('Sundowning', ['TNDNBTG', 'Levitate']),
name='Sundowning')
tg.create_task(
play_album('TMBTE', ['DYWTYLM', 'Aqua Regia']),
name='TMBTE')
if __name__ == '__main__':
asyncio.run(main())
Executing the new tool on the running process will yield a table like this:
python -m asyncio ps 12345
tid task id task name coroutine stack awaiter chain awaiter name awaiter id
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1935500 0x7fc930c18050 Task-1 TaskGroup._aexit -> TaskGroup.__aexit__ -> main 0x0
1935500 0x7fc930c18230 Sundowning TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
1935500 0x7fc93173fa50 TMBTE TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
1935500 0x7fc93173fdf0 TNDNBTG sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
1935500 0x7fc930d32510 Levitate sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
1935500 0x7fc930d32890 DYWTYLM sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
1935500 0x7fc93161ec30 Aqua Regia sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
or a tree like this:
python -m asyncio pstree 12345
└── (T) Task-1
└── main example.py:13
└── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
└── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) Sundowning
│ └── album example.py:8
│ └── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
│ └── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
│ ├── (T) TNDNBTG
│ │ └── play example.py:4
│ │ └── sleep Lib/asyncio/tasks.py:702
│ └── (T) Levitate
│ └── play example.py:4
│ └── sleep Lib/asyncio/tasks.py:702
└── (T) TMBTE
└── album example.py:8
└── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
└── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) DYWTYLM
│ └── play example.py:4
│ └── sleep Lib/asyncio/tasks.py:702
└── (T) Aqua Regia
└── play example.py:4
└── sleep Lib/asyncio/tasks.py:702
If a cycle is detected in the async await graph (which could indicate a programming issue), the tool raises an error and lists the cycle paths that prevent tree construction:
python -m asyncio pstree 12345
ERROR: await-graph contains cycles - cannot print a tree!
cycle: Task-2 → Task-3 → Task-2
(Contributed by Pablo Galindo, Łukasz Langa, Yury Selivanov, and Marta Gomez Macias in 91048.)
Concurrent safe warnings control
The warnings.catch_warnings context manager will now optionally use a context variable for warning filters. This is enabled by setting the ~sys.flags.context_aware_warnings flag, either with the -X command-line option or an environment variable. This gives predictable warnings control when using ~warnings.catch_warnings combined with multiple threads or asynchronous tasks. The flag defaults to true for the free-threaded build and false for the GIL-enabled build.
(Contributed by Neil Schemenauer and Kumar Aditya in 130010.)
Other language changes
- All Windows code pages are now supported as 'cpXXX' codecs on Windows. (Contributed by Serhiy Storchaka in
123803.) - Implement mixed-mode arithmetic rules combining real and complex numbers as specified by the C standard since C99. (Contributed by Sergey B Kirpichev in
69639.) - More syntax errors are now detected regardless of optimisation and the
-Ocommand-line option. This includes writes to__debug__, incorrect use ofawait, and asynchronous comprehensions outside asynchronous functions. For example,python -O -c 'assert (__debug__ := 1)'orpython -O -c 'assert await 1'now produceSyntaxErrors. (Contributed by Irit Katriel and Jelle Zijlstra in122245&121637.) - When subclassing a pure C type, the C slots for the new type are no longer replaced with a wrapped version on class creation if they are not explicitly overridden in the subclass. (Contributed by Tomasz Pytel in
132284.)
Built-ins
- The
bytes.fromhexandbytearray.fromhexmethods now accept ASCIIbytesandbytes-like objects <bytes-like object>. (Contributed by Daniel Pope in129349.) - Add class methods
float.from_numberandcomplex.from_numberto convert a number tofloatorcomplextype correspondingly. They raise aTypeErrorif the argument is not a real number. (Contributed by Serhiy Storchaka in84978.) - Support underscore and comma as thousands separators in the fractional part for floating-point presentation types of the new-style string formatting (with
formatorf-strings). (Contributed by Sergey B Kirpichev in87790.) - The
intfunction no longer delegates to~object.__trunc__. Classes that want to support conversion to!intmust implement either~object.__int__or~object.__index__. (Contributed by Mark Dickinson in119743.) - The
mapfunction now has an optional keyword-only strict flag likezipto check that all the iterables are of equal length. (Contributed by Wannes Boeykens in119793.) - The
memoryviewtype now supports subscription, making it ageneric type. (Contributed by Brian Schubert in126012.) - Using
NotImplementedin a boolean context will now raise aTypeError. This has raised aDeprecationWarningsince Python 3.9. (Contributed by Jelle Zijlstra in118767.) - Three-argument
pownow tries calling~object.__rpow__if necessary. Previously it was only called in two-argument!powand the binary power operator. (Contributed by Serhiy Storchaka in130104.) superobjects are nowcopyable <copy>andpickleable <pickle>. (Contributed by Serhiy Storchaka in125767.)
Command line and environment
-
The import time flag can now track modules that are already loaded ('cached'), via the new
-X importtime=2 <-X>. When such a module is imported, theselfandcumulativetimes are replaced by the stringcached.Values above
2for-X importtimeare now reserved for future use.(Contributed by Noah Kim and Adam Turner in
118655.) -
The command-line option
-cnow automatically dedents its code argument before execution. (Contributed by Jon Crall and Steven Sun in103998.) -
!-Jis no longer a reserved flag for Jython, and now has no special meaning. (Contributed by Adam Turner in133336.)
PEP 758: Allow except and except* expressions without brackets
The except and except* <except_star> expressions now allow brackets to be omitted when there are multiple exception types and the as clause is not used. For example:
try:
connect_to_server()
except TimeoutError, ConnectionRefusedError:
print('The network has ceased to be!')
(Contributed by Pablo Galindo and Brett Cannon in 758 and 131831.)
PEP 765: Control flow in finally blocks
The compiler now emits a SyntaxWarning when a return, break, or continue statement have the effect of leaving a finally block. This change is specified in 765.
In situations where this change is inconvenient (such as those where the warnings are redundant due to code linting), the warning filter <warning-filter> can be used to turn off all syntax warnings by adding ignore::SyntaxWarning as a filter. This can be specified in combination with a filter that converts other warnings to errors (for example, passing -Werror -Wignore::SyntaxWarning as CLI options, or setting PYTHONWARNINGS=error,ignore::SyntaxWarning).
Note that applying such a filter at runtime using the warnings module will only suppress the warning in code that is compiled after the filter is adjusted. Code that is compiled prior to the filter adjustment (for example, when a module is imported) will still emit the syntax warning.
(Contributed by Irit Katriel in 130080.)
Garbage collection
From Python 3.14.5 onwards:
The garbage collector (GC) has changed in Python 3.14.5.
Python 3.14.0-3.14.4 shipped with a new incremental GC. However, due to a number of reports of significant memory pressure in production environments, it has been reverted back to the generational GC from 3.13. This is the GC now used in Python 3.14.5 and later.
Previously in Python 3.14.0-3.14.4:
The cycle garbage collector is now incremental. This means that maximum pause times are reduced by an order of magnitude or more for larger heaps.
There are now only two generations: young and old. When gc.collect is not called directly, the GC is invoked a little less frequently. When invoked, it collects the young generation and an increment of the old generation, instead of collecting one or more generations.
The behavior of !gc.collect changes slightly:
gc.collect(1): Performs an increment of garbage collection, rather than collecting generation 1.- Other calls to
!gc.collectare unchanged.
(Contributed by Mark Shannon in 108362.)
Default interactive shell
-
The default
interactiveshell now highlights Python syntax. The feature is enabled by default, save ifPYTHON_BASIC_REPLor any other environment variable that disables colour is set. Seeusing-on-controlling-colorfor details.The default color theme for syntax highlighting strives for good contrast and exclusively uses the 4-bit VGA standard ANSI color codes for maximum compatibility. The theme can be customized using an experimental API
!_colorize.set_theme. This can be called interactively or in thePYTHONSTARTUPscript. Note that this function has no stability guarantees, and may change or be removed.(Contributed by Łukasz Langa in
131507.) -
The default
interactiveshell now supports import auto-completion. This means that typingimport coand pressing<Tab>will suggest modules starting withco. Similarly, typingfrom concurrent import iwill suggest submodules ofconcurrentstarting withi. Note that autocompletion of module attributes is not currently supported. (Contributed by Tomas Roun in69605.)
New modules
annotationlib: For introspectingannotations <annotation>. SeePEP 749 <whatsnew314-deferred-annotations>for more details. (Contributed by Jelle Zijlstra in119180.)compression(includingcompression.zstd): A package for compression-related modules, including a new module to support the Zstandard compression format. SeePEP 784 <whatsnew314-zstandard>for more details. (Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun, Victor Stinner, and Rogdham in132983.)concurrent.interpreters: Support for multiple interpreters in the standard library. SeePEP 734 <whatsnew314-multiple-interpreters>for more details. (Contributed by Eric Snow in134939.)string.templatelib: Support for template string literals (t-strings). SeePEP 750 <whatsnew314-template-string-literals>for more details. (Contributed by Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono, Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran, and Pablo Galindo Salgado in132661.)
Improved modules
argparse
- The default value of the
program name <prog>forargparse.ArgumentParsernow reflects the way the Python interpreter was instructed to find the__main__module code. (Contributed by Serhiy Storchaka and Alyssa Coghlan in66436.) - Introduced the optional suggest_on_error parameter to
argparse.ArgumentParser, enabling suggestions for argument choices and subparser names if mistyped by the user. (Contributed by Savannah Ostrowski in124456.) - Enable color for help text, which can be disabled with the optional color parameter to
argparse.ArgumentParser. This can also be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in130645.)
ast
- Add
~ast.compare, a function for comparing two ASTs. (Contributed by Batuhan Taskaya and Jeremy Hylton in60191.) - Add support for
copy.replacefor AST nodes. (Contributed by Bénédikt Tran in121141.) - Docstrings are now removed from an optimized AST in optimization level 2. (Contributed by Irit Katriel in
123958.) - The
reproutput for AST nodes now includes more information. (Contributed by Tomas Roun in116022.) - When called with an AST as input, the
~ast.parsefunction now always verifies that the root node type is appropriate. (Contributed by Irit Katriel in130139.) - Add new options to the command-line interface:
--feature-version <ast --feature-version>,--optimize <ast --optimize>, and--show-empty <ast --show-empty>. (Contributed by Semyon Moroz in133367.)
asyncio
-
The function and methods named
!create_tasknow take an arbitrary list of keyword arguments. All keyword arguments are passed to the~asyncio.Taskconstructor or the custom task factory. (See~asyncio.loop.set_task_factoryfor details.) Thenameandcontextkeyword arguments are no longer special; the name should now be set using thenamekeyword argument of the factory, andcontextmay beNone.This affects the following function and methods:
asyncio.create_task,asyncio.loop.create_task,asyncio.TaskGroup.create_task.(Contributed by Thomas Grainger in
128307.) -
There are two new utility functions for introspecting and printing a program's call graph:
~asyncio.capture_call_graphand~asyncio.print_call_graph. SeeAsyncio introspection capabilities <whatsnew314-asyncio-introspection>for more details. (Contributed by Yury Selivanov, Pablo Galindo Salgado, and Łukasz Langa in91048.)
calendar
- By default, today's date is highlighted in color in
calendar'scommand-line <calendar-cli>text output. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in128317.)
concurrent.futures
-
Add a new executor class,
~concurrent.futures.InterpreterPoolExecutor, which exposes multiple Python interpreters in the same process ('subinterpreters') to Python code. This uses a pool of independent Python interpreters to execute calls asynchronously.This is separate from the new
~concurrent.interpretersmodule introduced byPEP 734 <whatsnew314-multiple-interpreters>. (Contributed by Eric Snow in124548.)
-
On Unix platforms other than macOS,
'forkserver' <multiprocessing-start-method-forkserver>is now the defaultstart method <multiprocessing-start-methods>for~concurrent.futures.ProcessPoolExecutor(replacing'fork' <multiprocessing-start-method-fork>). This change does not affect Windows or macOS, where'spawn' <multiprocessing-start-method-spawn>remains the default start method.If the threading incompatible fork method is required, you must explicitly request it by supplying a multiprocessing context mp_context to
~concurrent.futures.ProcessPoolExecutor.See
forkserver restrictions <multiprocessing-programming-forkserver>for information and differences with the fork method and how this change may affect existing code with mutable global shared variables and/or shared objects that can not be automaticallypickled <pickle>.(Contributed by Gregory P. Smith in
84559.) -
Add two new methods to
~concurrent.futures.ProcessPoolExecutor,~concurrent.futures.ProcessPoolExecutor.terminate_workersand~concurrent.futures.ProcessPoolExecutor.kill_workers, as ways to terminate or kill all living worker processes in the given pool. (Contributed by Charles Machalow in130849.) -
Add the optional buffersize parameter to
Executor.map <concurrent.futures.Executor.map>to limit the number of submitted tasks whose results have not yet been yielded. If the buffer is full, iteration over the iterables pauses until a result is yielded from the buffer. (Contributed by Enzo Bonnal and Josh Rosenberg in74028.)
configparser
!configparserwill no longer write config files it cannot read, to improve security. Attempting to~configparser.ConfigParser.writekeys containing delimiters or beginning with the section header pattern will raise an~configparser.InvalidWriteError. (Contributed by Jacob Lincoln in129270.)
contextvars
- Support the
context managerprotocol for~contextvars.Tokenobjects. (Contributed by Andrew Svetlov in129889.)
ctypes
- The layout of
bit fields <ctypes-bit-fields-in-structures-unions>in~ctypes.Structureand~ctypes.Unionobjects is now a closer match to platform defaults (GCC/Clang or MSVC). In particular, fields no longer overlap. (Contributed by Matthias Görgens in97702.) - The
.Structure._layout_class attribute can now be set to help match a non-default ABI. (Contributed by Petr Viktorin in97702.) - The class of
~ctypes.Structure/~ctypes.Unionfield descriptors is now available as~ctypes.CField, and has new attributes to aid debugging and introspection. (Contributed by Petr Viktorin in128715.) - On Windows, the
~ctypes.COMErrorexception is now public. (Contributed by Jun Komoda in126686.) - On Windows, the
~ctypes.CopyComPointerfunction is now public. (Contributed by Jun Komoda in127275.) - Add
~ctypes.memoryview_at, a function to create amemoryviewobject that refers to the supplied pointer and length. This works likectypes.string_atexcept it avoids a buffer copy, and is typically useful when implementing pure Python callback functions that are passed dynamically-sized buffers. (Contributed by Rian Hunter in112018.) - Complex types,
~ctypes.c_float_complex,~ctypes.c_double_complex, and~ctypes.c_longdouble_complex, are now available if both the compiler and thelibffilibrary support complex C types. (Contributed by Sergey B Kirpichev in61103.) - Add
ctypes.util.dllistfor listing the shared libraries loaded by the current process. (Contributed by Brian Ward in119349.) - Move
ctypes.POINTERtypes cache from a global internal cache (_pointer_type_cache) to the_CData.__pointer_type__ <ctypes._CData.__pointer_type__>attribute of the corresponding!ctypestypes. This will stop the cache from growing without limits in some situations. (Contributed by Sergey Miryanov in100926.) - The
~ctypes.py_objecttype now supports subscription, making it ageneric type. (Contributed by Brian Schubert in132168.) !ctypesnow supportsfree-threading builds <free threading>. (Contributed by Kumar Aditya and Peter Bierma in127945.)
curses
- Add the
~curses.assume_default_colorsfunction, a refinement of the~curses.use_default_colorsfunction which allows changing the color pair0. (Contributed by Serhiy Storchaka in133139.)
datetime
- Add the
~datetime.date.strptimemethod to thedatetime.dateanddatetime.timeclasses. (Contributed by Wannes Boeykens in41431.)
decimal
- Add
.Decimal.from_numberas an alternative constructor for~decimal.Decimal. (Contributed by Serhiy Storchaka in121798.) - Expose
~decimal.IEEEContextto support creation of contexts corresponding to the IEEE 754 (2008) decimal interchange formats. (Contributed by Sergey B Kirpichev in53032.)
difflib
- Comparison pages with highlighted changes generated by the
~difflib.HtmlDiffclass now support 'dark mode'. (Contributed by Jiahao Li in129939.)
dis
-
Add support for rendering full source location information of
instructions <dis.Instruction>, rather than only the line number. This feature is added to the following interfaces via the show_positions keyword argument:dis.Bytecodedis.disdis.distbdis.disassemble
This feature is also exposed via
dis --show-positions. (Contributed by Bénédikt Tran in123165.) -
Add the
dis --specializedcommand-line option to show specialized bytecode. (Contributed by Bénédikt Tran in127413.)
errno
- Add the
~errno.EHWPOISONerror code constant. (Contributed by James Roy in126585.)
faulthandler
- Add support for printing the C stack trace on systems that
support it <c-stack-compatibility>via the new~faulthandler.dump_c_stackfunction or via the c_stack argument infaulthandler.enable. (Contributed by Peter Bierma in127604.)
fnmatch
- Add
~fnmatch.filterfalse, a function to reject names matching a given pattern. (Contributed by Bénédikt Tran in74598.)
fractions
- A
~fractions.Fractionobject may now be constructed from any object with the!as_integer_ratiomethod. (Contributed by Serhiy Storchaka in82017.) - Add
.Fraction.from_numberas an alternative constructor for~fractions.Fraction. (Contributed by Serhiy Storchaka in121797.)
functools
- Add the
~functools.Placeholdersentinel. This may be used with the~functools.partialor~functools.partialmethodfunctions to reserve a place for positional arguments in the returnedpartial object <partial-objects>. (Contributed by Dominykas Grigonis in119127.) - Allow the initial parameter of
~functools.reduceto be passed as a keyword argument. (Contributed by Sayandip Dutta in125916.)
getopt
- Add support for options with optional arguments. (Contributed by Serhiy Storchaka in
126374.) - Add support for returning intermixed options and non-option arguments in order. (Contributed by Serhiy Storchaka in
126390.)
getpass
- Support keyboard feedback in the
~getpass.getpassfunction via the keyword-only optional argument echo_char. Placeholder characters are rendered whenever a character is entered, and removed when a character is deleted. (Contributed by Semyon Moroz in77065.)
graphlib
- Allow
.TopologicalSorter.prepareto be called more than once as long as sorting has not started. (Contributed by Daniel Pope in130914.)
heapq
- The
!heapqmodule has improved support for working with max-heaps, via the following new functions:~heapq.heapify_max~heapq.heappush_max~heapq.heappop_max~heapq.heapreplace_max~heapq.heappushpop_max
hmac
- Add a built-in implementation for HMAC (
2104) using formally verified code from the HACL* project. This implementation is used as a fallback when the OpenSSL implementation of HMAC is not available. (Contributed by Bénédikt Tran in99108.)
http
-
Directory lists and error pages generated by the
http.servermodule allow the browser to apply its default dark mode. (Contributed by Yorik Hansen in123430.) -
The
http.servermodule now supports serving over HTTPS using thehttp.server.HTTPSServerclass. This functionality is exposed by the command-line interface (python -m http.server) through the following options:--tls-cert \<path\> <http.server --tls-cert>: Path to the TLS certificate file.--tls-key \<path\> <http.server --tls-key>: Optional path to the private key file.--tls-password-file \<path\> <http.server --tls-password-file>: Optional path to the password file for the private key.
(Contributed by Semyon Moroz in
85162.)
imaplib
- Add
.IMAP4.idle, implementing the IMAP4IDLEcommand as defined in2177. (Contributed by Forest in55454.)
inspect
~inspect.signaturetakes a new argument annotation_format to control theannotationlib.Formatused for representing annotations. (Contributed by Jelle Zijlstra in101552.).Signature.formattakes a new argument unquote_annotations. If true, stringannotations <annotation>are displayed without surrounding quotes. (Contributed by Jelle Zijlstra in101552.)- Add function
~inspect.ispackageto determine whether an object is apackageor not. (Contributed by Zhikang Yan in125634.)
io
- Reading text from a non-blocking stream with
readmay now raise aBlockingIOErrorif the operation cannot immediately return bytes. (Contributed by Giovanni Siragusa in109523.) - Add the
~io.Readerand~io.Writerprotocols as simpler alternatives to the pseudo-protocolstyping.IO,typing.TextIO, andtyping.BinaryIO. (Contributed by Sebastian Rittau in127648.)
json
- Add exception notes for JSON serialization errors that allow identifying the source of the error. (Contributed by Serhiy Storchaka in
122163.) - Allow using the
jsonmodule as a script using the-mswitch:python -m json. This is now preferred topython -m json.tool, which issoft deprecated. See theJSON command-line interface <json-commandline>documentation. (Contributed by Trey Hunner in122873.) - By default, the output of the
JSON command-line interface <json-commandline>is highlighted in color. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Tomas Roun in131952.)
linecache
~linecache.getlinecan now retrieve source code for frozen modules. (Contributed by Tian Gao in131638.)
logging.handlers
~logging.handlers.QueueListenerobjects now support thecontext managerprotocol. (Contributed by Charles Machalow in132106.)QueueListener.start <logging.handlers.QueueListener.start>now raises aRuntimeErrorif the listener is already started. (Contributed by Charles Machalow in132106.)
math
- Added more detailed error messages for domain errors in the module. (Contributed by Charlie Zhao and Sergey B Kirpichev in
101410.)
mimetypes
-
Add a public
command-line <mimetypes-cli>for the module, invoked viapython -m mimetypes. (Contributed by Oleg Iarygin and Hugo van Kemenade in93096.) -
Add several new MIME types based on RFCs and common usage:
Microsoft and
8081MIME types for fonts- Embedded OpenType:
application/vnd.ms-fontobject - OpenType Layout (OTF)
font/otf - TrueType:
font/ttf - WOFF 1.0
font/woff - WOFF 2.0
font/woff2
9559MIME types for Matroska audiovisual data container structures- audio with no video:
audio/matroska(.mka) - video:
video/matroska(.mkv) - stereoscopic video:
video/matroska-3d(.mk3d)
Images with RFCs
1494: CCITT Group 3 (.g3)3362: Real-time Facsimile, T.38 (.t38)3745: JPEG 2000 (.jp2), extension (.jpx) and compound (.jpm)3950: Tag Image File Format Fax eXtended, TIFF-FX (.tfx)4047: Flexible Image Transport System (.fits)7903: Enhanced Metafile (.emf) and Windows Metafile (.wmf)
Other MIME type additions and changes
2361: Change type for.avitovideo/vnd.aviand for.wavtoaudio/vnd.wave4337: Add MPEG-4audio/mp4(.m4a)5334: Add Ogg media (.oga,.oggand.ogx)6713: Add gzipapplication/gzip(.gz)9639: Add FLACaudio/flac(.flac)9512application/yamlMIME type for YAML files (.yamland.yml)- Add 7z
application/x-7z-compressed(.7z) - Add Android Package
application/vnd.android.package-archive(.apk) when not strict - Add deb
application/x-debian-package(.deb) - Add glTF binary
model/gltf-binary(.glb) - Add glTF JSON/ASCII
model/gltf+json(.gltf) - Add M4V
video/x-m4v(.m4v) - Add PHP
application/x-httpd-php(.php) - Add RAR
application/vnd.rar(.rar) - Add RPM
application/x-rpm(.rpm) - Add STL
model/stl(.stl) - Add Windows Media Video
video/x-ms-wmv(.wmv) - De facto: Add WebM
audio/webm(.weba) - ECMA-376: Add
.docx,.pptxand.xlsxtypes - OASIS: Add OpenDocument
.odg,.odp,.odsand.odttypes - W3C: Add EPUB
application/epub+zip(.epub)
(Contributed by Sahil Prajapati and Hugo van Kemenade in
84852, by Sasha "Nelie" Chernykh and Hugo van Kemenade in132056, and by Hugo van Kemenade in89416,85957, and129965.) - Embedded OpenType:
multiprocessing
-
On Unix platforms other than macOS,
'forkserver' <multiprocessing-start-method-forkserver>is now the defaultstart method <multiprocessing-start-methods>(replacing'fork' <multiprocessing-start-method-fork>). This change does not affect Windows or macOS, where'spawn' <multiprocessing-start-method-spawn>remains the default start method.If the threading incompatible fork method is required, you must explicitly request it via a context from
~multiprocessing.get_context(preferred) or change the default via~multiprocessing.set_start_method.See
forkserver restrictions <multiprocessing-programming-forkserver>for information and differences with the fork method and how this change may affect existing code with mutable global shared variables and/or shared objects that can not be automaticallypickled <pickle>.(Contributed by Gregory P. Smith in
84559.) -
multiprocessing's'forkserver'start method now authenticates its control socket to avoid solely relying on filesystem permissions to restrict what other processes could cause the forkserver to spawn workers and run code. (Contributed by Gregory P. Smith for97514.) -
The
multiprocessing proxy objects <multiprocessing-proxy_objects>for list and dict types gain previously overlooked missing methods:!clearand!copyfor proxies oflist~dict.fromkeys,reversed(d),d | {},{} | d,d |= {'b': 2}for proxies ofdict
(Contributed by Roy Hyunjin Han for
103134.) -
Add support for shared
setobjects via.SyncManager.set. Thesetin~multiprocessing.Managermethod is now available. (Contributed by Mingyu Park in129949.) -
Add the
~multiprocessing.Process.interrupttomultiprocessing.Processobjects, which terminates the child process by sending~signal.SIGINT. This enablesfinallyclauses to print a stack trace for the terminated process. (Contributed by Artem Pulkin in131913.)
operator
- Add
~operator.is_noneand~operator.is_not_noneas a pair of functions, such thatoperator.is_none(obj)is equivalent toobj is Noneandoperator.is_not_none(obj)is equivalent toobj is not None. (Contributed by Raymond Hettinger and Nico Mexis in115808.)
os
- Add the
~os.reload_environfunction to updateos.environandos.environbwith changes to the environment made byos.putenv, byos.unsetenv, or made outside Python in the same process. (Contributed by Victor Stinner in120057.) - Add the
~os.SCHED_DEADLINEand~os.SCHED_NORMALconstants to the!osmodule. (Contributed by James Roy in127688.) - Add the
~os.readintofunction to read into abuffer object <bufferobjects>from a file descriptor. (Contributed by Cody Maloney in129205.)
os.path
- The strict parameter to
~os.path.realpathaccepts a new value,~os.path.ALLOW_MISSING. If used, errors other thanFileNotFoundErrorwill be re-raised; the resulting path can be missing but it will be free of symlinks. (Contributed by Petr Viktorin for2025-4517.)
pathlib
-
Add methods to
pathlib.Pathto recursively copy or move files and directories:~pathlib.Path.copycopies a file or directory tree to a destination.~pathlib.Path.copy_intocopies into a destination directory.~pathlib.Path.movemoves a file or directory tree to a destination.~pathlib.Path.move_intomoves into a destination directory.
(Contributed by Barney Gale in
73991.) -
Add the
~pathlib.Path.infoattribute, which stores an object implementing the newpathlib.types.PathInfoprotocol. The object supports querying the file type and internally caching~os.statresults. Path objects generated by~pathlib.Path.iterdirare initialized with file type information gleaned from scanning the parent directory. (Contributed by Barney Gale in125413.)
pdb
-
The
pdbmodule now supports remote attaching to a running Python process using a new-p PID <pdb --pid>command-line option:python -m pdb -p 1234This will connect to the Python process with the given PID and allow you to debug it interactively. Notice that due to how the Python interpreter works attaching to a remote process that is blocked in a system call or waiting for I/O will only work once the next bytecode instruction is executed or when the process receives a signal.
This feature uses
PEP 768 <whatsnew314-remote-debugging>and the newsys.remote_execfunction to attach to the remote process and send the PDB commands to it.(Contributed by Matt Wozniski and Pablo Galindo in
131591.) -
Hardcoded breakpoints (
breakpointand~pdb.set_trace) now reuse the most recent~pdb.Pdbinstance that calls~pdb.Pdb.set_trace, instead of creating a new one each time. As a result, all the instance specific data likedisplayandcommandsare preserved across hardcoded breakpoints. (Contributed by Tian Gao in121450.) -
Add a new argument mode to
pdb.Pdb. Disable therestartcommand whenpdbis ininlinemode. (Contributed by Tian Gao in123757.) -
A confirmation prompt will be shown when the user tries to quit
pdbininlinemode.y,Y,<Enter>orEOFwill confirm the quit and callsys.exit, instead of raisingbdb.BdbQuit. (Contributed by Tian Gao in124704.) -
Inline breakpoints like
breakpointorpdb.set_tracewill always stop the program at calling frame, ignoring theskippattern (if any). (Contributed by Tian Gao in130493.) -
<tab>at the beginning of the line inpdbmulti-line input will fill in a 4-space indentation now, instead of inserting a\tcharacter. (Contributed by Tian Gao in130471.) -
Auto-indent is introduced in
pdbmulti-line input. It will either keep the indentation of the last line or insert a 4-space indentation when it detects a new code block. (Contributed by Tian Gao in133350.) -
$_asynctaskis added to access the current asyncio task if applicable. (Contributed by Tian Gao in124367.) -
pdb.set_trace_asyncis added to support debugging asyncio coroutines.awaitstatements are supported with this function. (Contributed by Tian Gao in132576.) -
Source code displayed in
pdbwill be syntax-highlighted. This feature can be controlled using the same methods as the defaultinteractiveshell, in addition to the newly addedcolorizeargument ofpdb.Pdb. (Contributed by Tian Gao and Łukasz Langa in133355.)
pickle
- Set the default protocol version on the
picklemodule to 5. For more details, seepickle protocols <pickle-protocols>. - Add exception notes for pickle serialization errors that allow identifying the source of the error. (Contributed by Serhiy Storchaka in
122213.)
platform
- Add
~platform.invalidate_caches, a function to invalidate cached results in the!platformmodule. (Contributed by Bénédikt Tran in122549.)
pydoc
Annotations <annotation>in help output are now usually displayed in a format closer to that in the original source. (Contributed by Jelle Zijlstra in101552.)
re
- Support
\zas a synonym for\Zinregular expressions <re>. It is interpreted unambiguously in many other regular expression engines, unlike\Z, which has subtly different behavior. (Contributed by Serhiy Storchaka in133306.) \Binregular expression <re>now matches the empty input string, meaning that it is now always the opposite of\b. (Contributed by Serhiy Storchaka in124130.)
socket
- Improve and fix support for Bluetooth sockets.
- Fix support of Bluetooth sockets on NetBSD and DragonFly BSD. (Contributed by Serhiy Storchaka in
132429.) - Fix support for
~socket.BTPROTO_HCIon FreeBSD. (Contributed by Victor Stinner in111178.) - Add support for
~socket.BTPROTO_SCOon FreeBSD. (Contributed by Serhiy Storchaka in85302.) - Add support for cid and bdaddr_type in the address for
~socket.BTPROTO_L2CAPon FreeBSD. (Contributed by Serhiy Storchaka in132429.) - Add support for channel in the address for
~socket.BTPROTO_HCIon Linux. (Contributed by Serhiy Storchaka in70145.) - Accept an integer as the address for
~socket.BTPROTO_HCIon Linux. (Contributed by Serhiy Storchaka in132099.) - Return cid in
~socket.socket.getsocknamefor~socket.BTPROTO_L2CAP. (Contributed by Serhiy Storchaka in132429.) - Add many new constants. (Contributed by Serhiy Storchaka in
132734.)
- Fix support of Bluetooth sockets on NetBSD and DragonFly BSD. (Contributed by Serhiy Storchaka in
ssl
- Indicate through the
~ssl.HAS_PHABoolean whether the!sslmodule supports TLSv1.3 post-handshake client authentication (PHA). (Contributed by Will Childs-Klein in128036.)
struct
- Support the
float complexanddouble complexC types in thestructmodule (formatting characters'F'and'D'respectively). (Contributed by Sergey B Kirpichev in121249.)
symtable
-
Expose the following
~symtable.Symbolmethods:~symtable.Symbol.is_comp_cell~symtable.Symbol.is_comp_iter~symtable.Symbol.is_free_class
(Contributed by Bénédikt Tran in
120029.)
sys
- The previously undocumented special function
sys.getobjects, which only exists in specialized builds of Python, may now return objects from other interpreters than the one it's called in. (Contributed by Eric Snow in125286.) - Add
sys._is_immortalfor determining if an object isimmortal. (Contributed by Peter Bierma in128509.) - On FreeBSD,
sys.platformno longer contains the major version number. It is always'freebsd', instead of'freebsd13'or'freebsd14'. (Contributed by Michael Osipov in129393.) - Raise
DeprecationWarningforsys._clear_type_cache. This function was deprecated in Python 3.13 but it didn't raise a runtime warning. - Add
sys.remote_execto implement the new external debugger interface. SeePEP 768 <whatsnew314-remote-debugging>for details. (Contributed by Pablo Galindo Salgado, Matt Wozniski, and Ivona Stojanovic in131591.) - Add the
sys._jitnamespace, containing utilities for introspecting just-in-time compilation. (Contributed by Brandt Bucher in133231.)
sys.monitoring
- Add two new monitoring events,
BRANCH_LEFTandBRANCH_RIGHT. These replace and deprecate the!BRANCHevent. (Contributed by Mark Shannon in122548.) - Add
sys.monitoring.clear_tool_idto unregister all events and callback functions associated with a tool identifier.sys.monitoring.free_tool_idnow calls it before releasing the tool identifier, instead of leaving its events and callbacks registered. (Contributed by Tian Gao in116750.)
sysconfig
- Add
ABIFLAGSkey to~sysconfig.get_config_varson Windows. (Contributed by Xuehai Pan in131799.)
tarfile
~tarfile.data_filternow normalizes symbolic link targets in order to avoid path traversal attacks. (Contributed by Petr Viktorin in127987and2025-4138.)~tarfile.TarFile.extractallnow skips fixing up directory attributes when a directory was removed or replaced by another kind of file. (Contributed by Petr Viktorin in127987and2024-12718.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallnow (re-)apply the extraction filter when substituting a link (hard or symbolic) with a copy of another archive member, and when fixing up directory attributes. The former raises a new exception,~tarfile.LinkFallbackError. (Contributed by Petr Viktorin for2025-4330and2024-12718.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallno longer extract rejected members when~tarfile.TarFile.errorlevelis zero. (Contributed by Matt Prodani and Petr Viktorin in112887and2025-4435.)
threading
threading.Thread.startnow sets the operating system thread name tothreading.Thread.name. (Contributed by Victor Stinner in59705.)
tkinter
- Make
tkinterwidget methods!afterand!after_idleaccept keyword arguments. (Contributed by Zhikang Yan in126899.) - Add ability to specify a name for
!tkinter.OptionMenuand!tkinter.ttk.OptionMenu. (Contributed by Zhikang Yan in130482.)
turtle
- Add context managers for
turtle.fill,turtle.poly, andturtle.no_animation. (Contributed by Marie Roald and Yngve Mardal Moe in126350.)
types
types.UnionTypeis now an alias fortyping.Union. Seebelow <whatsnew314-typing-union>for more details. (Contributed by Jelle Zijlstra in105499.)
typing
-
The
types.UnionTypeandtyping.Uniontypes are now aliases for each other, meaning that both old-style unions (created withUnion[int, str]) and new-style unions (int | str) now create instances of the same runtime type. This unifies the behavior between the two syntaxes, but leads to some differences in behavior that may affect users who introspect types at runtime:- Both syntaxes for creating a union now produce the same string representation in
repr. For example,repr(Union[int, str])is now"int | str"instead of"typing.Union[int, str]". - Unions created using the old syntax are no longer cached. Previously, running
Union[int, str]multiple times would return the same object (Union[int, str] is Union[int, str]would beTrue), but now it will return two different objects. Use==to compare unions for equality, notis. New-style unions have never been cached this way. This change could increase memory usage for some programs that use a large number of unions created by subscriptingtyping.Union. However, several factors offset this cost: unions used in annotations are no longer evaluated by default in Python 3.14 because of649; an instance oftypes.UnionTypeis itself much smaller than the object returned byUnion[]was on prior Python versions; and removing the cache also saves some space. It is therefore unlikely that this change will cause a significant increase in memory usage for most users. - Previously, old-style unions were implemented using the private class
typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers like~typing.get_originandtyping.get_argsinstead of relying on private implementation details. - It is now possible to use
typing.Unionitself inisinstancechecks. For example,isinstance(int | str, typing.Union)will returnTrue; previously this raisedTypeError. - The
!__args__attribute oftyping.Unionobjects is no longer writable. - It is no longer possible to set any attributes on
~typing.Unionobjects. This only ever worked for dunder attributes on previous versions, was never documented to work, and was subtly broken in many cases.
(Contributed by Jelle Zijlstra in
105499.) - Both syntaxes for creating a union now produce the same string representation in
-
~typing.TypeAliasTypenow supports star unpacking.
unicodedata
- The Unicode database has been updated to Unicode 16.0.0.
unittest
-
unittestoutput is now colored by default. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in127221.) -
unittest discovery supports
namespace packageas start directory again. It was removed in Python 3.11. (Contributed by Jacob Walls in80958.) -
A number of new methods were added in the
~unittest.TestCaseclass that provide more specialized tests.~unittest.TestCase.assertHasAttrand~unittest.TestCase.assertNotHasAttrcheck whether the object has a particular attribute.~unittest.TestCase.assertIsSubclassand~unittest.TestCase.assertNotIsSubclasscheck whether the object is a subclass of a particular class, or of one of a tuple of classes.~unittest.TestCase.assertStartsWith,~unittest.TestCase.assertNotStartsWith,~unittest.TestCase.assertEndsWithand~unittest.TestCase.assertNotEndsWithcheck whether the Unicode or byte string starts or ends with particular strings.
(Contributed by Serhiy Storchaka in
71339.)
urllib
-
Upgrade HTTP digest authentication algorithm for
urllib.requestby supporting SHA-256 digest authentication as specified in7616. (Contributed by Calvin Bui in128193.) -
Improve ergonomics and standards compliance when parsing and emitting
file:URLs.In
~urllib.request.url2pathname:- Accept a complete URL when the new require_scheme argument is set to true.
- Discard URL authority if it matches the local hostname.
- Discard URL authority if it resolves to a local IP address when the new resolve_host argument is set to true.
- Discard URL query and fragment components.
- Raise
~urllib.error.URLErrorif a URL authority isn't local, except on Windows where we return a UNC path as before.
In
~urllib.request.pathname2url:- Return a complete URL when the new add_scheme argument is set to true.
- Include an empty URL authority when a path begins with a slash. For example, the path
/etc/hostsis converted to the URL///etc/hosts.
On Windows, drive letters are no longer converted to uppercase, and
:characters not following a drive letter no longer cause anOSErrorexception to be raised.(Contributed by Barney Gale in
125866.)
uuid
- Add support for UUID versions 6, 7, and 8 via
~uuid.uuid6,~uuid.uuid7, and~uuid.uuid8respectively, as specified in9562. (Contributed by Bénédikt Tran in89083.) ~uuid.NILand~uuid.MAXare now available to represent the Nil and Max UUID formats as defined by9562. (Contributed by Nick Pope in128427.)- Allow generating multiple UUIDs simultaneously on the command-line via
python -m uuid --count <uuid --count>. (Contributed by Simon Legner in131236.)
webbrowser
-
Names in the
BROWSERenvironment variable can now refer to already registered browsers for thewebbrowsermodule, instead of always generating a new browser command.This makes it possible to set
BROWSERto the value of one of the supported browsers on macOS.
zipfile
- Added
ZipInfo._for_archive <zipfile.ZipInfo._for_archive>, a method to resolve suitable defaults for a~zipfile.ZipInfoobject as used byZipFile.writestr <zipfile.ZipFile.writestr>. (Contributed by Bénédikt Tran in123424.) .ZipFile.writestrnow respects theSOURCE_DATE_EPOCHenvironment variable in order to better support reproducible builds. (Contributed by Jiahao Li in91279.)
Optimizations
-
The import time for several standard library modules has been improved, including
annotationlib,ast,asyncio,base64,cmd,csv,gettext,importlib.util,locale,mimetypes,optparse,pickle,pprint,pstats,shlex,socket,string,subprocess,threading,tomllib,types, andzipfile.(Contributed by Adam Turner, Bénédikt Tran, Chris Markiewicz, Eli Schwartz, Hugo van Kemenade, Jelle Zijlstra, and others in
118761.) -
The interpreter now avoids some reference count modifications internally when it's safe to do so. This can lead to different values being returned from
sys.getrefcountandPy_REFCNTcompared to previous versions of Python. Seebelow <whatsnew314-refcount>for details.
asyncio
- Standard benchmark results have improved by 10-20% following the implementation of a new per-thread doubly linked list for
native tasks <asyncio.Task>, also reducing memory usage. This enables external introspection tools such aspython -m asyncio pstree <whatsnew314-asyncio-introspection>to introspect the call graph of asyncio tasks running in all threads. (Contributed by Kumar Aditya in107803.) - The module now has first class support for
free-threading builds <free threading>. This enables parallel execution of multiple event loops across different threads, scaling linearly with the number of threads. (Contributed by Kumar Aditya in128002.)
base64
~base64.b16decodeis now up to six times faster. (Contributed by Bénédikt Tran, Chris Markiewicz, and Adam Turner in118761.)
bdb
- The basic debugger now has a
sys.monitoring-based backend, which can be selected via the passing'monitoring'to the~bdb.Bdbclass's new backend parameter. (Contributed by Tian Gao in124533.)
difflib
- The
~difflib.IS_LINE_JUNKfunction is now up to twice as fast. (Contributed by Adam Turner and Semyon Moroz in130167.)
gc
-
From Python 3.14.5 onwards:
Python 3.14.0-3.14.4 shipped with a new incremental garbage collector. However, due to a number of reports of significant memory pressure in production environments, it has been reverted back to the generational GC from 3.13. This is the GC now used in Python 3.14.5 and later.
-
Previously in Python 3.14.0-3.14.4:
The new
incremental garbage collector <whatsnew314-incremental-gc>means that maximum pause times are reduced by an order of magnitude or more for larger heaps.Because of this optimization, the meaning of the results of
~gc.get_thresholdand~gc.set_thresholdhave changed, along with~gc.get_countand~gc.get_stats.- For backwards compatibility,
~gc.get_thresholdcontinues to return a three-item tuple. The first value is the threshold for young collections, as before; the second value determines the rate at which the old collection is scanned (the default is 10, and higher values mean that the old collection is scanned more slowly). The third value is now meaningless and is always zero. ~gc.set_thresholdnow ignores any items after the second.~gc.get_countand~gc.get_statscontinue to return the same format of results. The only difference is that instead of the results referring to the young, aging and old generations, the results refer to the young generation and the aging and collecting spaces of the old generation.
In summary, code that attempted to manipulate the behavior of the cycle GC may not work exactly as intended, but it is very unlikely to be harmful. All other code will work just fine.
(Contributed by Mark Shannon in
108362.) - For backwards compatibility,
io
- Opening and reading files now executes fewer system calls. Reading a small operating system cached file in full is up to 15% faster. (Contributed by Cody Maloney and Victor Stinner in
120754and90102.)
pathlib
Path.read_bytes <pathlib.Path.read_bytes>now uses unbuffered mode to open files, which is between 9% and 17% faster to read in full. (Contributed by Cody Maloney in120754.)
pdb
pdbnow supports two backends, based on eithersys.settraceorsys.monitoring. Using thepdb CLI <pdb-cli>orbreakpointwill always use thesys.monitoringbackend. Explicitly instantiatingpdb.Pdband its derived classes will use thesys.settracebackend by default, which is configurable. (Contributed by Tian Gao in124533.)
textwrap
- Optimize the
~textwrap.dedentfunction, improving performance by an average of 2.4x, with larger improvements for bigger inputs, and fix a bug with incomplete normalization of blank lines with whitespace characters other than space and tab.
uuid
~uuid.uuid3and~uuid.uuid5are now both roughly 40% faster for 16-byte names and 20% faster for 1024-byte names. Performance for longer names remains unchanged. (Contributed by Bénédikt Tran in128150.)~uuid.uuid4is now c. 30% faster. (Contributed by Bénédikt Tran in128150.)
zlib
-
On Windows, zlib-ng is now used as the implementation of the
zlibmodule in the default binaries. There are no known incompatibilities betweenzlib-ngand the previously-usedzlibimplementation. This should result in better performance at all compression levels.It is worth noting that
zlib.Z_BEST_SPEED(1) may result in significantly less compression than the previous implementation, whilst also significantly reducing the time taken to compress.(Contributed by Steve Dower in
91349.)
Removed
argparse
- Remove the type, choices, and metavar parameters of
!BooleanOptionalAction. These have been deprecated since Python 3.12. (Contributed by Nikita Sobolev in118805.) - Calling
~argparse.ArgumentParser.add_argument_groupon an argument group now raises aValueError. Similarly,~argparse.ArgumentParser.add_argument_groupor~argparse.ArgumentParser.add_mutually_exclusive_groupon a mutually exclusive group now both raiseValueErrors. This 'nesting' was never supported, often failed to work correctly, and was unintentionally exposed through inheritance. This functionality has been deprecated since Python 3.11. (Contributed by Savannah Ostrowski in127186.)
ast
-
Remove the following classes, which have been deprecated aliases of
~ast.Constantsince Python 3.8 and have emitted deprecation warnings since Python 3.12:!Bytes!Ellipsis!NameConstant!Num!Str
As a consequence of these removals, user-defined
visit_Num,visit_Str,visit_Bytes,visit_NameConstantandvisit_Ellipsismethods on custom~ast.NodeVisitorsubclasses will no longer be called when the!NodeVisitorsubclass is visiting an AST. Define avisit_Constantmethod instead.(Contributed by Alex Waygood in
119562.) -
Remove the following deprecated properties on
ast.Constant, which were present for compatibility with the now-removed AST classes:!Constant.n!Constant.s
Use
!Constant.valueinstead. (Contributed by Alex Waygood in119562.)
asyncio
-
Remove the following classes, methods, and functions, which have been deprecated since Python 3.12:
!AbstractChildWatcher!FastChildWatcher!MultiLoopChildWatcher!PidfdChildWatcher!SafeChildWatcher!ThreadedChildWatcher!AbstractEventLoopPolicy.get_child_watcher!AbstractEventLoopPolicy.set_child_watcher!get_child_watcher!set_child_watcher
(Contributed by Kumar Aditya in
120804.) -
asyncio.get_event_loopnow raises aRuntimeErrorif there is no current event loop, and no longer implicitly creates an event loop.(Contributed by Kumar Aditya in
126353.)There's a few patterns that use
asyncio.get_event_loop, most of them can be replaced withasyncio.run.If you're running an async function, simply use
asyncio.run.Before:
async def main(): ... loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.close()After:
async def main(): ... asyncio.run(main())If you need to start something, for example, a server listening on a socket and then run forever, use
asyncio.runand anasyncio.Event.Before:
def start_server(loop): ... loop = asyncio.get_event_loop() try: start_server(loop) loop.run_forever() finally: loop.close()After:
def start_server(loop): ... async def main(): start_server(asyncio.get_running_loop()) await asyncio.Event().wait() asyncio.run(main())If you need to run something in an event loop, then run some blocking code around it, use
asyncio.Runner.Before:
async def operation_one(): ... def blocking_code(): ... async def operation_two(): ... loop = asyncio.get_event_loop() try: loop.run_until_complete(operation_one()) blocking_code() loop.run_until_complete(operation_two()) finally: loop.close()After:
async def operation_one(): ... def blocking_code(): ... async def operation_two(): ... with asyncio.Runner() as runner: runner.run(operation_one()) blocking_code() runner.run(operation_two())
- Remove
email.utils.localtime's isdst parameter, which was deprecated in and has been ignored since Python 3.12. (Contributed by Hugo van Kemenade in118798.)
importlib.abc
-
Remove deprecated
importlib.abcclasses:!ResourceReader(use~importlib.resources.abc.TraversableResources)!Traversable(use~importlib.resources.abc.Traversable)!TraversableResources(use~importlib.resources.abc.TraversableResources)
(Contributed by Jason R. Coombs and Hugo van Kemenade in
93963.)
itertools
- Remove support for copy, deepcopy, and pickle operations from
itertoolsiterators. These have emitted aDeprecationWarningsince Python 3.12. (Contributed by Raymond Hettinger in101588.)
pathlib
- Remove support for passing additional keyword arguments to
~pathlib.Path. In previous versions, any such arguments are ignored. (Contributed by Barney Gale in74033.) - Remove support for passing additional positional arguments to
.PurePath.relative_toand~pathlib.PurePath.is_relative_to. In previous versions, any such arguments are joined onto other. (Contributed by Barney Gale in78707.)
pkgutil
- Remove the
!get_loaderand!find_loaderfunctions, which have been deprecated since Python 3.12. (Contributed by Bénédikt Tran in97850.)
pty
- Remove the
!master_openand!slave_openfunctions, which have been deprecated since Python 3.12. Usepty.openptyinstead. (Contributed by Nikita Sobolev in118824.)
sqlite3
- Remove
!versionand!version_infofrom thesqlite3module; use~sqlite3.sqlite_versionand~sqlite3.sqlite_version_infofor the actual version number of the runtime SQLite library. (Contributed by Hugo van Kemenade in118924.) - Using a sequence of parameters with named placeholders now raises a
~sqlite3.ProgrammingError, having been deprecated since Python 3.12. (Contributed by Erlend E. Aasland in118928and101693.)
urllib
-
Remove the
!Quoterclass fromurllib.parse, which has been deprecated since Python 3.11. (Contributed by Nikita Sobolev in118827.) -
Remove the
!URLopenerand!FancyURLopenerclasses fromurllib.request, which have been deprecated since Python 3.3.myopener.open()can be replaced with~urllib.request.urlopen.myopener.retrieve()can be replaced with~urllib.request.urlretrieve. Customisations to the opener classes can be replaced by passing customized handlers to~urllib.request.build_opener. (Contributed by Barney Gale in84850.)
Deprecated
New deprecations
- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; complex numbers should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.) argparse:- Passing the undocumented keyword argument prefix_chars to the
~argparse.ArgumentParser.add_argument_groupmethod is now deprecated. (Contributed by Savannah Ostrowski in125563.) - Deprecated the
argparse.FileTypetype converter. Anything relating to resource management should be handled downstream, after the arguments have been parsed. (Contributed by Serhiy Storchaka in58032.)
- Passing the undocumented keyword argument prefix_chars to the
asyncio:-
The
!asyncio.iscoroutinefunctionis now deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunctioninstead. (Contributed by Jiahao Li and Kumar Aditya in122875.) -
The
asynciopolicy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:!asyncio.AbstractEventLoopPolicy!asyncio.DefaultEventLoopPolicy!asyncio.WindowsSelectorEventLoopPolicy!asyncio.WindowsProactorEventLoopPolicy!asyncio.get_event_loop_policy!asyncio.set_event_loop_policy
Users should use
asyncio.runorasyncio.Runnerwith the loop_factory argument to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)(Contributed by Kumar Aditya in
127949.)
-
codecs: Thecodecs.openfunction is now deprecated, and will be removed in a future version of Python. Useopeninstead. (Contributed by Inada Naoki in133036.)ctypes:- On non-Windows platforms, setting
.Structure._pack_to use a MSVC-compatible default memory layout is now deprecated in favor of setting.Structure._layout_to'ms', and will be removed in Python 3.19. (Contributed by Petr Viktorin in131747.) - Calling
ctypes.POINTERon a string is now deprecated. Useincomplete types <ctypes-incomplete-types>for self-referential structures. Also, the internalctypes._pointer_type_cacheis deprecated. Seectypes.POINTERfor updated implementation details. (Contributed by Sergey Myrianov in100926.)
- On non-Windows platforms, setting
functools: Calling the Python implementation offunctools.reducewith function or sequence as keyword arguments is now deprecated; the parameters will be made positional-only in Python 3.16. (Contributed by Kirill Podoprigora in121676.)logging: Support for custom logging handlers with the strm argument is now deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in115032.)mimetypes: Valid extensions are either empty or must start with '.' formimetypes.MimeTypes.add_type. Undotted extensions are deprecated and will raise aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in75223.)!nturl2path: This module is now deprecated. Callurllib.request.url2pathnameand~urllib.request.pathname2urlinstead. (Contributed by Barney Gale in125866.)os: Theos.popenandos.spawn* <os.spawnl>functions are nowsoft deprecated. They should no longer be used to write new code. Thesubprocessmodule is recommended instead. (Contributed by Victor Stinner in120743.)pathlib:!pathlib.PurePath.as_uriis now deprecated and scheduled for removal in Python 3.19. Usepathlib.Path.as_uriinstead. (Contributed by Barney Gale in123599.)pdb: The undocumentedpdb.Pdb.curframe_localsattribute is now a deprecated read-only property, which will be removed in a future version of Python. The low overhead dynamic frame locals access added in Python 3.13 by667means the frame locals cache reference previously stored in this attribute is no longer needed. Derived debuggers should accesspdb.Pdb.curframe.f_localsdirectly in Python 3.13 and later versions. (Contributed by Tian Gao in124369and125951.)symtable: Deprecate!symtable.Class.get_methodsdue to the lack of interest, scheduled for removal in Python 3.16. (Contributed by Bénédikt Tran in119698.)tkinter: The!tkinter.Variablemethods!trace_variable,!trace_vdeleteand!trace_vinfoare now deprecated. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)urllib.parse: Accepting objects with false values (like0and[]) except empty strings, bytes-like objects andNonein~urllib.parse.parse_qsland~urllib.parse.parse_qsis now deprecated. (Contributed by Serhiy Storchaka in116897.)
Pending removal in Python 3.15
- The import system:
- Setting
__cached__on a module while failing to set__spec__.cached <importlib.machinery.ModuleSpec.cached>is deprecated. In Python 3.15,__cached__will cease to be set or take into consideration by the import system or standard library. (97879)
- Setting
ctypes:- The undocumented
!ctypes.SetPointerTypefunction has been deprecated since Python 3.13.
- The undocumented
http.server:- The obsolete and rarely used
!CGIHTTPRequestHandlerhas been deprecated since Python 3.13. No direct replacement exists. Anything is better than CGI to interface a web server with a request handler. - The
!--cgiflag to thepython -m http.servercommand-line interface has been deprecated since Python 3.13.
- The obsolete and rarely used
importlib:load_module()method: useexec_module()instead.
pathlib:!.PurePath.is_reservedhas been deprecated since Python 3.13. Useos.path.isreservedto detect reserved paths on Windows.
platform:!platform.java_verhas been deprecated since Python 3.13. This function is only useful for Jython support, has a confusing API, and is largely untested.
sysconfig:- The check_home argument of
sysconfig.is_python_buildhas been deprecated since Python 3.12.
- The check_home argument of
threading:~threading.RLockwill take no arguments in Python 3.15. Passing any arguments has been deprecated since Python 3.14, as the Python version does not permit any arguments, but the C version allows any number of positional or keyword arguments, ignoring every argument.
types:types.CodeType: Accessing!codeobject.co_lnotabwas deprecated in626since 3.10 and was planned to be removed in 3.12, but it only got a properDeprecationWarningin 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in101866.)
typing:- The undocumented keyword argument syntax for creating
~typing.NamedTupleclasses (for example,Point = NamedTuple("Point", x=int, y=int)) has been deprecated since Python 3.13. Use the class-based syntax or the functional syntax instead. - When using the functional syntax of
~typing.TypedDicts, failing to pass a value to the fields parameter (TD = TypedDict("TD")) or passingNone(TD = TypedDict("TD", None)) has been deprecated since Python 3.13. Useclass TD(TypedDict): passorTD = TypedDict("TD", {})to create a TypedDict with zero field. - The
!typing.no_type_check_decoratordecorator function has been deprecated since Python 3.13. After eight years in thetypingmodule, it has yet to be supported by any major type checker.
- The undocumented keyword argument syntax for creating
!sre_compile,!sre_constantsand!sre_parsemodules.wave:- The
getmark(),setmark()andgetmarkers()methods of the~wave.Wave_readand~wave.Wave_writeclasses have been deprecated since Python 3.13.
- The
zipimport:!zipimport.zipimporter.load_modulehas been deprecated since Python 3.10. Use~zipimport.zipimporter.exec_moduleinstead. (125746.)
Pending removal in Python 3.16
- The import system:
- Setting
~module.__loader__on a module while failing to set__spec__.loader <importlib.machinery.ModuleSpec.loader>is deprecated. In Python 3.16,!__loader__will cease to be set or taken into consideration by the import system or the standard library. - Setting
~module.__package__on a module while failing to set__spec__.parent <importlib.machinery.ModuleSpec.parent>is deprecated. In Python 3.16,!__package__will cease to be taken into consideration by the import system or standard library. (97879)
- Setting
- The bundled copy of
libmpdec. array:- The
'u'format code (wchar_t) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the'w'format code (Py_UCS4) for Unicode characters instead.
- The
asyncio:-
!asyncio.iscoroutinefunctionis deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunctioninstead. (Contributed by Jiahao Li and Kumar Aditya in122875.) -
asynciopolicy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:!asyncio.AbstractEventLoopPolicy!asyncio.DefaultEventLoopPolicy!asyncio.WindowsSelectorEventLoopPolicy!asyncio.WindowsProactorEventLoopPolicy!asyncio.get_event_loop_policy!asyncio.set_event_loop_policy
Users should use
asyncio.runorasyncio.Runnerwith loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)(Contributed by Kumar Aditya in
127949.)
-
builtins:- Bitwise inversion on boolean types,
~Trueor~Falsehas been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2and-1). Usenot xinstead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert tointexplicitly (~int(x)).
- Bitwise inversion on boolean types,
functools:- Calling the Python implementation of
functools.reducewith function or sequence as keyword arguments has been deprecated since Python 3.14.
- Calling the Python implementation of
logging:- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
115032.)
- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
mimetypes:- Valid extensions start with a '.' or are empty for
mimetypes.MimeTypes.add_type. Undotted extensions are deprecated and will raise aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in75223.)
- Valid extensions start with a '.' or are empty for
shutil:- The
!ExecErrorexception has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4, and is now an alias ofRuntimeError.
- The
symtable:- The
!symtable.Class.get_methodsmethod has been deprecated since Python 3.14.
- The
sys:- The
!_enablelegacywindowsfsencodingfunction has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
- The
sysconfig:- The
!sysconfig.expand_makefile_varsfunction has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead.
- The
tarfile:- The undocumented and unused
!TarInfo.tarfileattribute has been deprecated since Python 3.13.
- The undocumented and unused
Pending removal in Python 3.17
datetime:~datetime.datetime.strptimecalls using a format string containing%e(day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in70647.)
collections.abc:-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
encodings:- Passing non-ascii encoding names to
encodings.normalize_encodingis deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in136702.)
- Passing non-ascii encoding names to
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOS. (137586)
typing:-
Before Python 3.14, old-style unions were implemented using the private class
typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers liketyping.get_originandtyping.get_argsinstead of relying on private implementation details. -
typing.ByteString, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
tkinter:- The
!tkinter.Variablemethods!trace_variable,!trace(an alias of!trace_variable),!trace_vdeleteand!trace_vinfo, deprecated since Python 3.14, are scheduled for removal in Python 3.17. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)
- The
Pending removal in Python 3.18
-
No longer accept a boolean value when a file descriptor is expected. (Contributed by Serhiy Storchaka in
82626.) -
decimal:- The non-standard and undocumented
~decimal.Decimalformat specifier'N', which is only supported in the!decimalmodule's C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in89902.)
- The non-standard and undocumented
-
Deprecations defined by
829:importlines in{name}.pthfiles are silently ignored.
(Contributed by Barry Warsaw in
148641.)
Pending removal in Python 3.19
builtins:- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.)
- Passing a complex number as the real or imag argument in the
ctypes:- Implicitly switching to the MSVC-compatible struct layout by setting
~ctypes.Structure._pack_but not~ctypes.Structure._layout_on non-Windows platforms.
- Implicitly switching to the MSVC-compatible struct layout by setting
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in various!hashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.
-
http.cookies:http.cookies.Morsel.js_outputis deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_outputis deprecated and will be removed in Python 3.19.
imaplib:-
Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.Before Python 3.14, this property was used to implement the corresponding
read()andreadline()methods for~imaplib.IMAP4but this is no longer the case since then.
-
tkinter:tkinter.filedialog.askopenfileshas been deprecated since Python 3.16. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.20
-
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling~object.__init__method on initialized~struct.Structobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.) -
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.) -
Deprecations defined by
829:- Warnings are produced for
importlines found in{name}.pthfiles. {name}.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in
148641.) - Warnings are produced for
-
ast:- Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.
- Creating instances of abstract AST nodes (such as
-
typing:-
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
Pending removal in Python 3.21
-
abc- Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively.
- Soft-deprecated since Python 3.3
-
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
- Classes
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodis deprecated since Python 3.16 and will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
-
struct:- Soft-deprecated since Python 3.15, using
'F'and'D'type codes are now deprecated. These codes will be removed in Python 3.21. Use instead two-letter forms'Zf'and'Zd'.
- Soft-deprecated since Python 3.15, using
-
tempfile:tempfile._TemporaryFileWrapperwill be removed in Python 3.21. Use the publictempfile.TemporaryFileWrapperinstead.
Pending removal in future versions
The following APIs will be removed in the future, although there is currently no date scheduled for their removal.
argparse:- Nesting argument groups and nesting mutually exclusive groups are deprecated.
- Passing the undocumented keyword argument prefix_chars to
~argparse.ArgumentParser.add_argument_groupis now deprecated. - The
argparse.FileTypetype converter is deprecated.
builtins:- Generators:
throw(type, exc, tb)andathrow(type, exc, tb)signature is deprecated: usethrow(exc)andathrow(exc)instead, the single argument signature. - Currently Python accepts numeric literals immediately followed by keywords, for example
0in x,1or x,0if 1else 2. It allows confusing and ambiguous expressions like[0x1for x in y](which can be interpreted as[0x1 for x in y]or[0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In a future release it will be changed to a syntax error. (87999) - Support for
__index__()and__int__()method returning non-int type: these methods will be required to return an instance of a strict subclass ofint. - Support for
__float__()method returning a strict subclass offloat: these methods will be required to return an instance offloat. - Support for
__complex__()method returning a strict subclass ofcomplex: these methods will be required to return an instance ofcomplex.
- Generators:
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.)codecs: useopeninstead ofcodecs.open. (133038)!codeobject.co_lnotab: use thecodeobject.co_linesmethod instead.datetime:~datetime.datetime.utcnow: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp: usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: Plural value must be an integer.importlib:~importlib.util.cache_from_sourcedebug_override parameter is deprecated: use the optimization parameter instead.
importlib.metadata:EntryPointstuple interface.- Implicit
Noneon return values.
logging: thewarn()method has been deprecated since Python 3.3, use~logging.warninginstead.mailbox: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.os: Callingos.register_at_forkin a multi-threaded process.os.path:os.path.commonprefixis deprecated, useos.path.commonpathfor path prefixes. Theos.path.commonprefixfunction is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.!pydoc.ErrorDuringImport: A tuple value for exc_info parameter is deprecated, use an exception instance.re: More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in91760.)shutil:~shutil.rmtree's onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:~ssl.SSLContext.set_npn_protocolsand!selected_npn_protocolare deprecated: use ALPN instead.ssl.OP_NO_SSL*optionsssl.OP_NO_TLS*optionsssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.TLSVersion.TLSv1_1
threadingmethods:!threading.Condition.notifyAll: use~threading.Condition.notify_all.!threading.Event.isSet: use~threading.Event.is_set.!threading.Thread.isDaemon,threading.Thread.setDaemon: usethreading.Thread.daemonattribute.!threading.Thread.getName,threading.Thread.setName: usethreading.Thread.nameattribute.!threading.currentThread: usethreading.current_thread.!threading.activeCount: usethreading.active_count.
typing.Text(92332).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in105499.) unittest.IsolatedAsyncioTestCase: it is deprecated to return a value that is notNonefrom a test case.urllib.parsedeprecated functions:~urllib.parse.urlparseinsteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partial writes.xml.etree.ElementTree: Testing the truth value of an~xml.etree.ElementTree.Elementis deprecated. In a future release it will always returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cacheis deprecated: usesys._clear_internal_cachesinstead.
CPython bytecode changes
- Replaced the opcode
!BINARY_SUBSCRby theBINARY_OPopcode with theNB_SUBSCRoparg. (Contributed by Irit Katriel in100239.) - Add the
BUILD_INTERPOLATIONandBUILD_TEMPLATEopcodes to construct new~string.templatelib.Interpolationand~string.templatelib.Templateinstances, respectively. (Contributed by Lysandros Nikolaou and others in132661; see alsoPEP 750: Template strings <whatsnew314-template-string-literals>). - Remove the
!BUILD_CONST_KEY_MAPopcode. UseBUILD_MAPinstead. (Contributed by Mark Shannon in122160.) - Replace the
!LOAD_ASSERTION_ERRORopcode withLOAD_COMMON_CONSTANTand add support for loadingNotImplementedError. - Add the
LOAD_FAST_BORROWandLOAD_FAST_BORROW_LOAD_FAST_BORROWopcodes to reduce reference counting overhead when the interpreter can prove that the reference in the frame outlives the reference loaded onto the stack. (Contributed by Matt Page in130704.) - Add the
LOAD_SMALL_INTopcode, which pushes a small integer equal to theopargto the stack. The!RETURN_CONSTopcode is removed as it is no longer used. (Contributed by Mark Shannon in125837.) - Add the new
LOAD_SPECIALinstruction. Generate code forwithandasync withstatements using the new instruction. Removed the!BEFORE_WITHand!BEFORE_ASYNC_WITHinstructions. (Contributed by Mark Shannon in120507.) - Add the
POP_ITERopcode to support 'virtual' iterators. (Contributed by Mark Shannon in132554.)
Pseudo-instructions
- Add the
!ANNOTATIONS_PLACEHOLDERpseudo instruction to support partially executed module-level annotations withdeferred evaluation of annotations <whatsnew314-deferred-annotations>. (Contributed by Jelle Zijlstra in130907.) - Add the
!BINARY_OP_EXTENDpseudo instruction, which executes a pair of functions (guard and specialization functions) accessed from the inline cache. (Contributed by Irit Katriel in100239.) - Add three specializations for
CALL_KW;!CALL_KW_PYfor calls to Python functions,!CALL_KW_BOUND_METHODfor calls to bound methods, and!CALL_KW_NON_PYfor all other calls. (Contributed by Mark Shannon in118093.) - Add the
JUMP_IF_TRUEandJUMP_IF_FALSEpseudo instructions, conditional jumps which do not impact the stack. Replaced by the sequenceCOPY 1,TO_BOOL,POP_JUMP_IF_TRUE/FALSE. (Contributed by Irit Katriel in124285.) - Add the
!LOAD_CONST_MORTALpseudo instruction. (Contributed by Mark Shannon in128685.) - Add the
!LOAD_CONST_IMMORTALpseudo instruction, which does the same as!LOAD_CONST, but is more efficient for immortal objects. (Contributed by Mark Shannon in125837.) - Add the
NOT_TAKENpseudo instruction, used bysys.monitoringto record branch events (such asBRANCH_LEFT). (Contributed by Mark Shannon in122548.)
C API changes
Python configuration C API
Add a PyInitConfig C API <pyinitconfig_api> to configure the Python initialization without relying on C structures and the ability to make ABI-compatible changes in the future.
Complete the 587 PyConfig C API <pyconfig_api> by adding PyInitConfig_AddModule which can be used to add a built-in extension module; a feature previously referred to as the "inittab".
Add PyConfig_Get and PyConfig_Set functions to get and set the current runtime configuration.
587 'Python Initialization Configuration' unified all the ways to configure Python's initialization. This PEP also unifies the configuration of Python's preinitialization and initialization in a single API. Moreover, this PEP only provides a single choice to embed Python, instead of having two 'Python' and 'Isolated' choices (PEP 587), to further simplify the API.
The lower level PEP 587 PyConfig API remains available for use cases with an intentionally higher level of coupling to CPython implementation details (such as emulating the full functionality of CPython's CLI, including its configuration mechanisms).
(Contributed by Victor Stinner in 107954.)
741 and 587
New features in the C API
-
Add
Py_PACK_VERSIONandPy_PACK_FULL_VERSION, two new macros for bit-packing Python version numbers. This is useful for comparisons withPy_VersionorPY_VERSION_HEX. (Contributed by Petr Viktorin in128629.) -
Add
PyBytes_Join(sep, iterable) <PyBytes_Join>function, similar tosep.join(iterable)in Python. (Contributed by Victor Stinner in121645.) -
Add functions to manipulate the configuration of the current runtime Python interpreter (
PEP 741: Python configuration C API <whatsnew314-capi-config>):PyConfig_GetPyConfig_GetIntPyConfig_SetPyConfig_Names
(Contributed by Victor Stinner in
107954.) -
Add functions to configure Python initialization (
PEP 741: Python configuration C API <whatsnew314-capi-config>):Py_InitializeFromInitConfigPyInitConfig_AddModulePyInitConfig_CreatePyInitConfig_FreePyInitConfig_FreeStrListPyInitConfig_GetErrorPyInitConfig_GetExitCodePyInitConfig_GetIntPyInitConfig_GetStrPyInitConfig_GetStrListPyInitConfig_HasOptionPyInitConfig_SetIntPyInitConfig_SetStrPyInitConfig_SetStrList
(Contributed by Victor Stinner in
107954.) -
Add
Py_fopenfunction to open a file. This works similarly to the standard C!fopenfunction, instead accepting a Python object for the path parameter and setting an exception on error. The corresponding newPy_fclosefunction should be used to close a file. (Contributed by Victor Stinner in127350.) -
Add
Py_HashBufferto compute and return the hash value of a buffer. (Contributed by Antoine Pitrou and Victor Stinner in122854.) -
Add
PyImport_ImportModuleAttrandPyImport_ImportModuleAttrStringhelper functions to import a module and get an attribute of the module. (Contributed by Victor Stinner in128911.) -
Add
PyIter_NextItemto replacePyIter_Next, which has an ambiguous return value. (Contributed by Irit Katriel and Erlend Aasland in105201.) -
Add
PyLong_GetSignfunction to get the sign ofintobjects. (Contributed by Sergey B Kirpichev in116560.) -
Add
PyLong_IsPositive,PyLong_IsNegativeandPyLong_IsZerofor checking ifPyLongObjectis positive, negative, or zero, respectively. (Contributed by James Roy and Sergey B Kirpichev in126061.) -
Add new functions to convert C
<stdint.h>numbers to/from Pythonintobjects:PyLong_AsInt32PyLong_AsInt64PyLong_AsUInt32PyLong_AsUInt64PyLong_FromInt32PyLong_FromInt64PyLong_FromUInt32PyLong_FromUInt64
(Contributed by Victor Stinner in
120389.) -
Add a new import and export API for Python
intobjects (757):PyLong_GetNativeLayoutPyLong_ExportPyLong_FreeExportPyLongWriter_CreatePyLongWriter_FinishPyLongWriter_Discard
(Contributed by Sergey B Kirpichev and Victor Stinner in
102471.) -
Add
PyMonitoring_FireBranchLeftEventandPyMonitoring_FireBranchRightEventfor generatingBRANCH_LEFTandBRANCH_RIGHTevents, respectively. (Contributed by Mark Shannon in122548.) -
Add
PyType_Freezefunction to make a type immutable. (Contributed by Victor Stinner in121654.) -
Add
PyType_GetBaseByTokenandPy_tp_tokenslot for easier superclass identification, which attempts to resolve the type checking issue mentioned inPEP 630 <630#type-checking>. (Contributed in124153.) -
Add a new
PyUnicode_Equalfunction to test if two strings are equal. The function is also added to the Limited C API. (Contributed by Victor Stinner in124502.) -
Add a new
PyUnicodeWriterAPI to create a Pythonstrobject, with the following functions:PyUnicodeWriter_CreatePyUnicodeWriter_DecodeUTF8StatefulPyUnicodeWriter_DiscardPyUnicodeWriter_FinishPyUnicodeWriter_FormatPyUnicodeWriter_WriteASCIIPyUnicodeWriter_WriteCharPyUnicodeWriter_WriteReprPyUnicodeWriter_WriteStrPyUnicodeWriter_WriteSubstringPyUnicodeWriter_WriteUCS4PyUnicodeWriter_WriteUTF8PyUnicodeWriter_WriteWideChar
(Contributed by Victor Stinner in
119182.) -
The
kandKformats inPyArg_ParseTupleand similar functions now use~object.__index__if available, like all other integer formats. (Contributed by Serhiy Storchaka in112068.) -
Add support for a new
pformat unit inPy_BuildValuethat produces a Pythonboolobject from a C integer. (Contributed by Pablo Galindo in45325.) -
Add
PyUnstable_IsImmortalfor determining if an object isimmortal, for debugging purposes. (Contributed by Peter Bierma in128509.) -
Add
PyUnstable_Object_EnableDeferredRefcountfor enabling deferred reference counting, as outlined in703. -
Add
PyUnstable_Object_IsUniquelyReferencedas a replacement forPy_REFCNT(op) == 1onfree threaded <free threading>builds. (Contributed by Peter Bierma in133140.) -
Add
PyUnstable_Object_IsUniqueReferencedTemporaryto determine if an object is a unique temporary object on the interpreter's operand stack. This can be used in some cases as a replacement for checking ifPy_REFCNTis1for Python objects passed as arguments to C API functions. (Contributed by Sam Gross in133164.)
Limited C API changes
- In the limited C API version 3.14 and newer,
Py_TYPEandPy_REFCNTare now implemented as an opaque function call to hide implementation details. (Contributed by Victor Stinner in120600and124127.) - Remove the
PySequence_Fast_GET_SIZE,PySequence_Fast_GET_ITEM, andPySequence_Fast_ITEMSmacros from the limited C API, since they have always been broken in the limited C API. (Contributed by Victor Stinner in91417.)
Removed C APIs
- Creating
immutable types <Py_TPFLAGS_IMMUTABLETYPE>with mutable bases was deprecated in Python 3.12, and now raises aTypeError. (Contributed by Nikita Sobolev in119775.) - Remove
PyDictObject.ma_version_tagmember, which was deprecated in Python 3.12. Use thePyDict_AddWatcherAPI instead. (Contributed by Sam Gross in124296.) - Remove the private
_Py_InitializeMain()function. It was aprovisional APIadded to Python 3.8 by587. (Contributed by Victor Stinner in129033.) - Remove the undocumented APIs
!Py_C_RECURSION_LIMITand!PyThreadState.c_recursion_remaining. These were added in 3.13 and have been removed without deprecation. UsePy_EnterRecursiveCallto guard against runaway recursion in C code. (Removed by Petr Viktorin in133079, see also130396.)
Deprecated C APIs
- The
!Py_HUGE_VALmacro is nowsoft deprecated. Use!INFINITYinstead. (Contributed by Sergey B Kirpichev in120026.) - The
!Py_IS_NAN,!Py_IS_INFINITY, and!Py_IS_FINITEmacros are nowsoft deprecated. Use!isnan,!isinfand!isfiniteinstead, available frommath.hsince C99. (Contributed by Sergey B Kirpichev in119613.) - Non-tuple sequences are now deprecated as argument for the
(items)format unit inPyArg_ParseTupleand otherargument parsing <arg-parsing>functions if items contains format units which store aborrowed buffer <c-arg-borrowed-buffer>or aborrowed reference. (Contributed by Serhiy Storchaka in50333.) - The
_PyMonitoring_FireBranchEventfunction is now deprecated and should be replaced with calls toPyMonitoring_FireBranchLeftEventandPyMonitoring_FireBranchRightEvent. - The previously undocumented function
PySequence_Inis nowsoft deprecated. UsePySequence_Containsinstead. (Contributed by Yuki Kobayashi in127896.)
Pending removal in Python 3.15
-
The
!PyImport_ImportModuleNoBlock: UsePyImport_ImportModuleinstead. -
!PyWeakref_GetObjectand!PyWeakref_GET_OBJECT: UsePyWeakref_GetRefinstead. The pythoncapi-compat project can be used to getPyWeakref_GetRefon Python 3.12 and older. -
!PyUnicode_AsDecodedObject: UsePyCodec_Decodeinstead. -
!PyUnicode_AsDecodedUnicode: UsePyCodec_Decodeinstead; Note that some codecs (for example, "base64") may return a type other thanstr, such asbytes. -
!PyUnicode_AsEncodedObject: UsePyCodec_Encodeinstead. -
!PyUnicode_AsEncodedUnicode: UsePyCodec_Encodeinstead; Note that some codecs (for example, "base64") may return a type other thanbytes, such asstr. -
Python initialization functions, deprecated in Python 3.13:
!Py_GetPath: UsePyConfig_Get("module_search_paths") <PyConfig_Get>(sys.path) instead.!Py_GetPrefix: UsePyConfig_Get("base_prefix") <PyConfig_Get>(sys.base_prefix) instead. UsePyConfig_Get("prefix") <PyConfig_Get>(sys.prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetExecPrefix: UsePyConfig_Get("base_exec_prefix") <PyConfig_Get>(sys.base_exec_prefix) instead. UsePyConfig_Get("exec_prefix") <PyConfig_Get>(sys.exec_prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetProgramFullPath: UsePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetProgramName: UsePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetPythonHome: UsePyConfig_Get("home") <PyConfig_Get>or thePYTHONHOMEenvironment variable instead.
The pythoncapi-compat project can be used to get
PyConfig_Geton Python 3.13 and older.
Pending removal in Python 3.16
-
Functions to configure Python's initialization, deprecated in Python 3.11:
!PySys_SetArgvEx(): SetPyConfig.argvinstead.!PySys_SetArgv(): SetPyConfig.argvinstead.!Py_SetProgramName(): SetPyConfig.program_nameinstead.!Py_SetPythonHome(): SetPyConfig.homeinstead.
The
Py_InitializeFromConfigAPI should be used withPyConfiginstead. -
Global configuration variables:
!Py_DebugFlag: UsePyConfig.parser_debugorPyConfig_Get("parser_debug") <PyConfig_Get>instead.!Py_VerboseFlag: UsePyConfig.verboseorPyConfig_Get("verbose") <PyConfig_Get>instead.!Py_QuietFlag: UsePyConfig.quietorPyConfig_Get("quiet") <PyConfig_Get>instead.!Py_InteractiveFlag: UsePyConfig.interactiveorPyConfig_Get("interactive") <PyConfig_Get>instead.!Py_InspectFlag: UsePyConfig.inspectorPyConfig_Get("inspect") <PyConfig_Get>instead.!Py_OptimizeFlag: UsePyConfig.optimization_levelorPyConfig_Get("optimization_level") <PyConfig_Get>instead.!Py_NoSiteFlag: UsePyConfig.site_importorPyConfig_Get("site_import") <PyConfig_Get>instead.!Py_BytesWarningFlag: UsePyConfig.bytes_warningorPyConfig_Get("bytes_warning") <PyConfig_Get>instead.!Py_FrozenFlag: UsePyConfig.pathconfig_warningsorPyConfig_Get("pathconfig_warnings") <PyConfig_Get>instead.!Py_IgnoreEnvironmentFlag: UsePyConfig.use_environmentorPyConfig_Get("use_environment") <PyConfig_Get>instead.!Py_DontWriteBytecodeFlag: UsePyConfig.write_bytecodeorPyConfig_Get("write_bytecode") <PyConfig_Get>instead.!Py_NoUserSiteDirectory: UsePyConfig.user_site_directoryorPyConfig_Get("user_site_directory") <PyConfig_Get>instead.!Py_UnbufferedStdioFlag: UsePyConfig.buffered_stdioorPyConfig_Get("buffered_stdio") <PyConfig_Get>instead.!Py_HashRandomizationFlag: UsePyConfig.use_hash_seedandPyConfig.hash_seedorPyConfig_Get("hash_seed") <PyConfig_Get>instead.!Py_IsolatedFlag: UsePyConfig.isolatedorPyConfig_Get("isolated") <PyConfig_Get>instead.!Py_LegacyWindowsFSEncodingFlag: UsePyPreConfig.legacy_windows_fs_encodingorPyConfig_Get("legacy_windows_fs_encoding") <PyConfig_Get>instead.!Py_LegacyWindowsStdioFlag: UsePyConfig.legacy_windows_stdioorPyConfig_Get("legacy_windows_stdio") <PyConfig_Get>instead.!Py_FileSystemDefaultEncoding,!Py_HasFileSystemDefaultEncoding: UsePyConfig.filesystem_encodingorPyConfig_Get("filesystem_encoding") <PyConfig_Get>instead.!Py_FileSystemDefaultEncodeErrors: UsePyConfig.filesystem_errorsorPyConfig_Get("filesystem_errors") <PyConfig_Get>instead.!Py_UTF8Mode: UsePyPreConfig.utf8_modeorPyConfig_Get("utf8_mode") <PyConfig_Get>instead. (seePy_PreInitialize)
The
Py_InitializeFromConfigAPI should be used withPyConfigto set these options. OrPyConfig_Getcan be used to get these options at runtime. -
Py_UNICODEwhich was deprecated by393.
Pending removal in Python 3.18
-
The following private functions are deprecated and planned for removal in Python 3.18:
!_PyBytes_Join: usePyBytes_Join.!_PyDict_GetItemStringWithError: usePyDict_GetItemStringRef.!_PyDict_Pop(): usePyDict_Pop.!_PyLong_Sign(): usePyLong_GetSign.!_PyLong_FromDigitsand!_PyLong_New: usePyLongWriter_Create.!_PyThreadState_UncheckedGet: usePyThreadState_GetUnchecked.!_PyUnicode_AsString: usePyUnicode_AsUTF8.!_PyUnicodeWriter_Init: replace_PyUnicodeWriter_Init(&writer)withwriter = PyUnicodeWriter_Create(0) <PyUnicodeWriter_Create>.!_PyUnicodeWriter_Finish: replace_PyUnicodeWriter_Finish(&writer)withPyUnicodeWriter_Finish(writer) <PyUnicodeWriter_Finish>.!_PyUnicodeWriter_Dealloc: replace_PyUnicodeWriter_Dealloc(&writer)withPyUnicodeWriter_Discard(writer) <PyUnicodeWriter_Discard>.!_PyUnicodeWriter_WriteChar: replace_PyUnicodeWriter_WriteChar(&writer, ch)withPyUnicodeWriter_WriteChar(writer, ch) <PyUnicodeWriter_WriteChar>.!_PyUnicodeWriter_WriteStr: replace_PyUnicodeWriter_WriteStr(&writer, str)withPyUnicodeWriter_WriteStr(writer, str) <PyUnicodeWriter_WriteStr>.!_PyUnicodeWriter_WriteSubstring: replace_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)withPyUnicodeWriter_WriteSubstring(writer, str, start, end) <PyUnicodeWriter_WriteSubstring>.!_PyUnicodeWriter_WriteASCIIString: replace_PyUnicodeWriter_WriteASCIIString(&writer, str, size)withPyUnicodeWriter_WriteASCII(writer, str, size) <PyUnicodeWriter_WriteASCII>.!_PyUnicodeWriter_WriteLatin1String: replace_PyUnicodeWriter_WriteLatin1String(&writer, str, size)by decoding the string withPyUnicode_DecodeLatin1, writing the result withPyUnicodeWriter_WriteStr, and releasing the result withPy_DECREF.!_PyUnicodeWriter_Prepare: (no replacement).!_PyUnicodeWriter_PrepareKind: (no replacement).!_Py_HashPointer: usePy_HashPointer.!_Py_fopen_obj: usePy_fopen.PyGen_New: (no replacement).PyGen_NewWithQualName: (no replacement).PyCoro_New: (no replacement).PyAsyncGen_New: (no replacement).
The pythoncapi-compat project can be used to get these new public functions on Python 3.13 and older. (Contributed by Victor Stinner in
128863.)
Pending removal in future versions
The following APIs are deprecated and will be removed, although there is currently no date scheduled for their removal.
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch: UsePyErr_GetRaisedExceptioninstead.PyErr_NormalizeException: UsePyErr_GetRaisedExceptioninstead.PyErr_Restore: UsePyErr_SetRaisedExceptioninstead.PyOS_AfterFork: UsePyOS_AfterFork_Childinstead.PySlice_GetIndicesEx: UsePySlice_UnpackandPySlice_AdjustIndicesinstead.PyUnicode_READY: Unneeded since Python 3.12!PyErr_Display: UsePyErr_DisplayExceptioninstead.!_PyErr_ChainExceptions: Use!_PyErr_ChainExceptions1instead.!PyBytesObject.ob_shashmember: callPyObject_Hashinstead.- Thread Local Storage (TLS) API:
PyThread_create_key: UsePyThread_tss_allocinstead.PyThread_delete_key: UsePyThread_tss_freeinstead.PyThread_set_key_value: UsePyThread_tss_setinstead.PyThread_get_key_value: UsePyThread_tss_getinstead.PyThread_delete_key_value: UsePyThread_tss_deleteinstead.PyThread_ReInitTLS: Unneeded since Python 3.7.
Build changes
776: Emscripten is now an officially supported platform attier 3 <11#tier-3>. As a part of this effort, more than 25 bugs in Emscripten libc were fixed. Emscripten now includes support forctypes,termios, andfcntl, as well as experimental support for the newdefault interactive shell <tut-interactive>. (Contributed by R. Hood Chatham in127146,127683, and136931.)- Official Android binary releases are now provided on python.org.
- GNU Autoconf 2.72 is now required to generate
configure. (Contributed by Erlend Aasland in115765.) wasm32-unknown-emscriptenis now a11tier 3 platform. (Contributed by R. Hood Chatham in127146,127683, and136931.)#pragma-based linking withpython3*.libcan now be switched off withPy_NO_LINK_LIB. (Contributed by Jean-Christophe Fillion-Robin in82909.)- CPython now enables a set of recommended compiler options by default for improved security. Use the
--disable-safetyconfigureoption to disable them, or the--enable-slower-safetyoption for a larger set of compiler options, albeit with a performance cost. - The
WITH_FREELISTSmacro and--without-freelistsconfigureoption have been removed. - The new
configureoption--with-tail-call-interpmay be used to enable the experimental tail call interpreter. Seewhatsnew314-tail-call-interpreterfor further details. - To disable the new remote debugging support, use the
--without-remote-debugconfigureoption. This may be useful for security reasons. - iOS and macOS apps can now be configured to redirect
stdoutandstderrcontent to the system log. (Contributed by Russell Keith-Magee in127592.) - The iOS testbed is now able to stream test output while the test is running. The testbed can also be used to run the test suite of projects other than CPython itself. (Contributed by Russell Keith-Magee in
127592.)
build-details.json
Installations of Python now contain a new file, build-details.json. This is a static JSON document containing build details for CPython, to allow for introspection without needing to run code. This is helpful for use-cases such as Python launchers, cross-compilation, and so on.
build-details.json must be installed in the platform-independent standard library directory. This corresponds to the 'stdlib' <installation_paths> sysconfig installation path, which can be found by running sysconfig.get_path('stdlib').
739 -- build-details.json 1.0 -- a static description file for Python build details
Discontinuation of PGP signatures
PGP (Pretty Good Privacy) signatures will not be provided for releases of Python 3.14 or future versions. To verify CPython artifacts, users must use Sigstore verification materials. Releases have been signed using Sigstore since Python 3.11.
This change in release process was specified in 761.
Free-threaded Python is officially supported
The free-threaded build of Python is now supported and no longer experimental. This is the start of phase II where free-threaded Python is officially supported but still optional.
The free-threading team are confident that the project is on the right path, and appreciate the continued dedication from everyone working to make free-threading ready for broader adoption across the Python community.
With these recommendations and the acceptance of this PEP, the Python developer community should broadly advertise that free-threading is a supported Python build option now and into the future, and that it will not be removed without a proper deprecation schedule.
Any decision to transition to phase III, with free-threading as the default or sole build of Python is still undecided, and dependent on many factors both within CPython itself and the community. This decision is for the future.
Binary releases for the experimental just-in-time compiler
The official macOS and Windows release binaries now include an experimental just-in-time (JIT) compiler. Although it is not recommended for production use, it can be tested by setting PYTHON_JIT=1 <PYTHON_JIT> as an environment variable. Downstream source builds and redistributors can use the --enable-experimental-jit=yes-off configuration option for similar behavior.
The JIT is at an early stage and still in active development. As such, the typical performance impact of enabling it can range from 10% slower to 20% faster, depending on workload. To aid in testing and evaluation, a set of introspection functions has been provided in the sys._jit namespace. sys._jit.is_available can be used to determine if the current executable supports JIT compilation, while sys._jit.is_enabled can be used to tell if JIT compilation has been enabled for the current process.
Currently, the most significant missing functionality is that native debuggers and profilers like gdb and perf are unable to unwind through JIT frames (Python debuggers and profilers, like pdb or profile, continue to work without modification). Free-threaded builds do not support JIT compilation.
Please report any bugs or major performance regressions that you encounter!
744
Porting to Python 3.14
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in the Python API
-
On Unix platforms other than macOS, forkserver is now the default
start method <multiprocessing-start-methods>formultiprocessingand~concurrent.futures.ProcessPoolExecutor, instead of fork.See
(1) <whatsnew314-concurrent-futures-start-method>and(2) <whatsnew314-multiprocessing-start-method>for details.If you encounter
NameErrors or pickling errors coming out ofmultiprocessingorconcurrent.futures, see theforkserver restrictions <multiprocessing-programming-forkserver>.This change does not affect Windows or macOS, where
'spawn' <multiprocessing-start-method-spawn>remains the default start method. -
functools.partialis now a method descriptor. Wrap it instaticmethodif you want to preserve the old behavior. (Contributed by Serhiy Storchaka and Dominykas Grigonis in121027.) -
The
garbage collector is now incremental <whatsnew314-incremental-gc>, which means that the behavior ofgc.collectchanges slightly:gc.collect(1): Performs an increment of garbage collection, rather than collecting generation 1.- Other calls to
!gc.collectare unchanged.
-
The
locale.nl_langinfofunction now temporarily sets theLC_CTYPElocale in some cases. This temporary change affects other threads. (Contributed by Serhiy Storchaka in69998.) -
pickle.dumpandpickle.dumpsnow raise~pickle.PicklingErrorfor some failures that previously raisedAttributeError,ImportError,ValueError,UnicodeEncodeErroror!PicklingError, depending on the implementation (for example, pickling a local object, or an object whose module cannot be imported). The original exception is chained to the!PicklingError. Code that caught these exceptions should also catch!PicklingError. (Contributed by Serhiy Storchaka in122311.) -
types.UnionTypeis now an alias fortyping.Union, causing changes in some behaviors. Seeabove <whatsnew314-typing-union>for more details. (Contributed by Jelle Zijlstra in105499.) -
The runtime behavior of annotations has changed in various ways; see
above <whatsnew314-deferred-annotations>for details. While most code that interacts with annotations should continue to work, some undocumented details may behave differently. -
As part of making the
mimetypesCLI public, it now exits with1on failure instead of0and2on incorrect command-line parameters instead of1. Error messages are now printed to stderr. -
The
\Bpattern in regular expression now matches the empty string when given as the entire pattern, which may cause behavioural changes. -
On FreeBSD,
sys.platformno longer contains the major version number.
Changes in annotations (649 and 749)
This section contains guidance on changes that may be needed to annotations or Python code that interacts with or introspects annotations, due to the changes related to deferred evaluation of annotations <whatsnew314-deferred-annotations>.
In the majority of cases, working code from older versions of Python will not require any changes.
Implications for annotated code
If you define annotations in your code (for example, for use with a static type checker), then this change probably does not affect you: you can keep writing annotations the same way you did with previous versions of Python.
You will likely be able to remove quoted strings in annotations, which are frequently used for forward references. Similarly, if you use from __future__ import annotations to avoid having to write strings in annotations, you may well be able to remove that import once you support only Python 3.14 and newer. However, if you rely on third-party libraries that read annotations, those libraries may need changes to support unquoted annotations before they work as expected.
Implications for readers of __annotations__
If your code reads the ~object.__annotations__ attribute on objects, you may want to make changes in order to support code that relies on deferred evaluation of annotations. For example, you may want to use annotationlib.get_annotations with the ~annotationlib.Format.FORWARDREF format, as the dataclasses module now does.
The external typing_extensions package provides partial backports of some of the functionality of the annotationlib module, such as the ~annotationlib.Format enum and the ~annotationlib.get_annotations function. These can be used to write cross-version code that takes advantage of the new behavior in Python 3.14.
Related changes
The changes in Python 3.14 are designed to rework how !__annotations__ works at runtime while minimizing breakage to code that contains annotations in source code and to code that reads !__annotations__. However, if you rely on undocumented details of the annotation behavior or on private functions in the standard library, there are many ways in which your code may not work in Python 3.14. To safeguard your code against future changes, only use the documented functionality of the annotationlib module.
In particular, do not read annotations directly from the namespace dictionary attribute of type objects. Use annotationlib.get_annotate_from_class_namespace during class construction and annotationlib.get_annotations afterwards.
In previous releases, it was sometimes possible to access class annotations from an instance of an annotated class. This behavior was undocumented and accidental, and will no longer work in Python 3.14.
from __future__ import annotations
In Python 3.7, 563 introduced the from __future__ import annotations future statement <future>, which turns all annotations into strings.
However, this statement is now deprecated and it is expected to be removed in a future version of Python. This removal will not happen until after Python 3.13 reaches its end of life in 2029, being the last version of Python without support for deferred evaluation of annotations.
In Python 3.14, the behavior of code using from __future__ import annotations is unchanged.
Changes in the C API
Py_Finalizenow deletes all interned strings. This is backwards incompatible to any C extension that holds onto an interned string after a call toPy_Finalizeand is then reused after a call toPy_Initialize. Any issues arising from this behavior will normally result in crashes during the execution of the subsequent call toPy_Initializefrom accessing uninitialized memory. To fix, use an address sanitizer to identify any use-after-free coming from an interned string and deallocate it during module shutdown. (Contributed by Eddie Elizondo in113601.)- The
Unicode Exception Objects <unicodeexceptions>C API now raises aTypeErrorif its exception argument is not aUnicodeErrorobject. (Contributed by Bénédikt Tran in127691.)
-
The interpreter internally avoids some reference count modifications when loading objects onto the operands stack by
borrowing <borrowed reference>references when possible. This can lead to smaller reference count values compared to previous Python versions. C API extensions that checkedPy_REFCNTof1to determine if an function argument is not referenced by any other code should instead usePyUnstable_Object_IsUniqueReferencedTemporaryas a safer replacement. -
Private functions promoted to public C APIs:
_PyBytes_Join():PyBytes_Join_PyLong_IsNegative():PyLong_IsNegative_PyLong_IsPositive():PyLong_IsPositive_PyLong_IsZero():PyLong_IsZero_PyLong_Sign():PyLong_GetSign_PyUnicodeWriter_Dealloc():PyUnicodeWriter_Discard_PyUnicodeWriter_Finish():PyUnicodeWriter_Finish_PyUnicodeWriter_Init(): usePyUnicodeWriter_Create_PyUnicodeWriter_Prepare(): (no replacement)_PyUnicodeWriter_PrepareKind(): (no replacement)_PyUnicodeWriter_WriteChar():PyUnicodeWriter_WriteChar_PyUnicodeWriter_WriteStr():PyUnicodeWriter_WriteStr_PyUnicodeWriter_WriteSubstring():PyUnicodeWriter_WriteSubstring_PyUnicode_EQ():PyUnicode_Equal_PyUnicode_Equal():PyUnicode_Equal_Py_GetConfig():PyConfig_GetandPyConfig_GetInt_Py_HashBytes():Py_HashBuffer_Py_fopen_obj():Py_fopenPyMutex_IsLocked():PyMutex_IsLocked
The pythoncapi-compat project can be used to get most of these new functions on Python 3.13 and older.
Notable changes in 3.14.5
gc
- The incremental garbage collector shipped in Python 3.14.0-3.14.4 has been reverted back to the generational garbage collector from 3.13, due to a number of reports of significant memory pressure in production environments. See
whatsnew314-incremental-gcfor details.
What's new in Python 3.15
Editor
Hugo van Kemenade
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the issue number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the VCS log when researching a change.
This article explains the new features in Python 3.15, compared to 3.14. Python 3.15 was released on 9 October 2026. For full details, see the changelog <changelog>.
790 -- Python 3.15 release schedule
Summary -- Release highlights
Python 3.15 is the latest stable release of the Python programming language, with a mix of changes to the language, the implementation, and the standard library. The biggest changes include lazy imports <whatsnew315-lazy-imports>, frozendict <whatsnew315-frozendict> and sentinel <whatsnew315-sentinel> builtins, UTF-8 as the default encoding <whatsnew315-utf8-default>, unpacking in comprehensions <whatsnew315-unpacking-in-comprehensions>, and a stable ABI for free-threaded builds <whatsnew315-abi3t>.
The library changes include a new profiling package <whatsnew315-profiling-package> with Tachyon <whatsnew315-sampling-profiler>, a high-frequency statistical sampling profiler, more color <whatsnew315-more-color> in command-line output, as well as the usual deprecations and removals, and improvements in user-friendliness and correctness.
This article doesn't attempt to provide a complete specification of all new features, but instead gives a convenient overview. For full details refer to the documentation, such as the Library Reference <library-index> and Language Reference <reference-index>. To understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented.
See Porting to Python 3.15 for guidance on upgrading from earlier versions of Python.
Interpreter improvements:
661:Add sentinel built-in type <whatsnew315-sentinel>686:Python now uses UTF-8 as the default encoding <whatsnew315-utf8-default>798:Unpacking in comprehensions <whatsnew315-unpacking-in-comprehensions>810:Explicit lazy imports for faster startup times <whatsnew315-lazy-imports>814:Add frozendict built-in type <whatsnew315-frozendict>829:Package startup configuration files <whatsnew315-startup-files>The experimental JIT compiler has been significantly upgraded <whatsnew315-jit>Improved error messages <whatsnew315-improved-error-messages>
Significant improvements in the standard library:
799:A dedicated profiling package for organizing Python profiling tools <whatsnew315-profiling-package>799:Tachyon: High-frequency statistical sampling profiler <whatsnew315-sampling-profiler>More color <whatsnew315-more-color>
New typing features:
728:TypedDict with typed extra items <whatsnew315-typeddict>747:Annotating type forms with TypeForm <whatsnew315-typeform>800:Disjoint bases in the type system <whatsnew315-disjoint-base>
C API improvements:
782:A new PyBytesWriter C API to create a Python bytes object <whatsnew315-pybyteswriter>788:Protection against finalization in the C API <whatsnew315-c-api-interpreter-finalization>803,820 <820>,793 <793>:Stable ABI for free-threaded builds <whatsnew315-abi3t>and related C API
Build changes:
831:Frame pointers are enabled by default for improved system-level observability <whatsnew315-frame-pointers>
Release changes:
The official Windows 64-bit binaries now use the tail-calling interpreter <whatsnew315-windows-tail-calling-interpreter>- The official macOS binaries now install free-threading support by default
New features
810: Explicit lazy imports
Large Python applications often suffer from slow startup times. A significant contributor to this problem is the import system: when a module is imported, Python must locate the file, read it from disk, compile it to bytecode, and execute all top-level code. For applications with deep dependency trees, this process can take seconds, even when most of the imported code is never actually used during a particular run.
Developers have worked around this by moving imports inside functions, using importlib to load modules on demand, or restructuring code to avoid unnecessary dependencies. These approaches work but make code harder to read and maintain, scatter import statements throughout the codebase, and require discipline to apply consistently.
Python now provides a cleaner solution through explicit lazy imports using the new lazy soft keyword. When you mark an import as lazy, Python defers the actual module loading until the imported name is first used. This gives you the organizational benefits of declaring all imports at the top of the file while only paying the loading cost for modules you actually use.
The lazy keyword works with both import and from ... import statements. When you write lazy import heavy_module, Python does not immediately load the module. Instead, it creates a lightweight proxy object. The actual module loading happens transparently when you first access the name:
lazy import json
lazy from pathlib import Path
print("Starting up...") # json and pathlib are not fully imported yet
data = json.loads('{"key": "value"}') # json gets fully imported here
p = Path(".") # pathlib gets fully imported here
This mechanism is particularly useful for applications that import many modules at the top level but may only use a subset of them in any given run. The deferred loading reduces startup latency without requiring code restructuring or conditional imports scattered throughout the codebase.
In the case where loading a lazily imported module fails (for example, if the module does not exist), Python raises the exception at the point of first use rather than at import time. The associated traceback includes both the location where the name was accessed and the original import statement, making it straightforward to diagnose and debug the failure.
For cases where you want to enable lazy loading globally without modifying source code, Python provides the -X lazy_imports <-X> command-line option and the PYTHON_LAZY_IMPORTS environment variable. Both accept two values: all makes all imports lazy by default, and normal (the default) respects the lazy keyword in source code. The sys.set_lazy_imports and sys.get_lazy_imports functions allow changing and querying this mode at runtime.
For more selective control, sys.set_lazy_imports_filter accepts a callable that determines whether a specific module should be loaded lazily. The filter receives three arguments: the importing module's name (or None), the imported module's name, and the fromlist (or None for regular imports). It should return True to allow the import to be lazy, or False to force eager loading. This allows patterns like making only your own application's modules lazy while keeping third-party dependencies eager:
import sys
def myapp_filter(importing, imported, fromlist):
return imported.startswith("myapp.")
sys.set_lazy_imports_filter(myapp_filter)
sys.set_lazy_imports("all")
import myapp.slow_module # lazy (matches filter)
import json # eager (does not match filter)
The proxy type itself is available as types.LazyImportType for code that needs to detect lazy imports programmatically.
There are some restrictions on where the lazy keyword can be used. Lazy imports are only permitted at module scope; using lazy inside a function, class body, or try/except/finally block raises a SyntaxError. Neither star imports nor future imports can be lazy (lazy from module import * and lazy from __future__ import ... both raise SyntaxError).
For code that cannot use the lazy keyword directly (for example, when supporting Python versions older than 3.15 while still using lazy imports on 3.15+), a module can define ~module.__lazy_modules__ as a container of fully qualified module name strings. Regular import statements for those modules are then treated as lazy, with the same semantics as the lazy keyword:
__lazy_modules__ = ["json", "pathlib"]
import json # lazy
import os # still eager
(Contributed by Pablo Galindo Salgado and Dino Viehland in 142349.)
810 for the full specification and rationale.
814: Add frozendict built-in type
A new immutable type, frozendict, is added to the builtins module. It does not allow modification after creation. A !frozendict is not a subclass of dict; it inherits directly from object. A !frozendict is hashable as long as all of its keys and values are hashable. A !frozendict preserves insertion order, but comparison does not take order into account.
For example:
>>> a = frozendict(x=1, y=2)
>>> a
frozendict({'x': 1, 'y': 2})
>>> a['z'] = 3
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
a['z'] = 3
~^^^^^
TypeError: 'frozendict' object does not support item assignment
>>> b = frozendict(y=2, x=1)
>>> hash(a) == hash(b)
True
>>> a == b
True
The following standard library modules have been updated to accept !frozendict: copy, decimal, json, marshal, plistlib (only for serialization), pickle, pprint and xml.etree.ElementTree.
eval and exec accept !frozendict for globals, and type and str.maketrans accept !frozendict for dict.
Code checking for dict type using isinstance(arg, dict) can be updated to isinstance(arg, (dict, frozendict)) to accept also the !frozendict type, or to isinstance(arg, collections.abc.Mapping) to accept also other mapping types such as ~types.MappingProxyType.
(Contributed by Victor Stinner and Donghee Na in 141510.)
814 for the full specification and rationale.
661: Add sentinel built-in type
A new sentinel type is added to the builtins module for creating unique sentinel values with a concise representation. Sentinel objects preserve identity when copied, support use in type expressions with the | operator, and can be pickled when they are importable by module and name.
(Contributed by Jelle Zijlstra in 148829; PEP 661 written by Tal Einat.)
661 for further details.
799: A dedicated profiling package
A new profiling module has been added to organize Python's built-in profiling tools under a single, coherent namespace. This module contains:
profiling.tracing: deterministic function-call tracing (relocated fromcProfile).profiling.sampling: a new statistical sampling profiler (named Tachyon).
The cProfile module remains as an alias for backwards compatibility. The profile module is deprecated and will be removed in Python 3.17.
(Contributed by Pablo Galindo and László Kiss Kollár in 138122.)
799 for further details.
Tachyon: High-frequency statistical sampling profiler
A new statistical sampling profiler (Tachyon) has been added as profiling.sampling. This profiler enables low-overhead performance analysis of running Python processes without requiring code modification or process restart.
Unlike deterministic profilers (such as profiling.tracing) that instrument every function call, the sampling profiler periodically captures stack traces from running processes. This approach provides virtually zero overhead while achieving sampling rates of up to 1,000,000 Hz, making it the fastest sampling profiler available for Python (at the time of its contribution) and ideal for debugging performance issues in production environments. This capability is particularly valuable for debugging performance issues in production systems where traditional profiling approaches would be too intrusive.
Key features include:
- Zero-overhead profiling: Attach to any running Python process without affecting its performance. Ideal for production debugging where you can't afford to restart or slow down your application.
- No code modification required: Profile existing applications without restart. Simply point the profiler at a running process by PID and start collecting data.
- Flexible target modes:
- Profile running processes by PID (
attach) - attach to already-running applications - Run and profile scripts directly (
run) - profile from the very start of execution - Execute and profile modules (
run -m) - profile packages run aspython -m module - Capture a one-shot snapshot of a running process (
dump) - print a traceback-style stack of every thread (or all asyncio tasks with--async-aware). Useful for investigating hung processes.
- Profile running processes by PID (
- Multiple profiling modes: Choose what to measure based on your performance investigation:
- Wall-clock time (
--mode wall, default): Measures real elapsed time including I/O, network waits, and blocking operations. Use this to understand where your program spends calendar time, including when waiting for external resources. - CPU time (
--mode cpu): Measures only active CPU execution time, excluding I/O waits and blocking. Use this to identify CPU-bound bottlenecks and optimize computational work. - GIL-holding time (
--mode gil): Measures time spent holding Python's Global Interpreter Lock. Use this to identify which threads dominate GIL usage in multi-threaded applications. - Exception handling time (
--mode exception): Captures samples only from threads with an active exception. Use this to analyze exception handling overhead.
- Wall-clock time (
- Thread-aware profiling: Option to profile all threads (
-a) or just the main thread, essential for understanding multi-threaded application behavior. - Multiple output formats: Choose the visualization that best fits your workflow:
--pstats: Detailed tabular statistics compatible withpstats. Shows function-level timing with direct and cumulative samples. Best for detailed analysis and integration with existing Python profiling tools.--collapsed: Generates collapsed stack traces (one line per stack). This format is specifically designed for creating flame graphs with external tools like Brendan Gregg's FlameGraph scripts or speedscope.--flamegraph: Generates a self-contained interactive HTML flame graph using D3.js. Opens directly in your browser for immediate visual analysis. Flame graphs show the call hierarchy where width represents time spent, making it easy to spot bottlenecks at a glance.--gecko: Generates Gecko Profiler format compatible with Firefox Profiler. Upload the output to Firefox Profiler for advanced timeline-based analysis with features like stack charts, markers, and network activity.--heatmap: Generates an interactive HTML heatmap visualization with line-level sample counts. Creates a directory with per-file heatmaps showing exactly where time is spent at the source code level.
- Live interactive mode: Real-time TUI profiler with a top-like interface (
--live). Monitor performance as your application runs with interactive sorting and filtering. - Async-aware profiling: Profile async/await code with task-based stack reconstruction (
--async-aware). See which coroutines are consuming time, with options to show only running tasks or all tasks including those waiting. - Opcode-level profiling: Gather bytecode opcode information for instruction-level profiling (
--opcodes). Shows which bytecode instructions are executing, including specializations from the adaptive interpreter.
See profiling.sampling for the complete documentation, including all available output formats, profiling modes, and configuration options.
(Contributed by Pablo Galindo and László Kiss Kollár in 135953 and 138122.)
831: Frame pointers enabled by default
CPython is now built with frame pointers by default on platforms that support them. This uses the compiler flags -fno-omit-frame-pointer and -mno-omit-leaf-frame-pointer, making native stack unwinding faster and more reliable for system profilers, debuggers, crash analysis tools, and eBPF-based observability tools.
The flags are exposed through sysconfig, so extension modules built by tools that consume Python's build configuration inherit frame pointers by default. This propagation is intentional: mixed Python/native profiling needs an unbroken frame-pointer chain through the interpreter, extension modules, embedding applications, and native libraries.
[!IMPORTANT] Third-party build backends and native build systems should preserve these flags when they consume Python's
sysconfigvalues. Build systems that compile C, C++, Rust, or other native code without inheriting Python's compiler flags should enable equivalent frame-pointer flags themselves. A single native component built without frame pointers can break stack unwinding for the whole Python process.
(Contributed by Pablo Galindo Salgado and Savannah Ostrowski in 149201; PEP 831 written by Pablo Galindo Salgado, Ken Jin, Savannah Ostrowski, and Diego Russo.)
831 for further details.
798: Unpacking in comprehensions
List, set, and dictionary comprehensions, as well as generator expressions, now support unpacking with * and **. This extends the unpacking syntax from 448 to comprehensions, providing a new syntax for combining an arbitrary number of iterables or dictionaries into a single flat structure. This new syntax is a direct alternative to nested comprehensions, itertools.chain, and itertools.chain.from_iterable. For example:
>>> lists = [[1, 2], [3, 4], [5]]
>>> [*L for L in lists] # equivalent to [x for L in lists for x in L]
[1, 2, 3, 4, 5]
>>> sets = [{1, 2}, {2, 3}, {3, 4}]
>>> {*s for s in sets} # equivalent to {x for s in sets for x in s}
{1, 2, 3, 4}
>>> dicts = [{'a': 1}, {'b': 2}, {'a': 3}]
>>> {**d for d in dicts} # equivalent to {k: v for d in dicts for k,v in d.items()}
{'a': 3, 'b': 2}
Generator expressions can similarly use unpacking to yield values from multiple iterables:
>>> gen = (*L for L in lists) # equivalent to (x for L in lists for x in L)
>>> list(gen)
[1, 2, 3, 4, 5]
This change also extends to asynchronous generator expressions, such that, for example, (*a async for a in agen()) is equivalent to (x async for a in agen() for x in a).
(Contributed by Adam Hartz in 143055.)
798 for further details.
829: Package startup configuration files
Loaded by the site module when -S is not given, .pth files <site-pth-files> can contain lines that both extend sys.path and execute arbitrary code when the line starts with import (followed by a space or tab). The latter functionality can be problematic, since it is difficult to know exactly what gets executed when Python starts up.
As a step towards improving the ability to audit pre-start executable code, Python 3.15 introduces .start files <site-start-files> which contain entry point specifications of the form pkg.mod:callable where pkg.mod is the import path to the given callable. When Python starts up, the callable is located and called with no arguments.
import lines in .pth files are silently deprecated. When a matching .start file is found, import lines in .pth files are ignored. There is no change to sys.path extension lines in .pth files.
The site module also provides site.StartupState to batch startup processing for multiple site directories, ensuring all static path extensions are applied before any startup code is executed. site.main uses an instance of this class implicitly to batch process all startup configuration files during normal interpreter startup. Callers needing the same batching behavior can build a ~site.StartupState directly and drive it with ~site.StartupState.addsitedir, ~site.StartupState.addusersitepackages, and ~site.StartupState.addsitepackages, then call ~site.StartupState.process once at the end of the batch.
(Contributed by Barry Warsaw in 148641 and 150228.)
803: Stable ABI for free-threaded builds
C extensions that target the Stable ABI <stable-abi> can now be compiled for the new Stable ABI for Free-Threaded Builds (also known as abi3t), which makes them compatible with free-threaded builds <free-threaded build> of CPython. This usually requires some non-trivial changes to the source code; specifically:
- Switching to API introduced in
697(Python 3.12), such as negative~PyType_Spec.basicsizeandPyObject_GetTypeData, rather than makingPyObjectpart of the instance struct; and - Switching from a
PyInit_function to a new export hook,PyModExport_* <PyModExport_modulename>, introduced for this purpose in793, with a newPySlotstructure introduced in820.
Note that Stable ABI does not offer all the functionality that CPython has to offer. Extensions that cannot switch to abi3t should continue to build for the existing Stable ABI (abi3) and the version-specific ABI for free-threading (cp315t) separately.
Stable ABI for Free-Threaded Builds should typically be selected in a build tool. Tools with abi3t support include meson-python, scikit-build-core, and Maturin; see abi3t-migration-build for links to their documentation on abi3t builds. If your build tool does not support abi3t, compile for cp315t separately. If not using a build tool -- or when writing such a tool -- you can select abi3t by setting the macro !Py_TARGET_ABI3T as discussed in abi3-compiling.
A practical migration guide <abi3t-migration-howto> for switching to abi3t is available. The community-maintained Python Free-Threading Guide provides examples of building and testing abi3t wheels.
803 for further details.
788: Protecting the C API from interpreter finalization
In the C API, interpreter finalization <interpreter shutdown> can be problematic for many extensions, because attaching <attached thread state> a thread state will permanently hang the thread, resulting in deadlocks and other spurious issues. Additionally, it has historically been impossible to safely check whether an interpreter is alive before using it, leading to crashes when a thread concurrently deletes an interpreter while another thread is trying to attach to it.
There are now several new suites of APIs to circumvent these problems:
Interpreter guards <interpreter-guards>, which prevent an interpreter from finalizing.Interpreter views <interpreter-views>, which allow thread-safe access to an interpreter that may be concurrently finalizing or deleted.New APIs <c-api-attach-detach>to automatically attach and detach thread states that come with built-in protection against finalization.
In addition, APIs in the PyGILState family (most notably PyGILState_Ensure and PyGILState_Release) have been soft deprecated. There is no plan to remove them, and existing code will continue to work, but there will be no new PyGILState APIs in future versions of Python.
(Contributed by Peter Bierma in 149101.)
788 for further details.
Improved error messages
-
The interpreter now provides more helpful suggestions in
AttributeErrorexceptions when accessing an attribute on an object that does not exist, but a similar attribute is available through one of its members.For example, if the object has an attribute that itself exposes the requested name, the error message will suggest accessing it via that inner attribute:
from dataclasses import dataclass from math import pi @dataclass class Circle: radius: float @property def area(self) -> float: return pi * self.radius**2 class Container: def __init__(self, inner: Circle) -> None: self.inner = inner circle = Circle(radius=4.0) container = Container(circle) print(container.area)Running this code now produces a clearer suggestion:
Traceback (most recent call last): File "example.py", line 18, in <module> print(container.area) ^^^^^^^^^^^^^^ AttributeError: 'Container' object has no attribute 'area'. Did you mean '.inner.area' instead of '.area'? -
When an
AttributeErroron a builtin type has no close match via Levenshtein distance, the error message now checks a static table of common method names from other languages (JavaScript, Java, Ruby, C#) and suggests the Python equivalent:>>> [1, 2, 3].push(4) # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?
>>> 'hello'.toUpperCase() # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'str' object has no attribute 'toUpperCase'. Did you mean '.upper'?
When the Python equivalent is a language construct rather than a method, the hint describes the construct directly:
>>> {}.put("a", 1) # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'dict' object has no attribute 'put'. Use d[k] = v.
When a mutable method is called on an immutable type, the hint suggests the mutable counterpart:
>>> (1, 2, 3).append(4) # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'tuple' object has no attribute 'append'. Did you mean to use a 'list' object?
These hints also work for subclasses of builtin types.
(Contributed by Matt Van Horn in
146406.) -
The interpreter now tries to provide a suggestion when
delattrfails due to a missing attribute. When an attribute name that closely resembles an existing attribute is used, the interpreter will suggest the correct attribute name in the error message. For example:>>> class A: ... pass >>> a = A() >>> a.abcde = 1 >>> del a.abcdf # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'A' object has no attribute 'abcdf'. Did you mean: 'abcde'?
(Contributed by Nikita Sobolev and Pranjal Prajapati in
136588.) -
Several error messages incorrectly using the term "argument" have been corrected. (Contributed by Stan Ulbrych in
133382.)
Other language changes
-
Python now uses UTF-8 as the default encoding, independent of the system's environment. This means that I/O operations without an explicit encoding, for example,
open('flying-circus.txt'), will use UTF-8. UTF-8 is a widely-supported Unicode character encoding that has become a de facto standard for representing text, including nearly every webpage on the internet, many common file formats, programming languages, and more.This only applies when no
encodingargument is given. For best compatibility between versions of Python, ensure that an explicitencodingargument is always provided. Theopt-in encoding warning <io-encoding-warning>can be used to identify code that may be affected by this change. The specialencoding='locale'argument uses the current locale encoding, and has been supported since Python 3.10.To retain the previous behaviour, Python's UTF-8 mode may be disabled with the
PYTHONUTF8=0 <PYTHONUTF8>environment variable or the-X utf8=0 <-X>command-line option.(Contributed by Adam Turner in
133711; PEP 686 written by Inada Naoki.)686for further details. -
The interpreter help (such as
python --help) is now in color. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in148766.) -
Unraisable exceptions are now highlighted with color by default. This can be controlled by
environment variables <using-on-controlling-color>. (Contributed by Peter Bierma in134170.) -
More color in
argparse <whatsnew315-color-argparse>,ast <whatsnew315-color-ast>,calendar <whatsnew315-color-calendar>,difflib <whatsnew315-color-difflib>,http.server <whatsnew315-color-http.server>,pickletools <whatsnew315-color-pickletools>,PyREPL tab completion <whatsnew315-pyrepl-completion>,python --help <whatsnew315-color-interpreter-help>,sqlite3 <whatsnew315-color-sqlite3>,timeit <whatsnew315-color-timeit>,tokenize <whatsnew315-color-tokenize>,unraisable exceptions <whatsnew315-color-exceptions>andstdlib(ast, compileall, doctest, gzip, inspect, json.tool, pdb, profiling.sampling, random, regrtest, sqlite3, timeit, tokenize, trace, unittest, uuid, zipapp, zipfile) CLI help. -
The
~object.__repr__ofImportErrorandModuleNotFoundErrornow shows "name" and "path" asname=<name>andpath=<path>if they were given as keyword arguments at construction time. (Contributed by Serhiy Storchaka, Oleg Iarygin, and Yoav Nir in74185.) -
The
~object.__dict__and!__weakref__descriptors now use a single descriptor instance per interpreter, shared across all types that need them. This speeds up class creation, and helps avoid reference cycles. (Contributed by Petr Viktorin in135228.) -
The
-Woption and thePYTHONWARNINGSenvironment variable can now specify regular expressions instead of literal strings to match the warning message and the module name, if the corresponding field starts and ends with a forward slash (/). (Contributed by Serhiy Storchaka in134716.) -
Functions that take timestamp or timeout arguments now accept any real numbers (such as
~decimal.Decimaland~fractions.Fraction), not only integers or floats, although this does not improve precision. (Contributed by Serhiy Storchaka in67795.)
-
Added
bytearray.take_bytes(n=None, /) <bytearray.take_bytes>to take bytes out of abytearraywithout copying. This enables optimizing code which must returnbytesafter working with a mutable buffer of bytes such as data buffering, network protocol parsing, encoding, decoding, and compression. Common code patterns which can be optimized with~bytearray.take_bytesare listed below.Suggested optimizing refactors Description Old New Return bytesafter working withbytearrayEmpty a buffer getting the bytes Split a buffer at a specific separator Split a buffer at a specific separator; discard after the separator (Contributed by Cody Maloney in
139871.) -
Many functions related to compiling or parsing Python code, such as
compile,ast.parse,symtable.symtable, andimportlib.abc.InspectLoader.source_to_code, now allow the module name to be passed. It is needed to unambiguouslyfilter <warning-filter>syntax warnings by module name. (Contributed by Serhiy Storchaka in135801.) -
Allowed defining the __dict__ and __weakref__
__slots__ <slots>for any class. (Contributed by Serhiy Storchaka in41779.) -
Allowed defining any
__slots__ <slots>for a class derived fromtuple(including classes created bycollections.namedtuple). (Contributed by Serhiy Storchaka in41779.) -
The
slicetype now supports subscription, making it ageneric type. (Contributed by James Hilton-Balfe in128335.) -
The class
memoryviewnow supports thefloat complexanddouble complexC types: formatting characters'Zf'and'Zd'respectively. (Contributed by Victor Stinner in146151and148675.) -
Allow the count argument of
bytes.replaceto be a keyword. (Contributed by Stan Ulbrych in147856.) -
Unary plus is now accepted in
matchliteral patterns, mirroring the existing support for unary minus. (Contributed by Bartosz Sławecki in145239.) -
The import system now acquires per-module locks in hierarchical order (parent packages before their submodules). This fixes a long-standing deadlock where one thread importing
pkg.suband another importingpkg.sub.modcould each block the other whenpkg/sub/__init__.pyimportspkg.sub.mod. (Contributed by Gregory P. Smith in83065.) -
File names of Stable ABI extensions that use the
.sosuffix may now include a multiarch tuple, for example,foo.abi3-x86-64-linux-gnu.so. This permits stable ABI extensions for multiple architectures to be co-installed into the same directory, without clashing with each other, as regular dynamic extensions do. (Contributed by Stefano Rivera in122931.) -
The
__cached__attribute on modules, which was deprecated since version 3.13, is no longer set or taken into consideration by the import system or standard library. Use__spec__.cached <importlib.machinery.ModuleSpec.cached>instead. (Contributed by Brett Cannon in97879.)Note that the
~module.__loader__and~module.__package__attributes are also deprecated and scheduled for removal.
Default interactive shell
- Tab completions are now colored by object kind, based on
fancycompleter. SetPYTHON_BASIC_COMPLETERto fall back torlcompleter. Color can also be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Antonio Cuni and Pablo Galindo in130472.) - Tab completion now suggests module attributes in
from ... importstatements. Attributes can only be suggested once the module is imported, sostdlibmodules are imported automatically, while for other modules the completer offers to import them whenTabis pressed a second time. (Contributed by Loïc Simon and Pablo Galindo in140870.)
New modules
math.integer
This module provides access to the mathematical functions for integer arguments (791). (Contributed by Serhiy Storchaka in 81313.)
Improved modules
argparse
- The
~argparse.BooleanOptionalActionaction now supports single-dash long options and alternate prefix characters. (Contributed by Serhiy Storchaka in138525.) - Changed the suggest_on_error parameter of
argparse.ArgumentParserto default toTrue. This enables suggestions for mistyped arguments by default. (Contributed by Jakob Schluse in140450.) - Added backtick markup support in
~argparse.ArgumentParserdescription and epilog text to highlight inline code when color output is enabled. (Contributed by Savannah Ostrowski in142390.) - Extended backtick markup to argument
helptext and added support for double backticks (RST inline-literal style). (Contributed by Hugo van Kemenade in149375.)
array
- Support the
float complexanddouble complexC types: formatting characters'Zf'and'Zd'respectively. (Contributed by Victor Stinner in146151and148675.) - Support half-floats (16-bit IEEE 754 binary interchange format): formatting character
'e'. (Contributed by Sergey B Kirpichev in146238.) - The
array.typecodestype changed fromstrtotupleto support type codes longer than 1 character (ZfandZd). (Contributed by Victor Stinner in148675.)
ast
- Add color parameter to
~ast.dump. IfTrue, the returned string is syntax highlighted using ANSI escape sequences. IfFalse(the default), colored output is always disabled. (Contributed by Stan Ulbrych in148981.) - The
command-line <ast-cli>output is now syntax highlighted by default. This can becontrolled using environment variables <using-on-controlling-color>. (Contributed by Stan Ulbrych in148981.)
asyncio
- Added
TaskGroup.cancel <asyncio.TaskGroup.cancel>to allow early termination of a task group, for instance, when the goal of the tasks has been achieved or their services are no longer needed. Previously this would involve unintuitive boilerplate such as an extra task raising a custom exception which is then suppressed as it exits the task group. (Contributed by John Belmonte in127214.)
base64
- Added the pad parameter in
~base64.z85encode. (Contributed by Hauke Dämpfling in143103.) - Added the padded parameter in
~base64.b32encode,~base64.b32decode,~base64.b32hexencode,~base64.b32hexdecode,~base64.b64encode,~base64.b64decode,~base64.urlsafe_b64encode, and~base64.urlsafe_b64decode. (Contributed by Serhiy Storchaka in73613.) - Added the wrapcol parameter in
~base64.b16encode,~base64.b32encode,~base64.b32hexencode,~base64.b64encode,~base64.b85encode, and~base64.z85encode. (Contributed by Serhiy Storchaka in143214and146431.) - Added the ignorechars parameter in
~base64.b16decode,~base64.b32decode,~base64.b32hexdecode,~base64.b64decode,~base64.b85decode, and~base64.z85decode. (Contributed by Serhiy Storchaka in144001and146431.) - Added the canonical parameter in
~base64.b32decode,~base64.b32hexdecode,~base64.b64decode,~base64.a85decode,~base64.b85decode, and~base64.z85decode, to reject encodings with non-zero padding bits or other non-canonical forms. (Contributed by Gregory P. Smith in146311.)
binascii
-
Added functions for Base32 encoding:
~binascii.b2a_base32and~binascii.a2b_base32
(Contributed by James Seo in
146192.) -
Added functions for Ascii85, Base85, and Z85 encoding:
~binascii.b2a_ascii85and~binascii.a2b_ascii85~binascii.b2a_base85and~binascii.a2b_base85
(Contributed by James Seo and Serhiy Storchaka in
101178.) -
Added the padded parameter in
~binascii.b2a_base32,~binascii.a2b_base32,~binascii.b2a_base64, and~binascii.a2b_base64. (Contributed by Serhiy Storchaka in73613.) -
Added the wrapcol parameter in
~binascii.b2a_base64. (Contributed by Serhiy Storchaka in143214.) -
Added the alphabet parameter in
~binascii.b2a_base64and~binascii.a2b_base64. (Contributed by Serhiy Storchaka in145980.) -
Added the ignorechars parameter in
~binascii.a2b_hex,~binascii.unhexlify, and~binascii.a2b_base64. (Contributed by Serhiy Storchaka in144001and146431.) -
Added the canonical parameter in
~binascii.a2b_base64, to reject encodings with non-zero padding bits. (Contributed by Gregory P. Smith in146311.)
calendar
calendar'scommand-line <calendar-cli>text output has more color. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in148352.)- The
calendar'scommand-line <calendar-cli>HTML output now accepts the year-month option:python -m calendar -t html 2009 06. (Contributed by Pål Grønås Drange in140212.) - Calendar pages generated by the
calendar.HTMLCalendarclass now support dark mode and have been migrated to the HTML5 standard for improved accessibility. (Contributed by Jiahao Li and Hugo van Kemenade in137634.)
collections
- Added
!collections.Counter.__xor__and!collections.Counter.__ixor__to compute the symmetric difference between~collections.Counterobjects. (Contributed by Raymond Hettinger in138682.)
concurrent.futures
- Improved error reporting when a child process in a
concurrent.futures.ProcessPoolExecutorterminates abruptly. The resulting traceback will now tell you the PID and exit code of the terminated process. (Contributed by Jonathan Berg in139486.)
contextlib
- Added support for arbitrary descriptors
!__enter__,!__exit__,!__aenter__, and!__aexit__in~contextlib.ExitStackandcontextlib.AsyncExitStack, for consistency with thewithandasync withstatements. (Contributed by Serhiy Storchaka in144386.) ~contextlib.ContextDecoratorand~contextlib.AsyncContextDecorator(and therefore~contextlib.contextmanagerand~contextlib.asynccontextmanagerused as decorators) now detect generator functions, coroutine functions, and asynchronous generator functions and keep the context manager open across iteration or await. Previously the context manager exited as soon as the generator or coroutine object was created. (Contributed by Alex Grönholm & Gregory P. Smith in125862.)
ctypes
- Change the
~ctypes._SimpleCData._type_of~ctypes.c_float_complex,~ctypes.c_double_complexand~ctypes.c_longdouble_complexfromF,DandGtoZf,ZdandZgfor compatibility with NumPy. (Contributed by Victor Stinner in148675.)
dataclasses
- Annotations for generated
__init__methods no longer include internal type names. (Contributed by David Ellis in137530.)
dbm
- Added new
!reorganizemethods todbm.dumbanddbm.sqlite3to recover unused free space previously occupied by deleted entries. (Contributed by Andrea Oliveri in134004.)
difflib
- Introduced the optional color parameter to
difflib.unified_diff, enabling color output similar togit diff. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Douglas Thor in133725.) - Improved the styling of HTML diff pages generated by the
difflib.HtmlDiffclass, and migrated the output to the HTML5 standard. (Contributed by Jiahao Li in134580.)
- Email generators now raise an error when an
.EmailMessagecannot be accurately flattened due to a non-ASCII email address (mailbox) in an address header. Options for supporting Email Address Internationalization (EAI) are discussed in.EmailPolicy.utf8. (Contributed by R David Murray and Mike Edmunds in122540.)
faulthandler
- Added the max_threads parameter in
faulthandler.enable,faulthandler.dump_traceback,faulthandler.dump_traceback_later, andfaulthandler.register. (Contributed by Eric Froemling in149085.)
functools
~functools.singledispatchmethodnow supports non-descriptorcallables. (Contributed by Serhiy Storchaka in140873.)~functools.singledispatchmethodnow dispatches on the second argument if it wraps a regular method and is called as a class attribute. (Contributed by Bartosz Sławecki in143535.)
gc
- Python 3.14.0-3.14.4 shipped with a new incremental garbage collector. However, due to a number of reports of significant memory pressure in production environments, it has been reverted back to the generational GC from 3.13. This is the GC now used in Python 3.14.5 and later and Python 3.15. (Contributed by Sergey Miryanov in
148726.)
hashlib
- Ensure that hash functions guaranteed to be always available exist as attributes of
hashlibeven if they will not work at runtime due to missing backend implementations. For instance,hashlib.md5will no longer raiseAttributeErrorif OpenSSL is not available and Python has been built without MD5 support. (Contributed by Bénédikt Tran in136929.)
http.client
- A new max_response_headers keyword-only parameter has been added to
~http.client.HTTPConnectionand~http.client.HTTPSConnectionconstructors. This parameter overrides the default maximum number of allowed response headers. (Contributed by Alexander Enrique Urieles Nieto in131724.)
http.server
- The logging of
~http.server.BaseHTTPRequestHandler, as used by thecommand-line interface <http-server-cli>, is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in146292.) - Added
~http.server.SimpleHTTPRequestHandler.default_content_typeand the--content-type <http.server --content-type>command-line option to allow customizing the defaultContent-Typeheader for files with unknown extensions. (Contributed by John Comeau and Hugo van Kemenade in113471.) - Add a new
extra_response_headerskeyword argument to~http.server.SimpleHTTPRequestHandlerto support custom headers in HTTP responses. (Contributed by Anton I. Sipos in135057.) - Add a
-H/--header <http.server --header>option to thepython -m http.servercommand-line interface to support custom headers in HTTP responses. (Contributed by Anton I. Sipos in135057.)
importlib.metadata
- Previously, when accessing a distribution metadata directory not containing a metadata file,
metadata()andDistribution.metadatawould return an emptyPackageMetadataobject as if the file was present but empty. Now, aMetadataNotFoundexception is raised. See importlib_metadata#493 for background and rationale and143387for rationale on the compatibility concerns. (Contributed by Jason R. Coombs.)
inspect
- Add parameters inherit_class_doc and fallback_to_class_doc for
~inspect.getdoc. (Contributed by Serhiy Storchaka in132686.)
json
- Add the array_hook parameter to
~json.loadand~json.loadsfunctions: allow a callback for JSON literal array types to customize Python lists in the resulting decoded object. Passing combinedfrozendictto object_pairs_hook parameter andtupleto array_hook will yield a deeply nested immutable Python structure representing the JSON data. (Contributed by Joao S. O. Bueno in146440.)
locale
~locale.setlocalenow supports language codes with@-modifiers.@-modifiers are no longer silently removed in~locale.getlocale, but included in the language code. (Contributed by Serhiy Storchaka in137729.)- Undeprecate the
locale.getdefaultlocalefunction. (Contributed by Victor Stinner in130796.)
math
- Add
math.isnormalandmath.issubnormalfunctions. (Contributed by Sergey B Kirpichev in132908.) - Add
math.fmax,math.fminandmath.signbitfunctions. (Contributed by Bénédikt Tran in135853.)
mimetypes
- Add more MIME types. (Contributed by Benedikt Johannes, Charlie Lin, Foolbar, Gil Forcada and John Franey in
144217,145720,140937,139959,145698,145718,145918, and144213.) - Rename
application/x-texinfotoapplication/texinfo. (Contributed by Charlie Lin in140165.) - Changed the MIME type for
.aifiles toapplication/pdf. (Contributed by Stan Ulbrych in141239.)
mmap
mmap.mmapnow has a trackfd parameter on Windows; if it isFalse, the file handle corresponding to fileno will not be duplicated. (Contributed by Serhiy Storchaka in78502.)- Added the
mmap.mmap.set_namemethod to annotate an anonymous memory mapping if Linux kernel supportsPR_SET_VMA_ANON_NAME <PR_SET_VMA(2const)>(Linux 5.17 or newer). (Contributed by Donghee Na in142419.)
os
- Add
os.statxon Linux kernel versions 4.11 and later with glibc versions 2.28 and later. (Contributed by Jeffrey Bosboom and Victor Stinner in83714.) os.makedirsfunction now has a parent_mode parameter that allows specifying the mode for intermediate directories. This can be used to match the behavior from Python 3.6 and earlier by passingparent_mode=mode. (Contributed by Zackery Spytz and Gregory P. Smith in86533.)
os.path
- Add support of the all-but-last mode in
~os.path.realpath. (Contributed by Serhiy Storchaka in71189.) - The strict parameter to
os.path.realpathaccepts a new value,os.path.ALLOW_MISSING. If used, errors other thanFileNotFoundErrorwill be re-raised; the resulting path can be missing but it will be free of symlinks. (Contributed by Petr Viktorin for2025-4517.)
pathlib
pathlib.Path.mkdirnow has a parent_mode parameter that allows specifying the mode for intermediate directories whenparents=True. (Contributed by Gregory P. Smith in86533.)
pdb
- Use the new interactive shell as the default input shell for
pdb. (Contributed by Tian Gao in145379.)
pickle
- Add support for pickling private methods and nested classes. (Contributed by Zackery Spytz and Serhiy Storchaka in
77188.)
pickletools
- The output of the
pickletoolscommand-line interface is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in149026.)
pprint
- Add an expand keyword argument for
pprint.pprint,pprint.pformat,pprint.pp. If true, the output will be formatted similar to pretty-printedjson.dumpswhen indent is supplied. (Contributed by Stefan Todoran, Semyon Moroz and Hugo van Kemenade in112632.) - Add t-string support to
pprint. (Contributed by Loïc Simon and Hugo van Kemenade in134551.)
re
re.prefixmatchand a correspondingre.Pattern.prefixmatchhave been added as alternate, more explicit names for the existing and nowsoft deprecatedre.matchandre.Pattern.matchAPIs. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search. (Contributed by Gregory P. Smith in86519.)
resource
- Add new constants:
~resource.RLIMIT_NTHR,~resource.RLIMIT_UMTXP,~resource.RLIMIT_THREADS,~resource.RLIM_SAVED_CUR, and~resource.RLIM_SAVED_MAX. (Contributed by Serhiy Storchaka in137512.)
shelve
- Added new
!reorganizemethod toshelveused to recover unused free space previously occupied by deleted entries. (Contributed by Andrea Oliveri in134004.) - Add support for custom serialization and deserialization functions in the
shelvemodule. (Contributed by Furkan Onder in99631.)
shutil
shutil.copyfilenow also raises~shutil.SpecialFileErrorfor sockets and device files. (Contributed by Savannah Ostrowski in142693.)
socket
- Add constants for the ISO-TP CAN protocol. (Contributed by Patrick Menschel and Stefan Tatschner in
86819.)
sqlite3
-
The
command-line interface <sqlite3-cli>has several new features:- SQL keyword completion on
Tab. (Contributed by Long Tan in133393.)
- Prompts, error messages, and help text are now colored. This is enabled by default, see
using-on-controlling-colorfor details. (Contributed by Stan Ulbrych and Łukasz Langa in133461.) - Table, index, trigger, view, column, function, and schema completion on
Tab. (Contributed by Long Tan in136101.)
- SQL keyword completion on
ssl
-
Indicate through
ssl.HAS_PSK_TLS13whether thesslmodule supports "External PSKs" in TLSv1.3, as described in9258. (Contributed by Will Childs-Klein in133624.) -
Added new methods for managing groups used for SSL key agreement:
ssl.SSLContext.set_groupssets the groups allowed for doing key agreement, extending the previousssl.SSLContext.set_ecdh_curvemethod. This new API provides the ability to list multiple groups and supports fixed-field and post-quantum groups in addition to ECDH curves. This method can also be used to control what key shares are sent in the TLS handshake.ssl.SSLSocket.groupreturns the group selected for doing key agreement on the current connection after the TLS handshake completes. This call requires OpenSSL 3.2 or later.ssl.SSLContext.get_groupsreturns a list of all available key agreement groups compatible with the minimum and maximum TLS versions currently set in the context. This call requires OpenSSL 3.5 or later.
(Contributed by Ron Frederick in
136306.) -
Added a new method
ssl.SSLContext.set_ciphersuitesfor setting TLS 1.3 ciphers. For TLS 1.2 or earlier,ssl.SSLContext.set_ciphersshould continue to be used. Both calls can be made on the same context and the selected cipher suite will depend on the TLS version negotiated when a connection is made. (Contributed by Ron Frederick in137197.) -
Added new methods for managing signature algorithms:
ssl.get_sigalgsreturns a list of all available TLS signature algorithms. This call requires OpenSSL 3.4 or later.ssl.SSLContext.set_client_sigalgssets the signature algorithms allowed for certificate-based client authentication.ssl.SSLContext.set_server_sigalgssets the signature algorithms allowed for the server to complete the TLS handshake.ssl.SSLSocket.client_sigalgreturns the signature algorithm selected for client authentication on the current connection. This call requires OpenSSL 3.5 or later.ssl.SSLSocket.server_sigalgreturns the signature algorithm selected for the server to complete the TLS handshake on the current connection. This call requires OpenSSL 3.5 or later.
(Contributed by Ron Frederick in
138252.)
subprocess
-
subprocess.Popen.wait: whentimeoutis notNoneand the platform supports it, an efficient event-driven mechanism is used to wait for process termination:- Linux >= 5.3 uses
os.pidfd_open+select.poll. - macOS and other BSD variants use
select.kqueue+KQ_FILTER_PROC+KQ_NOTE_EXIT. - Windows keeps using
WaitForSingleObject(unchanged).
If none of these mechanisms are available, the function falls back to the traditional busy loop (non-blocking call and short sleeps). (Contributed by Giampaolo Rodola in
83069.) - Linux >= 5.3 uses
symtable
- Add
symtable.Function.get_cellsandsymtable.Symbol.is_cellmethods. (Contributed by Yashp002 in143504.)
sys
- Add
sys.abi_infonamespace to improve access to ABI information. (Contributed by Klaus Zimmermann in137476.)
sys.monitoring
- The
other events <monitoring-event-global>(PY_THROW,PY_UNWIND,RAISE,EXCEPTION_HANDLED, andRERAISE) can now be turned on and disabled on a per code object basis. Returning~sys.monitoring.DISABLEfrom a callback for one of these events disables the event for the entire code object (for the current tool), rather than raisingValueErroras in prior versions. (Contributed by Gabriele N. Tornetta in146182.)
tarfile
~tarfile.data_filternow normalizes symbolic link targets in order to avoid path traversal attacks. (Contributed by Petr Viktorin in127987and2025-4138.)~tarfile.TarFile.extractallnow skips fixing up directory attributes when a directory was removed or replaced by another kind of file. (Contributed by Petr Viktorin in127987and2024-12718.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallnow (re-)apply the extraction filter when substituting a link (hard or symbolic) with a copy of another archive member, and when fixing up directory attributes. The former raises a new exception,~tarfile.LinkFallbackError. (Contributed by Petr Viktorin for2025-4330and2024-12718.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallno longer extract rejected members when~tarfile.TarFile.errorlevelis zero. (Contributed by Matt Prodani and Petr Viktorin in112887and2025-4435.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallnow replace slashes with backslashes in symlink targets on Windows to prevent creation of corrupted links. (Contributed by Christoph Walcher in57911.)~tarfile.TarFile.gettarinfonow replaces backslashes with slashes in symlink targets on Windows to conform to the tar format standard. (Contributed by Daniele Nicolodi in151669.)
threading
- Added
~threading.serialize_iterator,~threading.synchronized_iterator, and~threading.concurrent_teeto support concurrent access to generators and iterators. (Contributed by Raymond Hettinger in124397.)
timeit
- The output of the
timeitcommand-line interface is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in146609.) - The command-line interface now colorizes error tracebacks by default. This can be controlled with
environment variables <using-on-controlling-color>. (Contributed by Yi Hong in139374.) - Make the target time of
timeit.Timer.autorangeconfigurable and add--target-timeoption to the command-line interface. (Contributed by Alessandro Cucci and Miikka Koskinen in80642.)
tkinter
- The
!tkinter.Text.searchmethod now supports two additional arguments: nolinestop which allows the search to continue across line boundaries; and strictlimits which restricts the search to within the specified range. (Contributed by Rihaan Meher in130848.) - A new method
!tkinter.Text.search_allhas been introduced. This method allows for searching for all matches of a pattern using Tcl's-alland-overlapoptions. (Contributed by Rihaan Meher in130848.) - Added new methods
!pack_content,!place_contentand!grid_contentwhich use Tk commands with new names (introduced in Tk 8.6) instead of!*_slavesmethods which use Tk commands with outdated names. (Contributed by Serhiy Storchaka in143754.) - Added
!Eventattributes!user_datafor Tk virtual events and!detailforEnter,Leave,FocusIn,FocusOut, andConfigureRequestevents. (Contributed by Matthias Kievernagel and Serhiy Storchaka in47655.)
tokenize
- The output of the
tokenizecommand-line interface <tokenize-cli>is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in148991.)
tomllib
-
The
tomllibmodule now supports TOML 1.1.0. This is a backwards compatible update, meaning that all valid TOML 1.0.0 documents are parsed the same way.The changes, according to the official TOML changelog, are:
-
Allow newlines and trailing commas in inline tables.
Previously an inline table had to be on a single line and couldn't end with a trailing comma. This is now relaxed so that the following is valid:
tbl = { key = "a string", moar-tbl = { key = 1, }, } -
Add
\xHHnotation to basic strings for codepoints under 255, and the\eescape for the escape character:null = "null byte: \x00; letter a: \x61" csi = "\e[" -
Seconds in datetime and time values are now optional. The following are now valid:
dt = 2010-02-03 14:15 t = 14:15
(Contributed by Taneli Hukkinen in
142956.) -
types
- Expose the write-through
localsproxy type astypes.FrameLocalsProxyType. This represents the type of theframe.f_localsattribute, as described in667. (Contributed by Peter Bierma in136492.)
typing
-
747: Add~typing.TypeForm, a new special form for annotating values that are themselves type expressions.TypeForm[T]means "a type form object describingT(or a type assignable toT)". At runtime,TypeForm(x)simply returnsx, which allows explicit annotation of type-form values without changing behavior.This helps libraries that accept user-provided type expressions (for example
int,str | None,~typing.TypedDictclasses, orlist[int]) expose precise signatures:from typing import Any, TypeForm def cast[T](typ: TypeForm[T], value: Any) -> T: ...(Contributed by Jelle Zijlstra in
145033.)
728: Add support in~typing.TypedDictfor the closed and extra_items class arguments. A closed~typing.TypedDictdoes not allow extra keys beyond those specified in the class body, while a~typing.TypedDictwithextra_itemsallows arbitrary extra items where the values are of the specified type. (Contributed by Angela Liss in137840.)- Code like
class ExtraTypeVars(P1[S], Protocol[T, T2]): ...now raises aTypeError, becauseSis not listed inProtocolparameters. (Contributed by Nikita Sobolev in137191.) - Code like
class B2(A[T2], Protocol[T1, T2]): ...now correctly handles type parameters order: it is(T1, T2), not(T2, T1)as it was incorrectly inferred at runtime before. (Contributed by Nikita Sobolev in137191.) 800: Addtyping.disjoint_base, a new decorator marking a class as a disjoint base. This is an advanced feature primarily intended to allow type checkers to faithfully reflect the runtime semantics of types defined as builtins or in compiled extensions. If a classCis a disjoint base, then child classes of that class cannot inherit from other disjoint bases that are not parent or child classes ofC. (Contributed by Jelle Zijlstra in148639.)~typing.TypeVarTuplenow acceptsbound,covariant,contravariant, andinfer_variancekeyword arguments, matching the interface of~typing.TypeVarand~typing.ParamSpec.boundsemantics remain undefined in the specification.
unicodedata
- The Unicode database has been updated to Unicode 17.0.0. (Contributed by Benjamin Peterson in
138706.) - Add
unicodedata.isxidstartandunicodedata.isxidcontinuefunctions to check whether a character can start or continue a Unicode Standard Annex #31 identifier. (Contributed by Stan Ulbrych in129117.) - Add the
~unicodedata.iter_graphemesfunction to iterate over grapheme clusters according to rules defined in Unicode Standard Annex #29, "Unicode Text Segmentation". Add~unicodedata.grapheme_cluster_break,~unicodedata.indic_conjunct_breakand~unicodedata.extended_pictographicfunctions to get the properties of the character which are related to the above algorithm. (Contributed by Serhiy Storchaka and Guillaume Sanchez in74902.) - Add
~unicodedata.blockfunction to return the Unicode block assigned to a character. (Contributed by Stan Ulbrych in66802.)
unittest
unittest.TestCase.assertLogswill now accept a formatter to control how messages are formatted. (Contributed by Garry Cairns in134567.)unittest.TestCase.assertWarnsandunittest.TestCase.assertWarnsRegexno longer swallow warnings that do not match the specified category or regex. Nested context managers are now supported. (Contributed by Serhiy Storchaka in143231.)
urllib.parse
- Add the missing_as_none parameter to
~urllib.parse.urlsplit,~urllib.parse.urlparseand~urllib.parse.urldefragfunctions. Add the keep_empty parameter to~urllib.parse.urlunsplitand~urllib.parse.urlunparsefunctions. This allows distinguishing between empty and undefined URI components and preserving empty components. (Contributed by Serhiy Storchaka in67041.)
venv
- On POSIX platforms, platlib directories will be created if needed when creating virtual environments, instead of using a
lib64 -> libsymlink. This means purelib and platlib of virtual environments no longer share the samelibdirectory on platforms wheresys.platlibdiris not equal tolib. (Contributed by Rui Xi in133951.)
warnings
- Improve filtering by module in
warnings.warn_explicitif no module argument is passed. It now tests the module regular expression in the warnings filter not only against the filename with.pystripped, but also against module names constructed starting from different parent directories of the filename (with/__init__.py,.pyand, on Windows,.pywstripped). (Contributed by Serhiy Storchaka in135801.)
wave
- Added support for IEEE floating-point WAVE audio (
WAVE_FORMAT_IEEE_FLOAT) inwave. - Added
wave.Wave_read.getformat,wave.Wave_write.getformat, andwave.Wave_write.setformatfor explicit frame format handling. wave.Wave_write.setparamsaccepts both 7-item tuples includingformatand 6-item tuples for backwards compatibility (defaulting toWAVE_FORMAT_PCM).WAVE_FORMAT_IEEE_FLOAToutput now includes afactchunk, as required for non-PCM WAVE formats.
(Contributed by Lionel Koenig and Michiel W. Beijen in 60729.)
webbrowser
- On macOS, the new
!webbrowser.MacOSclass opens URLs via/usr/bin/openinstead of constructing and executing AppleScript viaosascript. The default browser is detected from the LaunchServices preferences file usingplistlib, with!com.apple.Safarias the fallback on fresh installations. For non-HTTP(S) URLs,open -b <bundle-id>is used to route the URL through a browser rather than the OS file handler, preventing file injection attacks. (Contributed by Jeff Lyon in137586.)
xml
- Add the
xml.is_valid_namefunction to check whether a string can be used as an element or attribute name in XML. (Contributed by Serhiy Storchaka in139489.) - Add the
xml.is_valid_textfunction to check whether a string can be used in an XML document. (Contributed by Serhiy Storchaka in139489.)
xml.parsers.expat
- Add
~xml.parsers.expat.xmlparser.SetAllocTrackerActivationThresholdand~xml.parsers.expat.xmlparser.SetAllocTrackerMaximumAmplificationtoxmlparser <xmlparser-objects>objects to tune protections against disproportional amounts of dynamic memory usage from within an Expat parser. (Contributed by Bénédikt Tran in90949.) - Add
~xml.parsers.expat.xmlparser.SetBillionLaughsAttackProtectionActivationThresholdand~xml.parsers.expat.xmlparser.SetBillionLaughsAttackProtectionMaximumAmplificationtoxmlparser <xmlparser-objects>objects to tune protections against billion laughs attacks. (Contributed by Bénédikt Tran in90949.)
zlib
- Allow combining two Adler-32 checksums via
~zlib.adler32_combine. (Contributed by Callum Attryde and Bénédikt Tran in134635.) - Allow combining two CRC-32 checksums via
~zlib.crc32_combine. (Contributed by Bénédikt Tran in134635.)
Optimizations
mimallocis now used as the default allocator for raw memory allocations such as viaPyMem_RawMallocfor better performance onfree-threaded builds <free-threaded build>. (Contributed by Kumar Aditya in144914.)
base64 & binascii
- CPython's underlying base64 implementation now encodes 2x faster and decodes 3x faster thanks to simple CPU pipelining optimizations. (Contributed by Gregory P. Smith and Serhiy Storchaka in
143262.) - Implementation for Ascii85, Base85, and Z85 encoding has been rewritten in C. Encoding and decoding is now two orders of magnitude faster and consumes two orders of magnitude less memory. (Contributed by James Seo and Serhiy Storchaka in
101178.) - Implementation for Base32 has been rewritten in C. Encoding and decoding is now two orders of magnitude faster. (Contributed by James Seo in
146192.)
csv
csv.Sniffer.sniffdelimiter detection is now up to 1.6x faster. (Contributed by Maurycy Pawłowski-Wieroński in137628.)
Upgraded experimental JIT compiler
Results from the pyperformance benchmark suite report a 7-8% geometric mean performance improvement for the JIT over the standard CPython interpreter built with all optimizations enabled on x86-64 Linux. On AArch64 macOS, the JIT has an 11-12% speedup over the tail calling interpreter <whatsnew314-tail-call-interpreter> with all optimizations enabled. The speedups for JIT builds versus no JIT builds range from roughly 15% slowdown to over 100% speedup (ignoring the unpack_sequence microbenchmark) on x86-64 Linux and AArch64 macOS systems.
The major upgrades to the JIT are:
- LLVM 21 build-time dependency
- New tracing frontend
- Basic register allocation in the JIT
- More JIT optimizations
- GDB and GNU
backtrace()unwinding support - Better machine code generation
LLVM 21 build-time dependency
The JIT compiler now uses LLVM 21 for build-time stencil generation. As always, LLVM is only needed when building CPython with the JIT enabled; end users running Python do not need LLVM installed. Instructions for installing LLVM can be found in the JIT compiler documentation for all supported platforms. (Contributed by Savannah Ostrowski in 140973.)
A new tracing frontend
The JIT compiler now supports significantly more bytecode operations and control flow than in Python 3.14, enabling speedups on a wider variety of code. For example, simple Python object creation is now understood by the 3.15 JIT compiler. Overloaded operations and generators are also partially supported. This was made possible by an overhauled JIT tracing frontend that records actual execution paths through code, rather than estimating them as the previous implementation did. (Contributed by Ken Jin in 139109. Support for Windows added by Mark Shannon in 141703.)
Basic register allocation in the JIT
A basic form of register allocation has been added to the JIT compiler's optimizer. This allows the JIT compiler to avoid certain stack operations altogether and instead operate on registers. This allows the JIT to produce more efficient traces by avoiding reads and writes to memory. (Contributed by Mark Shannon in 135379.)
More JIT optimizations
More constant-propagation is now performed. This means when the JIT compiler detects that certain user code results in constants, the code can be simplified by the JIT. (Contributed by Ken Jin and Savannah Ostrowski in 132732.)
Reference counts <reference count> are avoided whenever it is safe to do so. This generally reduces the cost of most operations in Python. (Contributed by Ken Jin, Donghee Na, Zheao Li, Hai Zhu, Savannah Ostrowski, Reiden Ong, Noam Cohen, Tomas Roun, PuQing, Cajetan Rodrigues, and Sacul in 134584.)
By tracking unique references to objects, the JIT optimizer can now eliminate reference count updates and perform in-place operations on ints and floats. (Contributed by Reiden Ong, and Pieter Eendebak in 143414 and 146306.)
The JIT optimizer now supports significantly more operations than in 3.14. (Contributed by Kumar Aditya, Ken Jin, Jiahao Li, and Sacul in 131798.)
GDB and GNU backtrace() unwinding support
The JIT compiler now publishes unwind information for generated machine code to the GDB interface on supported Linux ELF platforms. When libgcc frame registration is available, the same unwind information is also registered for GNU backtrace() stack walkers. This allows native debuggers, crash handlers, and diagnostic tools using these mechanisms to unwind through JIT frames instead of stopping at generated code. (Contributed by Diego Russo and Pablo Galindo Salgado in 146071 and 149104.)
Better machine code generation
The JIT compiler's machine code generator now produces better machine code for x86-64 and AArch64 macOS and Linux targets. In general, users should experience lower memory usage for generated machine code and more efficient machine code versus 3.14. (Contributed by Brandt Bucher in 136528 and 135905. Implementation for AArch64 contributed by Mark Shannon in 139855. Additional optimizations for AArch64 contributed by Mark Shannon and Diego Russo in 140683 and 142305.)
Maintainability
The JIT optimizer's operations have been simplified. This was made possible by a refactoring of JIT data structures. (Contributed by Zhongtian Zheng in 148211 and Hai Zhu in 143421.)
Removed
ast
- The constructors of
AST nodes <ast_nodes>now raise aTypeErrorwhen a required argument is omitted or when a keyword argument that does not map to a field on the AST node is passed. These cases had previously raised aDeprecationWarningsince Python 3.13. (Contributed by Brian Schubert and Jelle Zijlstra in137600and105858.)
collections.abc
collections.abc.ByteStringhas been removed fromcollections.abc.__all__.!collections.abc.ByteStringhas been deprecated since Python 3.12, and is scheduled for removal in Python 3.17. (Contributed by Alex Waygood in118803.)
ctypes
- Removed the undocumented function
!ctypes.SetPointerType, which has been deprecated since Python 3.13. (Contributed by Bénédikt Tran in133866.)
datetime
~datetime.datetime.strptimenow raisesValueErrorwhen the format string contains%d(day of month) without a year directive. This has been deprecated since Python 3.13. (Contributed by Stan Ulbrych and Gregory P. Smith in70647.)
glob
- Removed the undocumented
!glob.glob0and!glob.glob1functions, which have been deprecated since Python 3.13. Useglob.globand pass a directory to its root_dir argument instead. (Contributed by Barney Gale in137466.)
http.server
- Removed the
!CGIHTTPRequestHandlerclass and the--cgiflag from thepython -m http.servercommand-line interface. They were deprecated in Python 3.13. (Contributed by Bénédikt Tran in133810.)
importlib
- The
load_module()methods of~importlib.abc.Loaderand its subclasses is removed. The import system will no longer call it when defined on custom subclasses. The method has been deprecated in favor of~importlib.abc.Loader.exec_modulesince Python 3.4. (Contributed by Brett Cannon in97850.)
importlib.resources
- Removed deprecated
packageparameter fromimportlib.resources.filesfunction. (Contributed by Semyon Moroz in138044.)
pathlib
- Removed deprecated
!pathlib.PurePath.is_reserved. Useos.path.isreservedto detect reserved paths on Windows. (Contributed by Nikita Sobolev in133875.)
platform
- Removed the
!platform.java_verfunction, which was deprecated since Python 3.13. (Contributed by Alexey Makridenko in133604.)
sre*
- Removed
!sre_compile,!sre_constantsand!sre_parsemodules. (Contributed by Stan Ulbrych in135994.)
sysconfig
- Removed the check_home parameter of
sysconfig.is_python_build. (Contributed by Filipe Laíns in92897.)
threading
- Remove support for arbitrary positional or keyword arguments in the C implementation of
~threading.RLockobjects. This was deprecated in Python 3.14. (Contributed by Bénédikt Tran in134087.)
types
- Removed
!codeobject.co_lnotabfromtypes.CodeType, deprecated since Python 3.12 by626. (Contributed by Nikita Sobolev in134690.)
typing
typing.ByteStringhas been removed fromtyping.__all__.!typing.ByteStringhas been deprecated since Python 3.9, and is scheduled for removal in Python 3.17. (Contributed by Alex Waygood in118803.)- The undocumented keyword argument syntax for creating
~typing.NamedTupleclasses (for example,Point = NamedTuple("Point", x=int, y=int)) is no longer supported. Use the class-based syntax or the functional syntax instead. (Contributed by Bénédikt Tran in133817.) - Using
TD = TypedDict("TD")orTD = TypedDict("TD", None)to construct a~typing.TypedDicttype with zero fields is no longer supported. Useclass TD(TypedDict): passorTD = TypedDict("TD", {})instead. (Contributed by Bénédikt Tran in133823.) - Deprecated
!typing.no_type_check_decoratorhas been removed. (Contributed by Nikita Sobolev in133601.)
wave
- Removed the
getmark(),setmark()andgetmarkers()methods of the~wave.Wave_readand~wave.Wave_writeclasses, which were deprecated since Python 3.13. (Contributed by Bénédikt Tran in133873.)
zipimport
- Remove deprecated
!zipimport.zipimporter.load_module. Usezipimport.zipimporter.exec_moduleinstead. (Contributed by Jiahao Li in133656.)
Deprecated
New deprecations
ast:-
Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.(Contributed by Brian Schubert in
116021.)
-
base64:- Accepting the
+and/characters with an alternative alphabet in~base64.b64decodeand~base64.urlsafe_b64decodeis now deprecated. In future Python versions they will be errors in the strict mode and discarded in the non-strict mode. (Contributed by Serhiy Storchaka in125346.)
- Accepting the
- CLI:
-
Deprecate
-band!-bbcommand-line options and schedule them to become no-ops in Python 3.17. These were primarily helpers for the Python 2 -> 3 transition. Starting with Python 3.17, noBytesWarningwill be raised for these cases; use a type checker instead.(Contributed by Nikita Sobolev in
136355.)
-
collections.abc:-
The following statements now cause
DeprecationWarnings to be emitted at runtime:from collections.abc import ByteStringimport collections.abc; collections.abc.ByteString.
DeprecationWarnings were already emitted ifcollections.abc.ByteStringwas subclassed or used as the second argument toisinstanceorissubclass, but warnings were not previously emitted if it was merely imported or accessed from the!collections.abcmodule. (Contributed by Alex Waygood in118803.)
-
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, the optional initial data parameter could also be passed as a keyword argument nameddata=orstring=in varioushashlibimplementations.Support for the
stringkeyword argument name is now deprecated and is slated for removal in Python 3.19. Prefer passing the initial data as a positional argument for maximum backwards compatibility.(Contributed by Bénédikt Tran in
134978.)
-
http.cookies:Morsel.js_output <http.cookies.Morsel.js_output>andBaseCookie.js_output <http.cookies.BaseCookie.js_output>are deprecated and will be removed in Python 3.19. UseMorsel.output <http.cookies.Morsel.output>orBaseCookie.output <http.cookies.BaseCookie.output>instead. (Contributed by kishorhange111 in148849.)
imaplib:- Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not explicitly close the current file. (Contributed by Bénédikt Tran in142307.)
- Altering
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
re:-
re.matchandre.Pattern.matchare nowsoft deprecatedin favor of the newre.prefixmatchandre.Pattern.prefixmatchAPIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.We do not plan to remove the older
!matchname, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use!match, while new code should prefer!prefixmatch. Seeprefixmatch-vs-match.(Contributed by Gregory P. Smith in
86519and Hugo van Kemenade in148100.)
-
struct:-
Calling
Struct.__new__()without a required argument is now deprecated and will be removed in Python 3.20. Calling the~object.__init__method on an initialized~struct.Structobject is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
'F'and'D'type codes are nowsoft deprecatedin favor of the two-letter forms'Zf'and'Zd'. (Contributed by Sergey B Kirpichev in121249.)
-
typing:-
The following statements now cause
DeprecationWarnings to be emitted at runtime:from typing import ByteStringimport typing; typing.ByteString.
DeprecationWarnings were already emitted iftyping.ByteStringwas subclassed or used as the second argument toisinstanceorissubclass, but warnings were not previously emitted if it was merely imported or accessed from the!typingmodule. (Contributed by Alex Waygood in118803.) -
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOSand scheduled for removal in Python 3.17. (Contributed by Jeff Lyon in137586.)
__version__:-
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.)
-
Pending removal in Python 3.16
- The import system:
- Setting
~module.__loader__on a module while failing to set__spec__.loader <importlib.machinery.ModuleSpec.loader>is deprecated. In Python 3.16,!__loader__will cease to be set or taken into consideration by the import system or the standard library. - Setting
~module.__package__on a module while failing to set__spec__.parent <importlib.machinery.ModuleSpec.parent>is deprecated. In Python 3.16,!__package__will cease to be taken into consideration by the import system or standard library. (97879)
- Setting
- The bundled copy of
libmpdec. array:- The
'u'format code (wchar_t) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the'w'format code (Py_UCS4) for Unicode characters instead.
- The
asyncio:-
!asyncio.iscoroutinefunctionis deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunctioninstead. (Contributed by Jiahao Li and Kumar Aditya in122875.) -
asynciopolicy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:!asyncio.AbstractEventLoopPolicy!asyncio.DefaultEventLoopPolicy!asyncio.WindowsSelectorEventLoopPolicy!asyncio.WindowsProactorEventLoopPolicy!asyncio.get_event_loop_policy!asyncio.set_event_loop_policy
Users should use
asyncio.runorasyncio.Runnerwith loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)(Contributed by Kumar Aditya in
127949.)
-
builtins:- Bitwise inversion on boolean types,
~Trueor~Falsehas been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2and-1). Usenot xinstead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert tointexplicitly (~int(x)).
- Bitwise inversion on boolean types,
functools:- Calling the Python implementation of
functools.reducewith function or sequence as keyword arguments has been deprecated since Python 3.14.
- Calling the Python implementation of
logging:- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
115032.)
- Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in
mimetypes:- Valid extensions start with a '.' or are empty for
mimetypes.MimeTypes.add_type. Undotted extensions are deprecated and will raise aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in75223.)
- Valid extensions start with a '.' or are empty for
shutil:- The
!ExecErrorexception has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4, and is now an alias ofRuntimeError.
- The
symtable:- The
!symtable.Class.get_methodsmethod has been deprecated since Python 3.14.
- The
sys:- The
!_enablelegacywindowsfsencodingfunction has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
- The
sysconfig:- The
!sysconfig.expand_makefile_varsfunction has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead.
- The
tarfile:- The undocumented and unused
!TarInfo.tarfileattribute has been deprecated since Python 3.13.
- The undocumented and unused
Pending removal in Python 3.17
datetime:~datetime.datetime.strptimecalls using a format string containing%e(day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in70647.)
collections.abc:-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
encodings:- Passing non-ascii encoding names to
encodings.normalize_encodingis deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in136702.)
- Passing non-ascii encoding names to
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOS. (137586)
typing:-
Before Python 3.14, old-style unions were implemented using the private class
typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers liketyping.get_originandtyping.get_argsinstead of relying on private implementation details. -
typing.ByteString, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
tkinter:- The
!tkinter.Variablemethods!trace_variable,!trace(an alias of!trace_variable),!trace_vdeleteand!trace_vinfo, deprecated since Python 3.14, are scheduled for removal in Python 3.17. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)
- The
Pending removal in Python 3.18
-
No longer accept a boolean value when a file descriptor is expected. (Contributed by Serhiy Storchaka in
82626.) -
decimal:- The non-standard and undocumented
~decimal.Decimalformat specifier'N', which is only supported in the!decimalmodule's C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in89902.)
- The non-standard and undocumented
-
Deprecations defined by
829:importlines in{name}.pthfiles are silently ignored.
(Contributed by Barry Warsaw in
148641.)
Pending removal in Python 3.19
builtins:- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.)
- Passing a complex number as the real or imag argument in the
ctypes:- Implicitly switching to the MSVC-compatible struct layout by setting
~ctypes.Structure._pack_but not~ctypes.Structure._layout_on non-Windows platforms.
- Implicitly switching to the MSVC-compatible struct layout by setting
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in various!hashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.
-
http.cookies:http.cookies.Morsel.js_outputis deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_outputis deprecated and will be removed in Python 3.19.
imaplib:-
Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.Before Python 3.14, this property was used to implement the corresponding
read()andreadline()methods for~imaplib.IMAP4but this is no longer the case since then.
-
tkinter:tkinter.filedialog.askopenfileshas been deprecated since Python 3.16. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.20
-
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling~object.__init__method on initialized~struct.Structobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.) -
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.) -
Deprecations defined by
829:- Warnings are produced for
importlines found in{name}.pthfiles. {name}.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in
148641.) - Warnings are produced for
-
ast:- Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.
- Creating instances of abstract AST nodes (such as
-
typing:-
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
Pending removal in Python 3.21
-
abc- Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively.
- Soft-deprecated since Python 3.3
-
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
- Classes
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodis deprecated since Python 3.16 and will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
-
struct:- Soft-deprecated since Python 3.15, using
'F'and'D'type codes are now deprecated. These codes will be removed in Python 3.21. Use instead two-letter forms'Zf'and'Zd'.
- Soft-deprecated since Python 3.15, using
-
tempfile:tempfile._TemporaryFileWrapperwill be removed in Python 3.21. Use the publictempfile.TemporaryFileWrapperinstead.
Pending removal in future versions
The following APIs will be removed in the future, although there is currently no date scheduled for their removal.
argparse:- Nesting argument groups and nesting mutually exclusive groups are deprecated.
- Passing the undocumented keyword argument prefix_chars to
~argparse.ArgumentParser.add_argument_groupis now deprecated. - The
argparse.FileTypetype converter is deprecated.
builtins:- Generators:
throw(type, exc, tb)andathrow(type, exc, tb)signature is deprecated: usethrow(exc)andathrow(exc)instead, the single argument signature. - Currently Python accepts numeric literals immediately followed by keywords, for example
0in x,1or x,0if 1else 2. It allows confusing and ambiguous expressions like[0x1for x in y](which can be interpreted as[0x1 for x in y]or[0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In a future release it will be changed to a syntax error. (87999) - Support for
__index__()and__int__()method returning non-int type: these methods will be required to return an instance of a strict subclass ofint. - Support for
__float__()method returning a strict subclass offloat: these methods will be required to return an instance offloat. - Support for
__complex__()method returning a strict subclass ofcomplex: these methods will be required to return an instance ofcomplex.
- Generators:
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.)codecs: useopeninstead ofcodecs.open. (133038)!codeobject.co_lnotab: use thecodeobject.co_linesmethod instead.datetime:~datetime.datetime.utcnow: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp: usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: Plural value must be an integer.importlib:~importlib.util.cache_from_sourcedebug_override parameter is deprecated: use the optimization parameter instead.
importlib.metadata:EntryPointstuple interface.- Implicit
Noneon return values.
logging: thewarn()method has been deprecated since Python 3.3, use~logging.warninginstead.mailbox: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.os: Callingos.register_at_forkin a multi-threaded process.os.path:os.path.commonprefixis deprecated, useos.path.commonpathfor path prefixes. Theos.path.commonprefixfunction is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.!pydoc.ErrorDuringImport: A tuple value for exc_info parameter is deprecated, use an exception instance.re: More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in91760.)shutil:~shutil.rmtree's onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:~ssl.SSLContext.set_npn_protocolsand!selected_npn_protocolare deprecated: use ALPN instead.ssl.OP_NO_SSL*optionsssl.OP_NO_TLS*optionsssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.TLSVersion.TLSv1_1
threadingmethods:!threading.Condition.notifyAll: use~threading.Condition.notify_all.!threading.Event.isSet: use~threading.Event.is_set.!threading.Thread.isDaemon,threading.Thread.setDaemon: usethreading.Thread.daemonattribute.!threading.Thread.getName,threading.Thread.setName: usethreading.Thread.nameattribute.!threading.currentThread: usethreading.current_thread.!threading.activeCount: usethreading.active_count.
typing.Text(92332).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in105499.) unittest.IsolatedAsyncioTestCase: it is deprecated to return a value that is notNonefrom a test case.urllib.parsedeprecated functions:~urllib.parse.urlparseinsteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partial writes.xml.etree.ElementTree: Testing the truth value of an~xml.etree.ElementTree.Elementis deprecated. In a future release it will always returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cacheis deprecated: usesys._clear_internal_cachesinstead.
Soft deprecations
There are no plans to remove soft deprecated APIs.
-
re.matchandre.Pattern.matchare nowsoft deprecatedin favor of the newre.prefixmatchandre.Pattern.prefixmatchAPIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.We do not plan to remove the older
!matchname, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use!match, while new code should prefer!prefixmatch. Seeprefixmatch-vs-match.(Contributed by Gregory P. Smith in
86519and Hugo van Kemenade in148100.)
C API changes
New features
-
Add
PyArg_ParseArrayandPyArg_ParseArrayAndKeywordsfunctions to parse arguments of functions using theMETH_FASTCALLcalling convention. (Contributed by Victor Stinner in144175.) -
Add the following functions for the new
frozendicttype:PyAnyDict_CheckPyAnyDict_CheckExactPyFrozenDict_CheckPyFrozenDict_CheckExactPyFrozenDict_New
(Contributed by Victor Stinner in
141510.) -
Add
PyObject_CallFinalizerFromDeallocfunction to the limited C API. (Contributed by Victor Stinner in146063.) -
Add
PySys_GetAttr,PySys_GetAttrString,PySys_GetOptionalAttr, andPySys_GetOptionalAttrStringfunctions as replacements forPySys_GetObject. (Contributed by Serhiy Storchaka in108512.) -
Add
PyUnstable_Unicode_GET_CACHED_HASHto get the cached hash of a string. See the documentation for caveats. (Contributed by Petr Viktorin in131510.) -
Add API for checking an extension module's ABI compatibility:
Py_mod_abi,PyABIInfo_Check, andPyABIInfo_VAR. (Contributed by Petr Viktorin in137210.)
-
Implement
782, thePyBytesWriter API <pybyteswriter>. Add functions:PyBytesWriter_CreatePyBytesWriter_DiscardPyBytesWriter_FinishPyBytesWriter_FinishWithPointerPyBytesWriter_FinishWithSizePyBytesWriter_FormatPyBytesWriter_GetDataPyBytesWriter_GetSizePyBytesWriter_GrowPyBytesWriter_GrowAndUpdatePointerPyBytesWriter_ResizePyBytesWriter_WriteBytes
(Contributed by Victor Stinner in
129813.) -
PyCriticalSectionand related functions are added to the Stable ABI. (Contributed by Petr Viktorin in149225.) -
Add a new
PyImport_CreateModuleFromInitfuncC API for creating a module from a spec and initfunc. (Contributed by Itamar Oren in116146.) -
Add
PyTuple_FromArrayto create atuplefrom an array. (Contributed by Victor Stinner in111489.) -
Add a new module export hook,
PyModExport_* <PyModExport_modulename>.(Contributed by Petr Viktorin in
793and140550.) -
Add functions that are guaranteed to be safe for use in
~PyTypeObject.tp_traversehandlers:PyObject_GetTypeData_DuringGC,PyObject_GetItemData_DuringGC,PyType_GetModuleState_DuringGC,PyModule_GetState_DuringGC,PyModule_GetToken_DuringGC,PyType_GetBaseByToken_DuringGC,PyType_GetModule_DuringGC,PyType_GetModuleByToken_DuringGC. (Contributed by Petr Viktorin in145925.) -
Add
PyObject_Dumpto dump an object tostderr. It should only be used for debugging. (Contributed by Victor Stinner in141070.) -
Implement
820:PySlot-- Unified slot system for the C API. Seecapi-slotsfor documentation.This adds:
- The
PySlotstruct; - the
PyType_FromSlotsfunction; - new slot IDs:
Py_slot_end,Py_slot_invalid;Py_slot_subslots,Py_tp_slots,Py_mod_slots;Py_tp_name,Py_tp_basicsize,Py_tp_extra_basicsize,Py_tp_itemsize,Py_tp_flags,Py_tp_metaclass,Py_tp_module; - convenience macros:
PySlot_DATA,PySlot_FUNC,PySlot_SIZE,PySlot_INT64,PySlot_UINT64,PySlot_STATIC_DATA,PySlot_END,PySlot_PTR,PySlot_PTR_STATIC.
The
PyModule_FromSlotsAndSpecfunction andPyModExportmodule export hook <extension-export-hook>also use the new!PySlotstruct.The following functions are
soft deprecated:PyType_FromSpecPyType_FromSpecWithBasesPyType_FromModuleAndSpecPyType_FromMetaclassPyModule_FromDefAndSpecPyModule_FromDefAndSpec2PyModule_ExecDef
The slots
Py_tp_basesandPy_tp_baseare now equivalent: they can be set either to a single type or a tuple of types. ThePy_tp_basesslot is preferred; the other is ignored if both are specified.(Contributed by Petr Viktorin in
149044.) - The
-
Add
PyUnstable_ThreadState_SetStackProtectionandPyUnstable_ThreadState_ResetStackProtectionfunctions to set the stack protection base address and stack protection size of a Python thread state. (Contributed by Victor Stinner in139653.) -
Add
PyUnstable_SetImmortalC API function to mark objects asimmortal. (Contributed by Kumar Aditya in143300.) -
Restore private provisional
_Py_InitializeMain()function removed in Python 3.14. (Contributed by Victor Stinner in142417.) -
Add
PyUnstable_DumpTracebackandPyUnstable_DumpTracebackThreadsfunctions to output Python stacktraces. (Contributed by Alex Malyshev in145559.)
Changed C APIs
- If the
Py_TPFLAGS_MANAGED_DICTorPy_TPFLAGS_MANAGED_WEAKREFflag is set thenPy_TPFLAGS_HAVE_GCmust be set too. (Contributed by Sergey Miryanov in134786.) PyDateTime_IMPORTis now thread safe. Code that directly checksPyDateTimeAPIforNULLshould be updated to callPyDateTime_IMPORTinstead. (Contributed by Kumar Aditya in141563.)
Removed C APIs
-
Remove deprecated
PyUnicodefunctions:!PyUnicode_AsDecodedObject: UsePyCodec_Decodeinstead.!PyUnicode_AsDecodedUnicode: UsePyCodec_Decodeinstead; note that some codecs (for example, "base64") may return a type other thanstr, such asbytes.!PyUnicode_AsEncodedObject: UsePyCodec_Encodeinstead.!PyUnicode_AsEncodedUnicode: UsePyCodec_Encodeinstead; note that some codecs (for example, "base64") may return a type other thanbytes, such asstr.
(Contributed by Stan Ulbrych in
133612.) -
!PyImport_ImportModuleNoBlock: deprecated alias ofPyImport_ImportModule. (Contributed by Bénédikt Tran in133644.) -
!PyWeakref_GetObjectand!PyWeakref_GET_OBJECT: usePyWeakref_GetRefinstead. The [|pythoncapi_compat_project_link|](https://github.com/python/pythoncapi-compat) can be used to get!PyWeakref_GetRefon Python 3.12 and older. (Contributed by Bénédikt Tran in133644.) -
Remove deprecated
!PySys_ResetWarnOptions. Clearsys.warnoptionsand!warnings.filtersinstead.(Contributed by Nikita Sobolev in
138886.)
The following functions are removed in favor of PyConfig_Get. The [|pythoncapi_compat_project_link|](https://github.com/python/pythoncapi-compat) can be used to get !PyConfig_Get on Python 3.13 and older.
-
Python initialization functions:
!Py_GetExecPrefix: usePyConfig_Get("base_exec_prefix") <PyConfig_Get>(sys.base_exec_prefix) instead. UsePyConfig_Get("exec_prefix") <PyConfig_Get>(sys.exec_prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetPath: usePyConfig_Get("module_search_paths") <PyConfig_Get>(sys.path) instead.!Py_GetPrefix: usePyConfig_Get("base_prefix") <PyConfig_Get>(sys.base_prefix) instead. UsePyConfig_Get("prefix") <PyConfig_Get>(sys.prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetProgramFullPath: usePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetProgramName: usePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetPythonHome: usePyConfig_Get("home") <PyConfig_Get>or thePYTHONHOMEenvironment variable instead.
(Contributed by Bénédikt Tran in
133644.)
Deprecated C APIs
-
Deprecate
456support for providing an external definition of the string hashing scheme. Removal is scheduled for Python 3.19.Previously, embedders could define
Py_HASH_ALGORITHMto bePy_HASH_EXTERNALto indicate that the hashing scheme was provided externally but this feature was undocumented, untested and most likely unused.(Contributed by Bénédikt Tran in
141226.) -
For unsigned integer formats in
PyArg_ParseTuple, accepting Python integers with value that is larger than the maximal value for the C type or less than the minimal value for the corresponding signed integer type of the same size is now deprecated. (Contributed by Serhiy Storchaka in132629.) -
PyBytes_FromStringAndSize(NULL, len) <PyBytes_FromStringAndSize>and_PyBytes_Resizearesoft deprecated, use thePyBytesWriterAPI instead. (Contributed by Victor Stinner in129813.) -
!_PyObject_CallMethodId,!_PyObject_GetAttrIdand!_PyUnicode_FromIdare deprecated since Python 3.15 and will be removed in Python 3.20. Instead, usePyUnicode_InternFromString()and cache the result in the module state, then callPyObject_CallMethodorPyObject_GetAttr. (Contributed by Victor Stinner in141049.) -
Deprecate
~PyComplexObject.cvalfield of thePyComplexObjecttype. UsePyComplex_AsCComplexandPyComplex_FromCComplexto convert a Python complex number to/from the CPy_complexrepresentation. (Contributed by Sergey B Kirpichev in128813.) -
Functions
_Py_c_sum,_Py_c_diff,_Py_c_neg,_Py_c_prod,_Py_c_quot,_Py_c_powand_Py_c_absaresoft deprecated. (Contributed by Sergey B Kirpichev in128813.) -
~PyConfig.bytes_warningis deprecated since Python 3.15 and will be removed in Python 3.17. (Contributed by Nikita Sobolev in136355.) -
!Py_INFINITYmacro issoft deprecated, use the C11 standard<math.h>!INFINITYinstead. (Contributed by Sergey B Kirpichev in141004.) -
The following macros are
soft deprecated:Py_ALIGNED: Preferalignasinstead.PY_FORMAT_SIZE_T: Use"z"directly.Py_LLandPy_ULL: Use standard suffixes,LLandULL.PY_LONG_LONG,PY_LLONG_MIN,PY_LLONG_MAX,PY_ULLONG_MAX,PY_INT32_T,PY_UINT32_T,PY_INT64_T,PY_UINT64_T,PY_SIZE_MAX: Use C99 types/limits.Py_UNICODE_SIZE: Usesizeof(wchar_t)directly.Py_VA_COPY: Useva_copydirectly.
The macro
Py_UNICODE_WIDE, which was scheduled for removal, issoft deprecatedinstead.(Contributed by Petr Viktorin in
146175.) -
!Py_MATH_Eland!Py_MATH_PIlare deprecated since Python 3.15 and will be removed in Python 3.20. (Contributed by Sergey B Kirpichev in141004.)
Build changes
-
Removed implicit fallback to the bundled copy of the
libmpdeclibrary. Now this should be explicitly enabled with!--with-system-libmpdecset tonoor with!--without-system-libmpdec. (Contributed by Sergey B Kirpichev in115119.) -
The new configure option
--with-missing-stdlib-config=FILEallows distributors to pass a JSON configuration file containing custom error messages forstandard librarymodules that are missing or packaged separately. (Contributed by Stan Ulbrych and Petr Viktorin in139707.) -
The new configure option
--with-pymalloc-hugepagesenables huge page support forpymalloc <pymalloc>arenas. When enabled, arena size increases to 2 MiB and allocation usesMAP_HUGETLB(Linux) orMEM_LARGE_PAGES(Windows) with automatic fallback to regular pages. On Windows, usebuild.bat --pymalloc-hugepages. At runtime, huge pages must be explicitly enabled by setting thePYTHON_PYMALLOC_HUGEPAGESenvironment variable to1. (Contributed by Pablo Galindo Salgado in144319.) -
Annotating anonymous mmap usage is now supported if the Linux kernel supports
PR_SET_VMA_ANON_NAME <PR_SET_VMA(2const)>(Linux 5.17 or newer). Annotations are visible in/proc/<pid>/mapsif the kernel supports the feature and-X dev <-X>is passed to Python, or Python is built indebug mode <debug-build>. (Contributed by Donghee Na in141770.) -
CPython is now built with frame pointers enabled by default (
831). Pass--without-frame-pointersto opt out.Authors of C extensions and native libraries built with custom build systems should ensure the unwind chain is intact. This is usually done by adding
-fno-omit-frame-pointerand similar flags toCFLAGS. See--without-frame-pointersdocumentation for the specific flags Python uses.(Contributed by Pablo Galindo Salgado and Savannah Ostrowski in
149201.)
- 64-bit builds using Visual Studio 2026 (MSVC 18) may now use the new
tail-calling interpreter <whatsnew314-tail-call-interpreter>. Results on Visual Studio 18.1.1 report between 15-20% speedup on the geometric mean of pyperformance on Windows x86-64 over the switch-case interpreter on an AMD Ryzen 7 5800X. We have observed speedups ranging from 14% for large pure-Python libraries to 40% for long-running small pure-Python scripts on Windows. This was made possible by a new feature introduced in MSVC 18, which the official Windows 64-bit binaries on python.org now use. (Contributed by Chris Eibl, Ken Jin, and Brandt Bucher in143068. Special thanks to Steve Dower, and the MSVC team including Hulon Jenkins.)
Porting to Python 3.15
This section lists previously described changes and other bugfixes that may require changes to your code.
-
sqlite3.ConnectionAPIs have been cleaned up.- All parameters of
sqlite3.connectexcept database are now keyword-only. - The first three parameters of methods
~sqlite3.Connection.create_functionand~sqlite3.Connection.create_aggregateare now positional-only. - The first parameter of methods
~sqlite3.Connection.set_authorizer,~sqlite3.Connection.set_progress_handlerand~sqlite3.Connection.set_trace_callbackis now positional-only.
(Contributed by Serhiy Storchaka in
133595.) - All parameters of
-
resource.RLIM_INFINITYis now always positive. Passing a negative integer value that corresponded to its old value (such as-1or-3, depending on platform) toresource.setrlimitandresource.prlimitis now deprecated. (Contributed by Serhiy Storchaka in137044.) -
mmap.mmap.resizehas been removed on platforms that don't support the underlying syscall, instead of raising aSystemError. (Contributed by An Long in138205.) -
A resource warning is now emitted for an unclosed
xml.etree.ElementTree.iterparseiterator if it opened a file. Use its!closemethod or thecontextlib.closingcontext manager to close it. (Contributed by Osama Abdelkader and Serhiy Storchaka in140601.) -
If a short option and a single-dash long option are passed to
argparse.ArgumentParser.add_argument, dest is now inferred from the single-dash long option. For example, inadd_argument('-f', '-foo'), dest is now'foo'instead of'f'. Pass an explicit dest argument to preserve the old behavior. (Contributed by Serhiy Storchaka in138697.) -
Padding of input no longer required in
base64.urlsafe_b64decode. Pass a new argumentpadded=Trueor usebase64.b64decodewith argumentaltchars=b'-_'(this works with older Python versions) to make padding required. (Contributed by Serhiy Storchaka in73613.) -
Since
unittest.TestCase.assertWarnsandunittest.TestCase.assertWarnsRegexno longer swallow warnings that do not match the specified category or regex, your tests may start leaking some warnings that were previously masked. Use warning filters to silence them or additional!assertWarns*to catch and check them. (Contributed by Serhiy Storchaka in143231.)
What's new in Python 3.16
Editor
Savannah Ostrowski
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the issue number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the VCS log when researching a change.
This article explains the new features in Python 3.16, compared to 3.15.
For full details, see the changelog <changelog>.
[!NOTE] Prerelease users should be aware that this document is currently in draft form. It will be updated substantially as Python 3.16 moves towards release, so it's worth checking back even after reading earlier versions.
Summary -- Release highlights
New features
Other language changes
- The
iterfunction now accepts the stop_exception parameter. The created iterator stops when the callable raises the specified exception. The second parameter is now named stop_value and can be passed by keyword.aiternow accepts the same stop_value and stop_exception parameters, calling an asynchronous callable and awaiting the result. (Contributed by Serhiy Storchaka in64862.) memoryview.castnow allows casting a multidimensional F-contiguous view to a one-dimensional view. (Contributed by Jaemin Park in91484.)memoryview.castnow accepts an order parameter. Withorder='F'it returns a zero-copy Fortran-contiguous (column-major) view of a flat buffer, which is useful for interfacing with column-major libraries. (Contributed by Serhiy Storchaka in78959.)Frame objects <frame-objects>now supportweak references <weakref>. This allows associating extra data with active frames, for example in debuggers, without keeping the frames (and everything they reference) alive indefinitely. (Contributed by Łukasz Langa in102960.)TypeErrormessages for some instance methods called with too many positional arguments now suggest checking whether the method definition is missing theselfparameter. (Contributed by Suren Nihalani in152315.)anextandaiterare now implemented in Python instead of C. The awaitable returned byanext(it, default)and the__anext__()of the iterator returned byaiter(callable, ...)are now plain coroutines, so introspection tools such asasyncio.print_call_graphcan see through them into the awaited code. (Contributed by Kumar Aditya in157361.)
Default interactive shell
- The
REPLnow displays error messages when editing commands cannot be performed, such as when tab completion finds no matches or a history search fails. (Contributed by Bartosz Sławecki in148228.)
New modules
- None yet.
Improved modules
argparse
~argparse.ArgumentGroupand~argparse.MutuallyExclusiveGroup, the types returned by~argparse.ArgumentParser.add_argument_groupand~argparse.ArgumentParser.add_mutually_exclusive_group, are now public. The_-prefixed names remain as aliases. (Contributed by Bernát Gábor in144812.)
asyncio
- Add the mode parameter to
asyncio.loop.create_unix_serverandasyncio.start_unix_serverto set the permissions of the Unix socket file created for path. (Contributed by Sam Bull in94984.) - Add eager_tasks parameter to
asyncio.runfunction andasyncio.Runnerclass constructor. (Contributed by Andrew Svetlov in128289.)
bdb
bdb.BdbQuitis now a subclass ofBaseException, instead ofException, to allow it to be used for cleanly exiting the debugger without being accidentally caught by user code. (Contributed by Tian Gao in149337.)
bz2
- Added constants
~bz2.bzlib_versionand~bz2.bzlib_version_infowhich provide information about the version of the bzip2 compression library in use. (Contributed by Serhiy Storchaka in117404.)
codecs
- On platforms that provide the C library's
iconv(3)function, every encoding known toiconvfor which Python has no built-in codec is now available (for examplecp1133). Prefixing an encoding name withiconv:forces theiconv-based codec even when a built-in codec of the same name exists. (Contributed by Serhiy Storchaka in152997.)
compression.zstd
- Added constants
~compression.zstd.ZSTD_VERSIONand~compression.zstd.ZSTD_VERSION_INFOwhich provide information about the version of the zstd library that was used for building the module.~compression.zstd.zstd_version_infois now a named tuple. (Contributed by Serhiy Storchaka in117404.)
concurrent.futures
- The iterator returned by
concurrent.futures.Executor.mapis no longer automatically closed if a function call raises an exception. Use the!closemethod to explicitly close the iterator. (Contributed by xzmeng and Serhiy Storchaka in108518.)
concurrent.interpreters
~concurrent.interpreters.Interpreterobjects now support thecontext managerprotocol. Exiting thewithblock calls~concurrent.interpreters.Interpreter.close. (Contributed by Peter Bierma in158370.)
csv
csv.Sniffer.sniffnow deduces the dialect by trial parsing instead of heuristics based on matching isolated fragments and on character frequencies, so the result is consistent with howcsv.readerwill parse the sample. It can now detect the escapechar parameter, accepts non-ASCII delimiters in the delimiters argument, no longer misdetects the delimiter when the sample contains delimiter characters inside quoted fields, and no longer takes quadratic time on quoted samples. The results may differ from those of earlier Python versions. (Contributed by Serhiy Storchaka in83273.)csv.Sniffer.sniffnow detects the lineterminator parameter by a majority vote among the line endings of the sample, instead of always returning'\r\n'. (Contributed by Serhiy Storchaka in75008.)
ctypes
- Add
ctypes.util.structfor generating~ctypes.Structuretypes from an annotation-based syntax, similar to how thedataclassesmodule is used. (Contributed by Peter Bierma in104533.) - Add
ctypes.util.wrap_dll_functionfor generating function pointers through a function signature. (Contributed by Peter Bierma in153903.) - Added constants
~ctypes.LIBFFI_VERSION,~ctypes.libffi_version,~ctypes.LIBFFI_VERSION_INFOand~ctypes.libffi_version_info, which provide information about the version of the libffi library in use. They are only available with libffi 3.5 or later. (Contributed by Serhiy Storchaka in157487.) - Objects with an
!_as_parameter_attribute are now implicitly converted when passed for a~ctypes.POINTERargument. (Contributed by Peter Bierma in71990.) Callback functions <ctypes-callback-functions>can now return~ctypes.Structureand~ctypes.Unioninstances by value. (Contributed by Russell Keith-Magee in49960.)
curses
- The
cursescharacter-cell window methods now accept a full character cell --- a spacing character optionally followed by combining characters --- in addition to a single integer or byte character. This affects~curses.window.addch,~curses.window.bkgd,~curses.window.bkgdset,~curses.window.border,~curses.window.box,~curses.window.echochar,~curses.window.hline,~curses.window.inschand~curses.window.vline. Also add the wide-character read methods~curses.window.get_wstrand~curses.window.in_wstr, the counterparts of~curses.window.getstrand~curses.window.instrthat return astrrather thanbytes, and the module functionscurses.erasewchar,curses.killwcharandcurses.wunctrl, the wide-character counterparts ofcurses.erasechar,curses.killcharandcurses.unctrl. On a narrow (non-ncursesw) build the character cell holds a single character without combining marks, representable as one byte in the window's encoding, and~curses.window.in_wstrreturns its decoded text. (Contributed by Serhiy Storchaka in151757.) - Add the
curses.complexchartype, representing a styled character cell (its text, attributes and color pair), and the window methods~curses.window.in_wchand~curses.window.getbkgrndthat return one --- the counterparts of~curses.window.inchand~curses.window.getbkgd. The character-cell methods, such as~curses.window.addchand~curses.window.border, now also accept a~curses.complexchar. These work whether or not Python was built against a wide-character-aware curses library; on a narrow build a cell holds a single character representable as one byte in the window's encoding (so only 8-bit locales are supported). (Contributed by Serhiy Storchaka in152233.) - Add the
curses.complexstrtype, an immutable run of styled cells (the string counterpart of~curses.complexchar), and the window method~curses.window.in_wchstrthat returns one. The string-cell methods~curses.window.addstr,~curses.window.addnstr,~curses.window.insstrand~curses.window.insnstrnow also accept a~curses.complexstr. Like~curses.complexchar, it works whether or not Python was built against a wide-character-aware curses library. (Contributed by Serhiy Storchaka in152233.) - The wide-character
cursesfunctions and methods~curses.window.get_wch,~curses.window.get_wstr,curses.unget_wch,curses.erasewchar,curses.killwcharandcurses.wunctrlnow also work when Python is not built against a wide-character-aware curses library, on an 8-bit locale, where each character is a single byte in the relevant encoding.curses.ungetchnow also accepts a one-character string, likecurses.unget_wch; on a wide-character build it can be any character (previously a multibyte character raisedOverflowError). (Contributed by Serhiy Storchaka in152470.) - Add support for multiple terminals to the
cursesmodule: the new functionscurses.newterm,curses.set_termandcurses.new_prescr, the correspondingscreen <curses-screen-objects>object, and thewindow.use() <curses.window.use>method. (Contributed by Serhiy Storchaka in90092.) - Add the
curseswindow methods~curses.window.attr_get,~curses.window.attr_set,~curses.window.attr_on,~curses.window.attr_offand~curses.window.color_set, which pass the color pair as a separate argument instead of packing it into the attribute value, and the correspondingWA_*attribute constants. (Contributed by Serhiy Storchaka in152219.) - Add the
curses.term_attrsfunction, which returns the supported video attributes asWA_* <curses-wa-constants>values, the counterpart ofcurses.termattrs. (Contributed by Serhiy Storchaka in152332.) - Add the
WACS_*constants to thecursesmodule, the counterparts of theACS_* <curses-acs-codes>line-drawing codes ascurses.complexcharcells. (Contributed by Serhiy Storchaka in155863.) - Add the
cursesfunctionscurses.alloc_pair,curses.find_pair,curses.free_pairandcurses.reset_color_pairsfor dynamic color-pair management, available when built against a wide-character ncurses with extended-color support. (Contributed by Serhiy Storchaka in151774.) - Add the
cursesfunctions~curses.scr_dump,~curses.scr_restore,~curses.scr_initand~curses.scr_set, which dump the whole screen to a file and restore it. (Contributed by Serhiy Storchaka in152260.) - Add the
curseswindow method~curses.window.dupwin, which returns a new window that is an independent duplicate of an existing one. (Contributed by Serhiy Storchaka in152258.) - Add the soft-label-key functions to the
cursesmodule, which manage a row of labels along the bottom line of the screen:~curses.slk_init,~curses.slk_set,~curses.slk_label,~curses.slk_refresh,~curses.slk_noutrefresh,~curses.slk_clear,~curses.slk_restore,~curses.slk_touch, the attribute functions~curses.slk_attron,~curses.slk_attroff,~curses.slk_attrset,~curses.slk_attr,~curses.slk_attr_on,~curses.slk_attr_off,~curses.slk_attr_set, and~curses.slk_color. (Contributed by Serhiy Storchaka in152263.) - Add the
curseskey-management functions~curses.define_key,~curses.key_definedand~curses.keyok, available when built against an ncurses withNCURSES_EXT_FUNCS. (Contributed by Serhiy Storchaka in152334.) - Add the
curses.has_mousefunction and thecurses.window.mouse_trafomethod, completing thecursesmouse interface. (Contributed by Serhiy Storchaka in152325.) - Add
cursesfunctions and window methods that report state which could previously only be set, such ascurses.window.is_keypad,curses.window.getparentandcurses.is_cbreak, available when built against an ncurses withNCURSES_EXT_FUNCS. (Contributed by Serhiy Storchaka in151776.) - Add
curses.nofilter, which undoes the effect ofcurses.filter. (Contributed by Serhiy Storchaka in151744.) curses.textpad.Textboxnow supports entering and reading back the full Unicode range, including combining characters, when curses is built with wide-character support. (Contributed by Serhiy Storchaka in133031.)
datetime
- Add the
%Nfformat code (where N is from 1 to 6) todatetime.datetime.strftime,datetime.time.strftime,datetime.date.strftime,datetime.datetime.strptimeanddatetime.time.strptime. (Contributed by Stan Ulbrych and Karoline Pauls in157290.) - Add
datetime.timezone.name, the name passed to the constructor, orNoneif no name was passed. (Contributed by Stan Ulbrych in131210.)
dbm.gnu
- Added constants
~dbm.gnu.GDBM_VERSION_INFO,~dbm.gnu.gdbm_version_infoand~dbm.gnu.gdbm_version, which provide information about the version of the GDBM library in use. (Contributed by Serhiy Storchaka in157478.)
dbm.ndbm
- Added constants which provide information about the version of the underlying library in use:
~dbm.ndbm.GDBM_VERSION_INFO,~dbm.ndbm.gdbm_version_infoand~dbm.ndbm.gdbm_versionif it is GDBM, or~dbm.ndbm.BDB_VERSION,~dbm.ndbm.bdb_version,~dbm.ndbm.BDB_VERSION_INFOand~dbm.ndbm.bdb_version_infoif it is Berkeley DB.dbm.ndbm.libraryis now'ndbm'instead of'GNU gdbm'for a classic NDBM library. (Contributed by Serhiy Storchaka in157480.)
decimal
- Added constants
~decimal.LIBMPDEC_VERSION,~decimal.libmpdec_version,~decimal.LIBMPDEC_VERSION_INFO, and~decimal.libmpdec_version_infoin the C implementation, which provide information about the version of the libmpdec library in use. (Contributed by Serhiy Storchaka in157475.)
difflib
- Expose the optional autojunk parameter of
difflib.SequenceMatcherin public functions and class methods indifflib, allowing callers to control the automatic junk heuristic. (Contributed by Tomasz Kazimierczak in118150.)
encodings
- Add the
utf-7-imapcodec, implementing the modified UTF-7 encoding used for international IMAP4 mailbox names (3501). (Contributed by Serhiy Storchaka in66788.) encodings.idna.nameprepnow takes a limit argument that allows rejecting extremely large input early. (Contributed by Petr Viktorin in157675.)
gzip
gzip.opennow accepts an optional argumentmtimewhich is passed on to the constructor of the~gzip.GzipFileclass. (Contributed by Marin Misur in91372.)
imaplib
- Add the
~imaplib.IMAP4.idmethod, a wrapper for theIDcommand (2971). (Contributed by Serhiy Storchaka in98092.) - Add the
~imaplib.IMAP4.movemethod, a wrapper for theMOVEcommand (6851). (Contributed by Serhiy Storchaka in77508.) - Add the
~imaplib.IMAP4.login_plainmethod, which authenticates using thePLAINSASL mechanism (4616) and supports non-ASCII user names and passwords. (Contributed by Przemysław Buczkowski and Serhiy Storchaka in89869.) - Non-ASCII mailbox names are now automatically encoded as modified UTF-7 (
3501, section 5.1.3) in the default mode, so international mailbox names can be passed as ordinarystrwithout enablingUTF8=ACCEPT(under which they are sent as UTF-8). (Contributed by Serhiy Storchaka in49555.) - The
~imaplib.IMAP4.copy,~imaplib.IMAP4.move,~imaplib.IMAP4.fetch,~imaplib.IMAP4.store,~imaplib.IMAP4.search,~imaplib.IMAP4.sort,~imaplib.IMAP4.threadand~imaplib.IMAP4.expungemethods now accept a keyword-only uid argument that selects the correspondingUIDcommand, as a more convenient alternative to~imaplib.IMAP4.uid. (Contributed by Serhiy Storchaka in153502.) ~imaplib.IMAP4.search,~imaplib.IMAP4.sortand~imaplib.IMAP4.thread(and the correspondinguidcommands) now encodestrsearch criteria to the declared charset, so international search text can be passed as an ordinarystr. When charset isNone(as it must be underUTF8=ACCEPT), the criteria are sent using the connection encoding instead. (Contributed by Serhiy Storchaka in153494.)- Command methods now accept structured arguments, so the module takes care of quoting instead of the caller. A message_set and lists of flags or other atoms can be passed as sequences instead of preformatted strings, and the
~imaplib.IMAP4.search,~imaplib.IMAP4.fetch,~imaplib.IMAP4.sort,~imaplib.IMAP4.threadand~imaplib.IMAP4.uidmethods accept a params keyword argument that substitutes and quotes?placeholders, in the manner ofsqlite3parameter substitution. (Contributed by Serhiy Storchaka in153521.)
io
- Add
io.BytesIO.peekmethod to read without advancing position. (Contributed by Marcel Martin in90533.)
ipaddress
- Add
IPv4Network.next_network() <ipaddress.IPv4Network.next_network>andIPv6Network.next_network() <ipaddress.IPv6Network.next_network>methods to find the next nearest network with a specific prefix size. (Contributed by Faisal Mahmood in87027.)
logging
~logging.handlers.TimedRotatingFileHandlernow uses the creation time instead of the last modification time of an existing log file as the basis for the first rotation after handler creation, if supported by the OS and file system. This allows it to be used in short-running programs that start and end before the rotation interval expires. (Contributed by Iván Márton and Serhiy Storchaka in84649.)
lzma
- Add support of new BCJ filters ARM64 and RISC-V via
!lzma.FILTER_ARM64and!lzma.FILTER_RISCV. Note that the new filters will work only if the runtime library supports them. ARM64 filter requireslzma5.4.0 or newer while RISC-V requires 5.6.0 or newer. (Contributed by Chien Wong in115988.) - Added constants
~lzma.LZMA_VERSION,~lzma.lzma_version,~lzma.LZMA_VERSION_INFO, and~lzma.lzma_version_info, which provide information about the version of the lzma library in use. (Contributed by Serhiy Storchaka in117404.)
math
- Added trigonometric functions that work in units of half turns, rather than radians. The new functions
math.acospi,math.asinpi,math.atanpi, andmath.atan2pireturn half-turn angles. The new functionsmath.cospi,math.sinpi, andmath.tanpitake half-turn angle arguments. These functions are recommended by IEEE 754-2019 and standardized in C23. (Contributed by Jeff Epler in150534.)
multiprocessing
- Add the optional buffersize parameter to
multiprocessing.pool.Pool.imapandmultiprocessing.pool.Pool.imap_unorderedto limit the number of submitted tasks whose results have not yet been yielded. If the buffer is full, iteration over the iterable pauses until a result is yielded from the buffer. To fully utilize pool's capacity when using this feature, set buffersize at least to the number of processes in pool (to consume iterable as you go), or even higher (to prefetch the nextN=buffersize-processesarguments). (Contributed by Oleksandr Baltian in136871.)
os
- Add
os.pidfd_getfdfor duplicating a file descriptor from another process via a pidfd. Available on Linux 5.6+. (Contributed by Maurycy Pawłowski-Wieroński in149464.) - The following functions are now available on Android:
os.chroot,os.initgroups,os.setegid,os.seteuid,os.setgid,os.setregid,os.setresgid,os.setresuid,os.setreuid, andos.setuid. Calling them without sufficient privileges now raisesPermissionErrorinstead of the functions being unavailable. (Contributed by Md Arif in152936.) os.readlinknow accepts a file descriptor referring to a symlink on Linux, Android, macOS and iOS. (Contributed by OOTS in157899.)
pydoc
- Modernize the HTML output of
pydoc. The pages generated by thepydocHTTP server now use semantic HTML5 markup and a new style sheet based on the python-docs-theme used by docs.python.org, with dark mode support. Class members inherited from other classes are collapsed by default. (Contributed by Serhiy Storchaka in153906.)
pickle
- Weak references (
weakref.ref),weakref.WeakMethod,weakref.WeakSet,weakref.WeakValueDictionaryandweakref.WeakKeyDictionarycan now be pickled if the weakly referenced objects are strongly referenced elsewhere in the same pickle; otherwise pickling raisespickle.PicklingError.!WeakMethodand!WeakSetcan now also be copied. (Contributed by Serhiy Storchaka in74876.)
quopri
quopri.decode,quopri.decodestringandbinascii.a2b_qpgained a strip_ws parameter. When true, trailing whitespace is stripped from each line while decoding, as required by2045for a quoted-printable body. (Contributed by Serhiy Storchaka in62222.)
re
renow supports set operations and nested sets in character classes, as described in Unicode Technical Standard #18: set difference ([A--B]), intersection ([A&&B]) and union ([A||B]), where an operand may be a nested set written in square brackets. For example,[a-z--[aeiou]]matches an ASCII lowercase consonant. (Contributed by Serhiy Storchaka in152100.)- Regular expressions now support Unicode property escapes
\p{...}and\P{...}, which match a character by a Unicode property -- for example\p{Lu}(an uppercase letter),\p{Cased}or\p{ASCII}. Seethe regular expression syntax <re-syntax>for the supported properties. (Contributed by Serhiy Storchaka in95555.)
readline
- Added constants
~readline.READLINE_VERSION_INFO,~readline.readline_version_infoand~readline.readline_version, which provide information about the version of the Readline library in use. (Contributed by Serhiy Storchaka in157485.)
shlex
- Add keyword-only parameter force to
shlex.quoteto force quoting a string, even if it is already safe for a shell without being quoted. (Contributed by Jay Berry in148846.)
shutil
- Add keyword-only copy_dir_stat parameter to
shutil.copytree: set it to false to skip copying directory metadata withshutil.copystat, e.g. when copying a read-only tree. (Contributed by Łukasz Langa in89721.) shutil.unpack_archivecan now unpack wheel files using thewhlformat. (Contributed by Emma Harper Smith and Stan Ulbrych in84027.)
socket
- The
socket.sethostnamefunction is now available on Android. Calling it without sufficient privileges now raisesPermissionErrorinstead of the function being unavailable. (Contributed by Md Arif in152936.)
sqlite3
sqlite3.Blobnow supports negative-step slices for reading and writing (for example,blob[9:0:-2]). Previously, such slices would raiseSystemErrororValueError. (Contributed by Jiseok CHOI in150449.)- Added constants
~sqlite3.SQLITE_VERSIONand~sqlite3.SQLITE_VERSION_INFOwhich provide information about the version of the SQLite library that was used for building the module.~sqlite3.sqlite_version_infois now a named tuple. (Contributed by Serhiy Storchaka in157470.)
ssl
- Added support for
Encrypted Client Hello <ssl-encrypted-client-hello>(ECH) with OpenSSL 4.0 or later. Clients can supply an ECHConfigList discovered through DNS, for example using a third-party library such asdnspythonto query HTTPS or SVCB records, as the ech_config argument of~ssl.SSLContext.wrap_socketand~ssl.SSLContext.wrap_bioor with~ssl.SSLContext.set_ech_config. Servers can use~ssl.SSLContext.load_ech_keysto load ECH private keys and their configurations from PEM files. (Contributed by Peter Bierma and Iain R. Learmonth in89730.) ssl.OPENSSL_VERSION_INFOis now a named tuple. Added~ssl.OPENSSL_API_VERSION_INFOwhich provides information about the version of the OpenSSL library that was used for building the module. (Contributed by Serhiy Storchaka in157513.)- The
sslmodule now rejects TLS certificate chains that contain one of a set of compromised eMudhra intermediate CA certificates. The affected certificates are identified by their public key, so cross-signed copies that reuse the same key are blocked as well. It is a defense-in-depth backstop that applies even when an application supplies its own root CA bundle, and regardless of whether the platform trust store has removed trust. (Contributed by Christian Heimes in160040for2026-115557.)
symtable
symtable.symtablenow accepts an AST object, like the built-incompile. (Contributed by Serhiy Storchaka in153844.)- Inlined list, set and dict comprehensions (
709) are now represented as their own symbol table entries, of type~symtable.SymbolTableType.INLINED_COMPREHENSION. Each such entry is a lexical child of the enclosing scope and records the comprehension's own locals, cells, and free names. It does not correspond to a separate compilation unit. For names loaded only inside an inlined list, set, or dict comprehension,symtable.Symbol.is_referencedcan now returnTrueon the enclosing function. (Contributed by Irit Katriel in124697.)
tkinter
- Added many
tkinter.ttk.Treeviewmethods wrapping the enhancedttk::treeviewwidget commands from Tk 9.1, such as~tkinter.ttk.Treeview.sort,~tkinter.ttk.Treeview.search,~tkinter.ttk.Treeview.expand,~tkinter.ttk.Treeview.collapse,~tkinter.ttk.Treeview.hide,~tkinter.ttk.Treeview.unhide, and methods for cell focus, selection and tagging. The~tkinter.ttk.Treeview.expandand~tkinter.ttk.Treeview.collapsemethods (without recursion) also work on Tk older than 9.1. (Contributed by Serhiy Storchaka in151910.) - Added constants
~tkinter.TCL_VERSION_INFOand~tkinter.TK_VERSION_INFO, named tuples with the versions of the Tcl and Tk libraries that were used for building the module. (Contributed by Serhiy Storchaka in157514.) - Added new
!tkinter.Textmethods~tkinter.Text.edit_canundoand~tkinter.Text.edit_canredowhich return whether an undo or redo is possible. (Contributed by Serhiy Storchaka in151674.) - Added new
!tkinter.Textmethods~tkinter.Text.syncand~tkinter.Text.pendingsyncwhich control and report the synchronization of the displayed view with the underlying text. (Contributed by Serhiy Storchaka in151675.) - Added the
ttk.Style.theme_styles <tkinter.ttk.Style.theme_styles>method which returns the list of styles defined in a theme. (Contributed by Serhiy Storchaka in151920.) - Added new
!tkinter.Canvasmethods~tkinter.Canvas.rcharswhich replaces the text or coordinates of canvas items, and~tkinter.Canvas.rotatewhich rotates the coordinates of canvas items. (Contributed by Serhiy Storchaka in151876.) - Added a
!validatemethod to the!tkinter.Entryand!tkinter.Spinboxwidgets, which forces an evaluation of the validation command. (Contributed by Serhiy Storchaka in151878.) - Added the
tkinter.Menu.postcascademethod, and the~tkinter.Misc.tk_scalingand~tkinter.Misc.tk_inactivemethods which respectively query or set the display scaling factor and report the user idle time. (Contributed by Serhiy Storchaka in151881.) - Added the
!tk_printmethod totkinter.Canvasandtkinter.Textwhich prints the contents of the widget using the native print dialog. It requires Tk 8.7/9.0 or newer. (Contributed by Serhiy Storchaka in153256.) - Added new window-management methods
~tkinter.Misc.winfo_isdark(dark mode detection),~tkinter.Wm.wm_iconbadge(application icon badge) and~tkinter.Wm.wm_stackorder(toplevel stacking order). (Contributed by Serhiy Storchaka in151874.) - Added the
~tkinter.Misc.tk_appname,~tkinter.Misc.tk_useinputmethodsand~tkinter.Misc.tk_caretmethods, exposing the application send name, the X Input Methods state and the input method caret location. (Contributed by Serhiy Storchaka in151886.) - Added support for more options in
!tkinter.PhotoImagemethods: the format parameter of~tkinter.PhotoImage.put, the metadata parameter of~tkinter.PhotoImage.put,~tkinter.PhotoImage.read,~tkinter.PhotoImage.writeand~tkinter.PhotoImage.data, and the withalpha parameter of~tkinter.PhotoImage.get. (Contributed by Serhiy Storchaka in151890.) - Added the
~tkinter.PhotoImage.redithermethod which recalculates the dithered image when its data was supplied in pieces. (Contributed by Serhiy Storchaka in151888.) tkinter.OptionMenunow accepts arbitrary!tkinter.Menubuttonoptions as keyword arguments, which can also override its default appearance. (Contributed by Serhiy Storchaka in101284.)- The
tkinter.simpledialogdialogs were modernized to match the look and feel of the native Tk dialogs.!tkinter.simpledialog.SimpleDialogand the~tkinter.simpledialog.askinteger,~tkinter.simpledialog.askfloatand~tkinter.simpledialog.askstringdialogs are now built from the themedtkinter.ttkwidgets instead of the classictkinterwidgets; the!tkinter.simpledialog.Dialogbase class still defaults to the classic widgets for compatibility. Both!Dialogand!SimpleDialoggained a use_ttk parameter that selects between the classic Tk widgets and the themed ttk widgets.!SimpleDialogalso gained bitmap and detail parameters, draws the standard icons with themed images in the ttk version, and accepts mappings of button options as buttons entries. (Contributed by Serhiy Storchaka in59396.) - The
!tkinter.filedialog.FileDialogdialog and its!tkinter.filedialog.LoadFileDialogand!tkinter.filedialog.SaveFileDialogsubclasses are now built from the themedtkinter.ttkwidgets by default instead of the classictkinterwidgets, and gained a use_ttk parameter to select between them. (Contributed by Serhiy Storchaka in59396.) - Added the
tkinter.systraymodule which provides the~tkinter.systray.SysTrayIconclass as an interface to the system tray icon and the~tkinter.systray.notifyfunction which sends a desktop notification. They require Tk 8.7/9.0 or newer. (Contributed by Serhiy Storchaka in153259.) tkinter.scrolledtext.ScrolledTextgained a use_ttk parameter to use the themedtkinter.ttkframe and scroll bar instead of the classictkinterwidgets. (Contributed by Serhiy Storchaka in59396.)tkinter.font.Fontcan now wrap a font description without creating a new named font, by passing it as font withexists=Trueand no name. This avoids a loss of precision in~tkinter.font.Font.actual,~tkinter.font.Font.measureand~tkinter.font.Font.metrics. (Contributed by Serhiy Storchaka in143990.)- Added the
tkinter.fontchoosermodule which provides the~tkinter.fontchooser.FontChooserclass as an interface to the native font selection dialog. (Contributed by Serhiy Storchaka in72880.) - Values of several Tcl object types returned by
tkinterare now converted to the corresponding Python type instead of being wrapped in a!_tkinter.Tcl_Obj:index,window,nsNameandparsedVarNameobjects tostr, andpixelscreen distances with no unit suffix tointorfloat. (Contributed by Serhiy Storchaka in153513.)
turtle
- Translations of the
turtledocstrings are now distributed on PyPI in theturtle-translationspackage. Additionally, added thePYTHON_TURTLE_LANGenvironment variable to select the language. (Contributed by Stan Ulbrych in156360.)
unicodedata
- The Unicode database has been updated to Unicode 18.0.0.
uuid
uuid.UUID,uuid.uuid4, anduuid.uuid7now have C implementations, with a pure Python fallback. In microbenchmarks, UUIDv4 and UUIDv7 generation are approximately 15 and 30 times faster, respectively, than the pure Python implementations. UUID construction and string conversion are also faster; seewhatsnew316-uuid-optimizationsfor the benchmark results. (Contributed by Yury Selivanov in139123.)
xml
- Add support for multiple multi-byte encodings in the
XML parser <xml.parsers.expat>: "cp932", "cp949", "cp950", "Big5", "EUC-JP", "GB2312", "GBK", "johab", and "Shift_JIS". Add partial support (only BMP characters) for multi-byte encodings "Big5-HKSCS", "EUC_JIS-2004", "EUC_JISX0213", "Shift_JIS-2004", "Shift_JISX0213", "utf-8-sig" and non-standard aliases like "UTF8" (without hyphen). The parser now raisesValueErrorfor known unsupported multi-byte encodings such as "ISO-2022-JP" or "raw-unicode-escape" instead of failing later, when encountering non-ASCII data. (Contributed by Serhiy Storchaka in62259.) xml.dom.minidomnow conforms closer to the DOM Level 1 specification. It checks names passed to the factory methods, rejects inserting or setting a node created by another document or making a node a descendant of itself, rejects a second element or document type child of a document and a notation child of a document fragment, reports attributes defaulted in the DTD and whether an attribute was given in the start tag, and implements!EntityReferencenodes and!Document.createEntityReference. (Contributed by Jason Orendorff and Serhiy Storchaka in44871.)xml.dom.minidomnow validates namespaces in the factory methods~xml.dom.Document.createElementNS,~xml.dom.Document.createAttributeNSand~xml.dom.Element.setAttributeNS.~xml.dom.NamespaceErris now raised for a malformed qualified name, for a prefix with an empty namespace, and for illegal use of thexmlandxmlnsprefixes. (Contributed by Serhiy Storchaka in156665.)~xml.dom.minidom.Node.toprettyxmlinxml.dom.minidomand~xml.etree.ElementTree.indentinxml.etree.ElementTreeno longer add whitespace inside an element which is marked withxml:space="preserve"or which contains text.!toprettyxmlalso takes into account the content model declared in the DTD. (Contributed by Serhiy Storchaka in81623.)- Add
!GetSpecifiedAttributeCountmethod to theXML parser <xml.parsers.expat>objects. It tells how many of the reported attributes were given in the start tag rather than defaulted from the DTD. (Contributed by Jason Orendorff and Serhiy Storchaka in44871.) - The
~xml.dom.minidom.Node.writexml,~xml.dom.minidom.Node.toxmland~xml.dom.minidom.Node.toprettyxmlmethods now work for!DocumentFragmentnodes inxml.dom.minidom. (Contributed by Serhiy Storchaka in54092.) ~xml.etree.ElementTree.XMLPullParserand~xml.etree.ElementTree.iterparsenow support the target parameter. The reported object is the value returned by the corresponding method of the target, so a large document can be parsed incrementally without building a tree for it. (Contributed by Serhiy Storchaka in63102.)- Added constant
~xml.parsers.expat.VERSION_INFOin theXML parser <xml.parsers.expat>module, which provides information about the version of the Expat library that was used for building the module.~xml.parsers.expat.version_infois now a named tuple. (Contributed by Serhiy Storchaka in157473.)
zipfile
- Add
ZipFile.remove() <zipfile.ZipFile.remove>to remove a member from an archive's central directory, andZipFile.repack() <zipfile.ZipFile.repack>to reclaim the space used by the local file entries of removed members. (Contributed by Danny Lin in51067.)
zlib
- Added constants
~zlib.ZLIB_VERSION_INFO,~zlib.zlib_version_info, and~zlib.ZLIBNG_VERSION_INFO, which provide information about the version of the zlib and the zlib-ng libraries in use. Added~zlib.zlib_versionas an alias of~zlib.ZLIB_RUNTIME_VERSION. (Contributed by Serhiy Storchaka in117404.)
Optimizations
datetime and time
datetime.datetime.strptime,datetime.date.strptime,datetime.time.strptime, andtime.strptimeare faster for common numeric formats such as%Y-%m-%dand%Y-%m-%d %H:%M:%S. (Contributed by Paul Ganssle in158252, based on work by Stan Ulbrych.)
re
- Character class escapes (
\d,\D,\s,\S,\wand\W) outside a character set, and character sets containing a single such escape (such as[\d]or[^\s]), are now compiled to a singleCATEGORYopcode instead of being wrapped in anINblock. This speeds up matching of patterns such as\d+and reduces the size of the compiled byte code. (Contributed by Serhiy Storchaka in152033and Pieter Eendebak in152056.)
uuid
-
C implementations accelerate UUID generation, construction, and string conversion. Microbenchmarks comparing the C and pure Python implementations measured the following speedups:
Operation Speedup uuid.uuid4generation15.01x uuid.uuid7generation29.64x uuid.UUIDfrom a string6.76x uuid.UUIDfrom bytes5.16x strconversion of a UUID6.66x (Contributed by Yury Selivanov in
139123.)
Removed
annotationlib
- The
!annotationlib.ForwardRef._evaluatemethod which has been deprecated since Python 3.14. Useannotationlib.ForwardRef.evaluateortyping.evaluate_forward_refinstead.
array
- The
'u'format code (wchar_t) which has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use'w'format code instead (Py_UCS4, always 4 bytes).
asyncio
- The
!asyncio.iscoroutinefunctionwhich has been deprecated since Python 3.14. Useinspect.iscoroutinefunctioninstead. - The event loop policy system, including the
!asyncio.AbstractEventLoopPolicy,!asyncio.DefaultEventLoopPolicy,!asyncio.WindowsSelectorEventLoopPolicyand!asyncio.WindowsProactorEventLoopPolicyclasses and the!asyncio.get_event_loop_policyand!asyncio.set_event_loop_policyfunctions, which have been deprecated since Python 3.14. Useasyncio.runorasyncio.Runnerwith a custom loop_factory instead.
functools
- Remove support for calling the Python implementation of
functools.reducewith function or sequence as keyword arguments, deprecated since Python 3.14. These parameters are now positional-only. (Contributed by Nikita Sobolev in149537.)
logging
- Remove support for custom logging handlers with the strm argument, deprecated since Python 3.14. Define handlers with the stream argument instead. (Contributed by Nikita Sobolev in
149598.)
mimetypes
- Remove support for undotted extensions in
mimetypes.MimeTypes.add_type, deprecated since Python 3.14. Valid extensions must now start with a'.'or be empty; undotted extensions raise aValueError. (Contributed by Nikita Sobolev in149720.)
shutil
- The
!ExecErrorexception which has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4. (Contributed by Stan Ulbrych in149567.)
symtable
- The
!symtable.Class.get_methodsmethod which has been deprecated since Python 3.14.
sys
- The
!_enablelegacywindowsfsencodingfunction which has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead. (Contributed by Stan Ulbrych in149595.)
sysconfig
- The
!sysconfig.expand_makefile_varsfunction which has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead. (Contributed by Stan Ulbrych in149499.)
tarfile
- The undocumented and unused
!tarfile.TarFile.tarfileattribute has been deprecated since Python 3.13.
xml.etree.ElementTree
- The undocumented
!xml.etree.ElementTree.ElementTree.write_c14nmethod and the support ofmethod="c14n"in~xml.etree.ElementTree.ElementTree.writeand~xml.etree.ElementTree.tostring. They never worked and always raisedValueError. Usexml.etree.ElementTree.canonicalizeinstead. (Contributed by Daniel Hillier in118318.)
Deprecated
New deprecations
abc:abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractproperty, soft-deprecated since Python 3.3, now raise aDeprecationWarning. These classes will be removed in Python 3.21; useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively instead.
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, deprecated since Python 3.9, are no longer imported byfrom ast import *and issue a deprecation warning on use. The classes are slated for removal in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tupleobjects, deprecated since Python 3.9, now issues a deprecation warning on use. This property is slated for removal in 3.21. Useast.Tuple.eltsinstead.
- Classes
__author__,__credits__,__copyright__and__date__:-
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.)
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodnow emits aDeprecationWarningand will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
struct:- The
'F'and'D'type codes, soft-deprecated since Python 3.15, are now deprecated. These codes will be removed in Python 3.21. Use the two-letter forms'Zf'and'Zd'instead. (Contributed by Sergey B Kirpichev in121249.)
- The
tempfile:- The private
tempfile._TemporaryFileWrappername is deprecated and is slated for removal in Python 3.21. Use the new publictempfile.TemporaryFileWrapperinstead, which is the return type oftempfile.NamedTemporaryFile.
- The private
tkinter:tkinter.filedialog.askopenfilesis deprecated and slated for removal in Python 3.19. Opening several files at once is error-prone, and the returned list cannot be used in awithstatement. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.17
datetime:~datetime.datetime.strptimecalls using a format string containing%e(day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in70647.)
collections.abc:-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
encodings:- Passing non-ascii encoding names to
encodings.normalize_encodingis deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in136702.)
- Passing non-ascii encoding names to
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOS. (137586)
typing:-
Before Python 3.14, old-style unions were implemented using the private class
typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers liketyping.get_originandtyping.get_argsinstead of relying on private implementation details. -
typing.ByteString, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
tkinter:- The
!tkinter.Variablemethods!trace_variable,!trace(an alias of!trace_variable),!trace_vdeleteand!trace_vinfo, deprecated since Python 3.14, are scheduled for removal in Python 3.17. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)
- The
Pending removal in Python 3.18
-
No longer accept a boolean value when a file descriptor is expected. (Contributed by Serhiy Storchaka in
82626.) -
decimal:- The non-standard and undocumented
~decimal.Decimalformat specifier'N', which is only supported in the!decimalmodule's C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in89902.)
- The non-standard and undocumented
-
Deprecations defined by
829:importlines in{name}.pthfiles are silently ignored.
(Contributed by Barry Warsaw in
148641.)
Pending removal in Python 3.19
builtins:- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.)
- Passing a complex number as the real or imag argument in the
ctypes:- Implicitly switching to the MSVC-compatible struct layout by setting
~ctypes.Structure._pack_but not~ctypes.Structure._layout_on non-Windows platforms.
- Implicitly switching to the MSVC-compatible struct layout by setting
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in various!hashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.
-
http.cookies:http.cookies.Morsel.js_outputis deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_outputis deprecated and will be removed in Python 3.19.
imaplib:-
Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.Before Python 3.14, this property was used to implement the corresponding
read()andreadline()methods for~imaplib.IMAP4but this is no longer the case since then.
-
tkinter:tkinter.filedialog.askopenfileshas been deprecated since Python 3.16. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.20
-
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling~object.__init__method on initialized~struct.Structobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.) -
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.) -
Deprecations defined by
829:- Warnings are produced for
importlines found in{name}.pthfiles. {name}.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in
148641.) - Warnings are produced for
-
ast:- Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.
- Creating instances of abstract AST nodes (such as
-
typing:-
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
Pending removal in Python 3.21
-
abc- Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively.
- Soft-deprecated since Python 3.3
-
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
- Classes
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodis deprecated since Python 3.16 and will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
-
struct:- Soft-deprecated since Python 3.15, using
'F'and'D'type codes are now deprecated. These codes will be removed in Python 3.21. Use instead two-letter forms'Zf'and'Zd'.
- Soft-deprecated since Python 3.15, using
-
tempfile:tempfile._TemporaryFileWrapperwill be removed in Python 3.21. Use the publictempfile.TemporaryFileWrapperinstead.
Pending removal in future versions
The following APIs will be removed in the future, although there is currently no date scheduled for their removal.
argparse:- Nesting argument groups and nesting mutually exclusive groups are deprecated.
- Passing the undocumented keyword argument prefix_chars to
~argparse.ArgumentParser.add_argument_groupis now deprecated. - The
argparse.FileTypetype converter is deprecated.
builtins:- Generators:
throw(type, exc, tb)andathrow(type, exc, tb)signature is deprecated: usethrow(exc)andathrow(exc)instead, the single argument signature. - Currently Python accepts numeric literals immediately followed by keywords, for example
0in x,1or x,0if 1else 2. It allows confusing and ambiguous expressions like[0x1for x in y](which can be interpreted as[0x1 for x in y]or[0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In a future release it will be changed to a syntax error. (87999) - Support for
__index__()and__int__()method returning non-int type: these methods will be required to return an instance of a strict subclass ofint. - Support for
__float__()method returning a strict subclass offloat: these methods will be required to return an instance offloat. - Support for
__complex__()method returning a strict subclass ofcomplex: these methods will be required to return an instance ofcomplex.
- Generators:
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.)codecs: useopeninstead ofcodecs.open. (133038)!codeobject.co_lnotab: use thecodeobject.co_linesmethod instead.datetime:~datetime.datetime.utcnow: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp: usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: Plural value must be an integer.importlib:~importlib.util.cache_from_sourcedebug_override parameter is deprecated: use the optimization parameter instead.
importlib.metadata:EntryPointstuple interface.- Implicit
Noneon return values.
logging: thewarn()method has been deprecated since Python 3.3, use~logging.warninginstead.mailbox: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.os: Callingos.register_at_forkin a multi-threaded process.os.path:os.path.commonprefixis deprecated, useos.path.commonpathfor path prefixes. Theos.path.commonprefixfunction is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.!pydoc.ErrorDuringImport: A tuple value for exc_info parameter is deprecated, use an exception instance.re: More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in91760.)shutil:~shutil.rmtree's onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:~ssl.SSLContext.set_npn_protocolsand!selected_npn_protocolare deprecated: use ALPN instead.ssl.OP_NO_SSL*optionsssl.OP_NO_TLS*optionsssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.TLSVersion.TLSv1_1
threadingmethods:!threading.Condition.notifyAll: use~threading.Condition.notify_all.!threading.Event.isSet: use~threading.Event.is_set.!threading.Thread.isDaemon,threading.Thread.setDaemon: usethreading.Thread.daemonattribute.!threading.Thread.getName,threading.Thread.setName: usethreading.Thread.nameattribute.!threading.currentThread: usethreading.current_thread.!threading.activeCount: usethreading.active_count.
typing.Text(92332).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in105499.) unittest.IsolatedAsyncioTestCase: it is deprecated to return a value that is notNonefrom a test case.urllib.parsedeprecated functions:~urllib.parse.urlparseinsteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partial writes.xml.etree.ElementTree: Testing the truth value of an~xml.etree.ElementTree.Elementis deprecated. In a future release it will always returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cacheis deprecated: usesys._clear_internal_cachesinstead.
Porting to Python 3.16
This section lists previously described changes and other bugfixes that may require changes to your code.
- In
tkinter, the name parameter of the~tkinter.Misc.wait_variable,~tkinter.Misc.setvarand~tkinter.Misc.getvarmethods and the value parameter of!setvarare now required. Calling these methods without them, which formerly defaulted to'PY_VAR'and'1', now raisesTypeError. (Contributed by Serhiy Storchaka in152587.) uuid.UUIDnow consistently raisesTypeErrorwhen the bytes or bytes_le argument is not abytesobject. Previously, some invalid inputs raisedAssertionErrororValueError. (Contributed by Yury Selivanov in139123.)xml.dom.minidomnow raises~xml.dom.InvalidCharacterErrfor a name which is not a valid XML name,~xml.dom.WrongDocumentErrfor inserting or setting a node created by another document,~xml.dom.InuseAttributeErrfor setting an attribute node which belongs to another element, and~xml.dom.HierarchyRequestErrfor inserting a node into itself or its descendant. It also rejects a second element or document type child of a document and a notation child of a document fragment. Such operations formerly succeeded and produced an invalid document or an endless loop. On the other hand,!Element.removeAttributeand!Element.removeAttributeNSno longer raise~xml.dom.NotFoundErrif there is no matching attribute. Attributes defaulted in the DTD are no longer omitted when parsing. (Contributed by Jason Orendorff and Serhiy Storchaka in44871.)xml.dom.minidomnow raises~xml.dom.NamespaceErrfor a malformed qualified name, for a prefix with an empty namespace, and for illegal use of thexmlandxmlnsprefixes. Such operations formerly succeeded and produced an invalid document. (Contributed by Serhiy Storchaka in156665.)~xml.dom.minidom.Node.toprettyxmlinxml.dom.minidomand~xml.etree.ElementTree.indentinxml.etree.ElementTreeno longer add whitespace inside an element which is marked withxml:space="preserve"or which contains text, because this changed the content of the element.!toprettyxmlalso takes into account the content model declared in the DTD. (Contributed by Serhiy Storchaka in81623.)- On Windows, seeking a pipe now fails instead of silently appearing to succeed:
os.lseekand~io.IOBase.seekraiseOSError, and~io.IOBase.seekablereturnsFalse. As a consequence, opening a pipe in a read-write binary mode ('r+b'or'w+b') now raisesio.UnsupportedOperationunless buffering is disabled. (Contributed by An Long in86768.)
Build changes
-
Remove the bundled copy of the libmpdec decimal library from the CPython source tree to simplify maintenance and updates. The
decimalmodule will now unconditionally use the system's libmpdec decimal library. Also remove the now unused!--with-system-libmpdecconfigureflag. This change has no impact on binary releases of Python, which have been built against a separate copy of libmpdec for the past several releases.(Contributed by Sergey B Kirpichev in
115119.) -
Add a
--with-build-details-suffixconfigure flag to allow Linux distributions that co-install multiple versions of Python in the same tree to avoidbuild-details.jsonclashes.(Contributed by Stefano Rivera in
131372.) -
Add the
--with-cursesconfigureoption to select the curses backend for thecursesandcurses.panelmodules. In addition toncurseswandncurses, it can now build against the system's nativecurseslibrary (for example on NetBSD or Solaris), with wide-character support when the library provides it.--without-cursesexcludes the modules from the build.(Contributed by Serhiy Storchaka in
136687.) -
Add the
--with-zliband--with-bzip2configureoptions to select the zlib and bzip2 implementations used to build thezlibandbz2modules. In addition to the default system libraries, they can build against zlib-rs and libbzip2-rs, and--with-zlib=zlib-ngverifies that the detected zlib is zlib-ng.--without-zliband--without-bzip2exclude the modules from the build.(Contributed by Stan Ulbrych in
139314.) -
Add the
--with-hwaddress-sanitizerconfigureoption to build with HWAddressSanitizer.(Contributed by Stan Ulbrych, Florian Mayer and AnnaAr321 in
156049.)
C API changes
New features
- Add
Py_HashBufferto the limited C API. (Contributed by Victor Stinner in148233.) - Add
Py_SETREFandPy_XSETREFmacros to the limited C API. (Contributed by Nathan Goldbaum and Victor Stinner in158842.)
Porting to Python 3.16
PyType_ClearCacheis now a no-op as the type cache is now implemented per-type. It still returns the current version tag.- Functions reading marshalled data from a
FILE*, such asPyMarshal_ReadObjectFromFile, now raiseOSErrorfor I/O errors andKeyboardInterruptfor interrupted reading, instead ofEOFError. (Contributed by Serhiy Storchaka in155907.) PyMarshal_WriteLongToFileandPyMarshal_WriteObjectToFilenow set the error indicator for I/O errors and interrupted writing, instead of ignoring them.PyMarshal_WriteObjectToFilenow also sets the error indicator if the value cannot be marshalled. (Contributed by Serhiy Storchaka in155907.)_Py_c_absno longer setserrnoto zero on success, but rather leaves it unchanged. (Contributed by Sergey B Kirpichev in155526.)
Deprecated C APIs
PyGen_New,PyGen_NewWithQualName,PyCoro_New, andPyAsyncGen_Neware deprecated. They are scheduled for removal in 3.18.- Deprecate
PyInitConfig_GetExitCode,PyStatus_Exit, andPyStatus_IsExitfunctions, andPyStatus.exitcodemember.Py_InitializeFromInitConfigandPy_InitializeFromConfigcan no longer return an exit code. Instead, if a command line option wants to exit Python, the option is now processed inPy_RunMain. (Contributed by Victor Stinner in158080.) PyModule_GetFilenameis no longer deprecated, but usingPyModule_GetFilenameObjectinstead is still recommended. (Contributed by Victor Stinner in154757.)- Soft deprecate functions modifying Unicode strings:
PyUnicode_New,PyUnicode_CopyCharacters,PyUnicode_Fill,PyUnicode_Resize,PyUnicode_WRITEandPyUnicode_WriteChar. Use the saferPyUnicodeWriterAPI instead. (Contributed by Victor Stinner in157710.)
Pending removal in Python 3.18
-
The following private functions are deprecated and planned for removal in Python 3.18:
!_PyBytes_Join: usePyBytes_Join.!_PyDict_GetItemStringWithError: usePyDict_GetItemStringRef.!_PyDict_Pop(): usePyDict_Pop.!_PyLong_Sign(): usePyLong_GetSign.!_PyLong_FromDigitsand!_PyLong_New: usePyLongWriter_Create.!_PyThreadState_UncheckedGet: usePyThreadState_GetUnchecked.!_PyUnicode_AsString: usePyUnicode_AsUTF8.!_PyUnicodeWriter_Init: replace_PyUnicodeWriter_Init(&writer)withwriter = PyUnicodeWriter_Create(0) <PyUnicodeWriter_Create>.!_PyUnicodeWriter_Finish: replace_PyUnicodeWriter_Finish(&writer)withPyUnicodeWriter_Finish(writer) <PyUnicodeWriter_Finish>.!_PyUnicodeWriter_Dealloc: replace_PyUnicodeWriter_Dealloc(&writer)withPyUnicodeWriter_Discard(writer) <PyUnicodeWriter_Discard>.!_PyUnicodeWriter_WriteChar: replace_PyUnicodeWriter_WriteChar(&writer, ch)withPyUnicodeWriter_WriteChar(writer, ch) <PyUnicodeWriter_WriteChar>.!_PyUnicodeWriter_WriteStr: replace_PyUnicodeWriter_WriteStr(&writer, str)withPyUnicodeWriter_WriteStr(writer, str) <PyUnicodeWriter_WriteStr>.!_PyUnicodeWriter_WriteSubstring: replace_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)withPyUnicodeWriter_WriteSubstring(writer, str, start, end) <PyUnicodeWriter_WriteSubstring>.!_PyUnicodeWriter_WriteASCIIString: replace_PyUnicodeWriter_WriteASCIIString(&writer, str, size)withPyUnicodeWriter_WriteASCII(writer, str, size) <PyUnicodeWriter_WriteASCII>.!_PyUnicodeWriter_WriteLatin1String: replace_PyUnicodeWriter_WriteLatin1String(&writer, str, size)by decoding the string withPyUnicode_DecodeLatin1, writing the result withPyUnicodeWriter_WriteStr, and releasing the result withPy_DECREF.!_PyUnicodeWriter_Prepare: (no replacement).!_PyUnicodeWriter_PrepareKind: (no replacement).!_Py_HashPointer: usePy_HashPointer.!_Py_fopen_obj: usePy_fopen.PyGen_New: (no replacement).PyGen_NewWithQualName: (no replacement).PyCoro_New: (no replacement).PyAsyncGen_New: (no replacement).
The pythoncapi-compat project can be used to get these new public functions on Python 3.13 and older. (Contributed by Victor Stinner in
128863.)
Pending removal in Python 3.19
456embedders support for the string hashing scheme definition.
Pending removal in Python 3.20
!_PyObject_CallMethodId,!_PyObject_GetAttrIdand!_PyUnicode_FromIdare deprecated since 3.15 and will be removed in 3.20. Instead, usePyUnicode_InternFromString()and cache the result in the module state, then callPyObject_CallMethodorPyObject_GetAttr. (Contributed by Victor Stinner in141049.)- The
cvalfield inPyComplexObject(128813). UsePyComplex_AsCComplexandPyComplex_FromCComplexto convert a Python complex number to/from the CPy_complexrepresentation. - Macros
!Py_MATH_PIland!Py_MATH_El.
Pending removal in future versions
The following APIs are deprecated and will be removed, although there is currently no date scheduled for their removal.
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch: UsePyErr_GetRaisedExceptioninstead.PyErr_NormalizeException: UsePyErr_GetRaisedExceptioninstead.PyErr_Restore: UsePyErr_SetRaisedExceptioninstead.PyOS_AfterFork: UsePyOS_AfterFork_Childinstead.PySlice_GetIndicesEx: UsePySlice_UnpackandPySlice_AdjustIndicesinstead.PyUnicode_READY: Unneeded since Python 3.12!PyErr_Display: UsePyErr_DisplayExceptioninstead.!_PyErr_ChainExceptions: Use!_PyErr_ChainExceptions1instead.!PyBytesObject.ob_shashmember: callPyObject_Hashinstead.- Thread Local Storage (TLS) API:
PyThread_create_key: UsePyThread_tss_allocinstead.PyThread_delete_key: UsePyThread_tss_freeinstead.PyThread_set_key_value: UsePyThread_tss_setinstead.PyThread_get_key_value: UsePyThread_tss_getinstead.PyThread_delete_key_value: UsePyThread_tss_deleteinstead.PyThread_ReInitTLS: Unneeded since Python 3.7.
Removed C APIs
-
Remove 21 global configuration variables, deprecated in Python 3.12. To initialize Python, the
PyInitConfig C API <pyinitconfig_api>can be used instead. To read these variables at runtime,PyConfig_Getcan be used instead. Removed variables with theirPyInitConfig C API <pyinitconfig_api>andPyConfig_Getreplacement:!Py_DebugFlag: Use"parser_debug"instead.!Py_VerboseFlag: Use"verbose"instead.!Py_QuietFlag: Use"quiet"instead.!Py_InteractiveFlag: Use"interactive"instead.!Py_InspectFlag: Use"inspect"instead.!Py_OptimizeFlag: Use"optimization_level"instead.!Py_NoSiteFlag: Use"site_import"instead (opposite value).!Py_BytesWarningFlag: Use"bytes_warning"instead.!Py_FrozenFlag: Use"pathconfig_warnings"instead (opposite value).!Py_IgnoreEnvironmentFlag: Use"use_environment"instead (opposite value).!Py_DontWriteBytecodeFlag: Use"write_bytecode"instead (opposite value).!Py_NoUserSiteDirectory: Use"user_site_directory"instead (opposite value).!Py_UnbufferedStdioFlag: Use"buffered_stdio"instead (opposite value).!Py_HashRandomizationFlag: Use"hash_seed"instead.!Py_IsolatedFlag: Use"isolated"instead.!Py_LegacyWindowsFSEncodingFlag: Use"legacy_windows_fs_encoding"instead.!Py_LegacyWindowsStdioFlag: Use"legacy_windows_stdio"instead.!Py_FileSystemDefaultEncoding,!Py_HasFileSystemDefaultEncoding: Use"filesystem_encoding"instead.!Py_FileSystemDefaultEncodeErrors: Use"filesystem_errors"instead.!Py_UTF8Mode: Use"utf8_mode"instead.
(Contributed by Victor Stinner in
158001.) -
Remove
!PyEval_InitThreadsfunction which did nothing since Python 3.7 and was deprecated since Python 3.9. (Contributed by Victor Stinner in154757.) -
Remove
!Py_SetProgramNameand!Py_SetPythonHomefunctions, deprecated since Python 3.11. Instead, usePyInitConfig C API <pyinitconfig_api>to set respectively"program_name"and"home". (Contributed by Victor Stinner in158001.) -
Remove
!PySys_SetArgvand!PySys_SetArgvExfunctions, deprecated since Python 3.11. Instead, set directlysys.argv, and maybe alsosys.path. (Contributed by Victor Stinner in158001.) -
The
!PyUnstable_ExecutableKindsarray, as well as the macros!PyUnstable_EXECUTABLE_KIND_SKIP,!PyUnstable_EXECUTABLE_KIND_PY_FUNCTION,!PyUnstable_EXECUTABLE_KIND_BUILTIN_FUNCTION,!PyUnstable_EXECUTABLE_KIND_METHOD_DESCRIPTORand!PyUnstable_EXECUTABLE_KINDS, were removed.(Contributed by Peters Bierma and Viktorin in
152105.)
What's New In Python 3.2
This article explains the new features in Python 3.2 as compared to 3.1. Python 3.2 was released on February 20, 2011. It focuses on a few highlights and gives a few examples. For full details, see the Misc/NEWS file.
392 - Python 3.2 Release Schedule
PEP 384: Defining a Stable ABI
In the past, extension modules built for one Python version were often not usable with other Python versions. Particularly on Windows, every feature release of Python required rebuilding all extension modules that one wanted to use. This requirement was the result of the free access to Python interpreter internals that extension modules could use.
With Python 3.2, an alternative approach becomes available: extension modules which restrict themselves to a limited API (by defining Py_LIMITED_API) cannot use many of the internals, but are constrained to a set of API functions that are promised to be stable for several releases. As a consequence, extension modules built for 3.2 in that mode will also work with 3.3, 3.4, and so on. Extension modules that make use of details of memory structures can still be built, but will need to be recompiled for every feature release.
384 - Defining a Stable ABI
PEP written by Martin von Löwis.
PEP 389: Argparse Command Line Parsing Module
A new module for command line parsing, argparse, was introduced to overcome the limitations of optparse which did not provide support for positional arguments (not just options), subcommands, required options and other common patterns of specifying and validating options.
This module has already had widespread success in the community as a third-party module. Being more fully featured than its predecessor, the argparse module is now the preferred module for command-line processing. The older module is still being kept available because of the substantial amount of legacy code that depends on it.
Here's an annotated example parser showing features like limiting results to a set of choices, specifying a metavar in the help screen, validating that one or more positional arguments is present, and making a required option:
import argparse
parser = argparse.ArgumentParser(
description = 'Manage servers', # main description for help
epilog = 'Tested on Solaris and Linux') # displayed after help
parser.add_argument('action', # argument name
choices = ['deploy', 'start', 'stop'], # three allowed values
help = 'action on each target') # help msg
parser.add_argument('targets',
metavar = 'HOSTNAME', # var name used in help msg
nargs = '+', # require one or more targets
help = 'url for target machines') # help msg explanation
parser.add_argument('-u', '--user', # -u or --user option
required = True, # make it a required argument
help = 'login as user')
Example of calling the parser on a command string:
>>> cmd = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'
>>> result = parser.parse_args(cmd.split())
>>> result.action
'deploy'
>>> result.targets
['sneezy.example.com', 'sleepy.example.com']
>>> result.user
'skycaptain'
Example of the parser's automatically generated help:
>>> parser.parse_args('-h'.split())
usage: manage_cloud.py [-h] -u USER
{deploy,start,stop} HOSTNAME [HOSTNAME ...]
Manage servers
positional arguments:
{deploy,start,stop} action on each target
HOSTNAME url for target machines
optional arguments:
-h, --help show this help message and exit
-u USER, --user USER login as user
Tested on Solaris and Linux
An especially nice argparse feature is the ability to define subparsers, each with their own argument patterns and help displays:
import argparse
parser = argparse.ArgumentParser(prog='HELM')
subparsers = parser.add_subparsers()
parser_l = subparsers.add_parser('launch', help='Launch Control') # first subgroup
parser_l.add_argument('-m', '--missiles', action='store_true')
parser_l.add_argument('-t', '--torpedos', action='store_true')
parser_m = subparsers.add_parser('move', help='Move Vessel', # second subgroup
aliases=('steer', 'turn')) # equivalent names
parser_m.add_argument('-c', '--course', type=int, required=True)
parser_m.add_argument('-s', '--speed', type=int, default=0)
$ ./helm.py --help # top level help (launch and move)
$ ./helm.py launch --help # help for launch options
$ ./helm.py launch --missiles # set missiles=True and torpedos=False
$ ./helm.py steer --course 180 --speed 5 # set movement parameters
389 - New Command Line Parsing Module
PEP written by Steven Bethard.
upgrading-optparse-code for details on the differences from optparse.
PEP 391: Dictionary Based Configuration for Logging
The logging module provided two kinds of configuration, one style with function calls for each option or another style driven by an external file saved in a configparser format. Those options did not provide the flexibility to create configurations from JSON or YAML files, nor did they support incremental configuration, which is needed for specifying logger options from a command line.
To support a more flexible style, the module now offers logging.config.dictConfig for specifying logging configuration with plain Python dictionaries. The configuration options include formatters, handlers, filters, and loggers. Here's a working example of a configuration dictionary:
{"version": 1,
"formatters": {"brief": {"format": "%(levelname)-8s: %(name)-15s: %(message)s"},
"full": {"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"}
},
"handlers": {"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"level": "INFO",
"stream": "ext://sys.stdout"},
"console_priority": {
"class": "logging.StreamHandler",
"formatter": "full",
"level": "ERROR",
"stream": "ext://sys.stderr"}
},
"root": {"level": "DEBUG", "handlers": ["console", "console_priority"]}}
If that dictionary is stored in a file called conf.json, it can be loaded and called with code like this:
>>> import json, logging.config
>>> with open('conf.json') as f:
... conf = json.load(f)
...
>>> logging.config.dictConfig(conf)
>>> logging.info("Transaction completed normally")
INFO : root : Transaction completed normally
>>> logging.critical("Abnormal termination")
2011-02-17 11:14:36,694 root CRITICAL Abnormal termination
391 - Dictionary Based Configuration for Logging
PEP written by Vinay Sajip.
PEP 3148: The concurrent.futures module
Code for creating and managing concurrency is being collected in a new top-level namespace, concurrent. Its first member is a futures package which provides a uniform high-level interface for managing threads and processes.
The design for concurrent.futures was inspired by the java.util.concurrent package. In that model, a running call and its result are represented by a ~concurrent.futures.Future object that abstracts features common to threads, processes, and remote procedure calls. That object supports status checks (running or done), timeouts, cancellations, adding callbacks, and access to results or exceptions.
The primary offering of the new module is a pair of executor classes for launching and managing calls. The goal of the executors is to make it easier to use existing tools for making parallel calls. They save the effort needed to setup a pool of resources, launch the calls, create a results queue, add time-out handling, and limit the total number of threads, processes, or remote procedure calls.
Ideally, each application should share a single executor across multiple components so that process and thread limits can be centrally managed. This solves the design challenge that arises when each component has its own competing strategy for resource management.
A simple of example of ~concurrent.futures.ThreadPoolExecutor is a launch of four parallel threads for copying files:
import concurrent.futures, shutil
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
e.submit(shutil.copy, 'src3.txt', 'dest4.txt')
3148 - Futures -- Execute Computations Asynchronously
PEP written by Brian Quinlan.
Code for Threaded Parallel URL reads<threadpoolexecutor-example>, an example using threads to fetch multiple web pages in parallel.
Code for computing prime numbers in parallel<processpoolexecutor-example>, an example demonstrating ~concurrent.futures.ProcessPoolExecutor.
PEP 3147: PYC Repository Directories
Python's scheme for caching bytecode in .pyc files did not work well in environments with multiple Python interpreters. If one interpreter encountered a cached file created by another interpreter, it would recompile the source and overwrite the cached file, thus losing the benefits of caching.
The issue of "pyc fights" has become more pronounced as it has become commonplace for Linux distributions to ship with multiple versions of Python. These conflicts also arise with CPython alternatives such as Unladen Swallow.
To solve this problem, Python's import machinery has been extended to use distinct filenames for each interpreter. Instead of Python 3.2 and Python 3.3 and Unladen Swallow each competing for a file called "mymodule.pyc", they will now look for "mymodule.cpython-32.pyc", "mymodule.cpython-33.pyc", and "mymodule.unladen10.pyc". And to prevent all of these new files from cluttering source directories, the pyc files are now collected in a "__pycache__" directory stored under the package directory.
Aside from the filenames and target directories, the new scheme has a few aspects that are visible to the programmer:
-
Imported modules now have a
__cached__attribute which stores the name of the actual file that was imported:>>> import collections >>> collections.__cached__ # doctest: +SKIP 'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
-
The tag that is unique to each interpreter is accessible from the
!impmodule:>>> import imp # doctest: +SKIP >>> imp.get_tag() # doctest: +SKIP 'cpython-32'
-
Scripts that try to deduce source filename from the imported file now need to be smarter. It is no longer sufficient to simply strip the "c" from a ".pyc" filename. Instead, use the new functions in the
!impmodule:>>> imp.source_from_cache('c:/py32/lib/__pycache__/collections.cpython-32.pyc') # doctest: +SKIP 'c:/py32/lib/collections.py' >>> imp.cache_from_source('c:/py32/lib/collections.py') # doctest: +SKIP 'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
-
The
py_compileandcompileallmodules have been updated to reflect the new naming convention and target directory. The command-line invocation of compileall has new options:-ifor specifying a list of files and directories to compile and-bwhich causes bytecode files to be written to their legacy location rather than __pycache__. -
The
importlib.abcmodule has been updated with newabstract base classes <abstract base class>for loading bytecode files. The obsolete ABCs,!PyLoaderand!PyPycLoader, have been deprecated (instructions on how to stay Python 3.1 compatible are included with the documentation).
3147 - PYC Repository Directories
PEP written by Barry Warsaw.
PEP 3149: ABI Version Tagged .so Files
The PYC repository directory allows multiple bytecode cache files to be co-located. This PEP implements a similar mechanism for shared object files by giving them a common directory and distinct names for each version.
The common directory is "pyshared" and the file names are made distinct by identifying the Python implementation (such as CPython, PyPy, Jython, etc.), the major and minor version numbers, and optional build flags (such as "d" for debug, "m" for pymalloc, "u" for wide-unicode). For an arbitrary package "foo", you may see these files when the distribution package is installed:
/usr/share/pyshared/foo.cpython-32m.so
/usr/share/pyshared/foo.cpython-33md.so
In Python itself, the tags are accessible from functions in the sysconfig module:
>>> import sysconfig
>>> sysconfig.get_config_var('SOABI') # find the version tag
'cpython-32mu'
>>> sysconfig.get_config_var('EXT_SUFFIX') # find the full filename extension
'.cpython-32mu.so'
3149 - ABI Version Tagged .so Files
PEP written by Barry Warsaw.
PEP 3333: Python Web Server Gateway Interface v1.0.1
This informational PEP clarifies how bytes/text issues are to be handled by the WSGI protocol. The challenge is that string handling in Python 3 is most conveniently handled with the str type even though the HTTP protocol is itself bytes oriented.
The PEP differentiates so-called native strings that are used for request/response headers and metadata versus byte strings which are used for the bodies of requests and responses.
The native strings are always of type str but are restricted to code points between U+0000 through U+00FF which are translatable to bytes using Latin-1 encoding. These strings are used for the keys and values in the environment dictionary and for response headers and statuses in the !start_response function. They must follow 2616 with respect to encoding. That is, they must either be ISO-8859-1 characters or use 2047 MIME encoding.
For developers porting WSGI applications from Python 2, here are the salient points:
- If the app already used strings for headers in Python 2, no change is needed.
- If instead, the app encoded output headers or decoded input headers, then the headers will need to be re-encoded to Latin-1. For example, an output header encoded in utf-8 was using
h.encode('utf-8')now needs to convert from bytes to native strings usingh.encode('utf-8').decode('latin-1'). - Values yielded by an application or sent using the
!writemethod must be byte strings. The!start_responsefunction and environ must use native strings. The two cannot be mixed.
For server implementers writing CGI-to-WSGI pathways or other CGI-style protocols, the users must to be able access the environment using native strings even though the underlying platform may have a different convention. To bridge this gap, the wsgiref module has a new function, wsgiref.handlers.read_environ for transcoding CGI variables from os.environ into native strings and returning a new dictionary.
3333 - Python Web Server Gateway Interface v1.0.1
PEP written by Phillip Eby.
Other Language Changes
Some smaller changes made to the core Python language are:
-
String formatting for
formatandstr.formatgained new capabilities for the format character #. Previously, for integers in binary, octal, or hexadecimal, it caused the output to be prefixed with '0b', '0o', or '0x' respectively. Now it can also handle floats, complex, and Decimal, causing the output to always have a decimal point even when no digits follow it.>>> format(20, '#o') '0o24' >>> format(12.34, '#5.0f') ' 12.'
(Suggested by Mark Dickinson and implemented by Eric Smith in
7094.) -
There is also a new
str.format_mapmethod that extends the capabilities of the existingstr.formatmethod by accepting arbitrarymappingobjects. This new method makes it possible to use string formatting with any of Python's many dictionary-like objects such as~collections.defaultdict,~shelve.Shelf,~configparser.ConfigParser, ordbm. It is also useful with customdictsubclasses that normalize keys before look-up or that supply a~object.__missing__method for unknown keys:>>> import shelve >>> d = shelve.open('tmp.shl') >>> 'The {project_name} status is {status} as of {date}'.format_map(d) 'The testing project status is green as of February 15, 2011' >>> class LowerCasedDict(dict): ... def __getitem__(self, key): ... return dict.__getitem__(self, key.lower()) ... >>> lcd = LowerCasedDict(part='widgets', quantity=10) >>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd) 'There are 10 widgets in stock' >>> class PlaceholderDict(dict): ... def __missing__(self, key): ... return '<{}>'.format(key) ... >>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict()) 'Hello <name>, welcome to <location>'
(Suggested by Raymond Hettinger and implemented by Eric Smith in
6081.)
-
The interpreter can now be started with a quiet option,
-q, to prevent the copyright and version information from being displayed in the interactive mode. The option can be introspected using thesys.flagsattribute:$ python -q >>> sys.flags sys.flags(debug=0, division_warning=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)(Contributed by Marcin Wojdyr in
1772833). -
The
hasattrfunction works by callinggetattrand detecting whether an exception is raised. This technique allows it to detect methods created dynamically by~object.__getattr__or~object.__getattribute__which would otherwise be absent from the class dictionary. Formerly, hasattr would catch any exception, possibly masking genuine errors. Now, hasattr has been tightened to only catchAttributeErrorand let other exceptions pass through:>>> class A: ... @property ... def f(self): ... return 1 // 0 ... >>> a = A() >>> hasattr(a, 'f') Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero(Discovered by Yury Selivanov and fixed by Benjamin Peterson;
9666.) -
The
strof a float or complex number is now the same as itsrepr. Previously, thestrform was shorter but that just caused confusion and is no longer needed now that the shortest possiblerepris displayed by default:>>> import math >>> repr(math.pi) '3.141592653589793' >>> str(math.pi) '3.141592653589793'
(Proposed and implemented by Mark Dickinson;
9337.) -
memoryviewobjects now have a~memoryview.releasemethod and they also now support the context management protocol. This allows timely release of any resources that were acquired when requesting a buffer from the original object.>>> with memoryview(b'abcdefgh') as v: ... print(v.tolist()) [97, 98, 99, 100, 101, 102, 103, 104]
(Added by Antoine Pitrou;
9757.) -
Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block:
def outer(x): def inner(): return x inner() del xThis is now allowed. Remember that the target of an
exceptclause is cleared, so this code which used to work with Python 2.6, raised aSyntaxErrorwith Python 3.1 and now works again:def f(): def print_error(): print(e) try: something except Exception as e: print_error() # implicit "del e" here(See
4617.) -
Struct sequence types <struct-sequence-objects>are now subclasses of tuple. This means that C structures like those returned byos.stat,time.gmtime, andsys.version_infonow work like anamed tupleand now work with functions and methods that expect a tuple as an argument. This is a big step forward in making the C structures as flexible as their pure Python counterparts:>>> import sys >>> isinstance(sys.version_info, tuple) True >>> 'Version %d.%d.%d %s(%d)' % sys.version_info # doctest: +SKIP 'Version 3.2.0 final(0)'
(Suggested by Arfrever Frehtes Taifersar Arahesis and implemented by Benjamin Peterson in
8413.) -
Warnings are now easier to control using the
PYTHONWARNINGSenvironment variable as an alternative to using-Wat the command line:$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'(Suggested by Barry Warsaw and implemented by Philip Jenvey in
7301.) -
A new warning category,
ResourceWarning, has been added. It is emitted when potential issues with resource consumption or cleanup are detected. It is silenced by default in normal release builds but can be enabled through the means provided by thewarningsmodule, or on the command line.A
ResourceWarningis issued at interpreter shutdown if thegc.garbagelist isn't empty, and ifgc.DEBUG_UNCOLLECTABLEis set, all uncollectable objects are printed. This is meant to make the programmer aware that their code contains object finalization issues.A
ResourceWarningis also issued when afile objectis destroyed without having been explicitly closed. While the deallocator for such object ensures it closes the underlying operating system resource (usually, a file descriptor), the delay in deallocating the object could produce various issues, especially under Windows. Here is an example of enabling the warning from the command line:$ python -q -Wdefault >>> f = open("foo", "wb") >>> del f __main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>(Added by Antoine Pitrou and Georg Brandl in
10093and477863.) -
rangeobjects now support index and count methods. This is part of an effort to make more objects fully implement thecollections.Sequence <collections.abc.Sequence>abstract base class. As a result, the language will have a more uniform API. In addition,rangeobjects now support slicing and negative indices, even with values larger thansys.maxsize. This makes range more interoperable with lists:>>> range(0, 100, 2).count(10) 1 >>> range(0, 100, 2).index(10) 5 >>> range(0, 100, 2)[5] 10 >>> range(0, 100, 2)[0:5] range(0, 10, 2)(Contributed by Daniel Stutzbach in
9213, by Alexander Belopolsky in2690, and by Nick Coghlan in10889.) -
The
callablebuiltin function from Py2.x was resurrected. It provides a concise, readable alternative to using anabstract base classin an expression likeisinstance(x, collections.Callable):>>> callable(max) True >>> callable(20) False
(See
10518.) -
Python's import mechanism can now load modules installed in directories with non-ASCII characters in the path name. This solved an aggravating problem with home directories for users with non-ASCII characters in their usernames.
(Required extensive work by Victor Stinner in
9425.)
New, Improved, and Deprecated Modules
Python's standard library has undergone significant maintenance efforts and quality improvements.
The biggest news for Python 3.2 is that the email package, mailbox module, and !nntplib modules now work correctly with the bytes/text model in Python 3. For the first time, there is correct handling of messages with mixed encodings.
Throughout the standard library, there has been more careful attention to encodings and text versus bytes issues. In particular, interactions with the operating system are now better able to exchange non-ASCII data using the Windows MBCS encoding, locale-aware encodings, or UTF-8.
Another significant win is the addition of substantially better support for SSL connections and security certificates.
In addition, more classes now implement a context manager to support convenient and reliable resource clean-up using a with statement.
The usability of the email package in Python 3 has been mostly fixed by the extensive efforts of R. David Murray. The problem was that emails are typically read and stored in the form of bytes rather than str text, and they may contain multiple encodings within a single email. So, the email package had to be extended to parse and generate email messages in bytes format.
-
New functions
~email.message_from_bytesand~email.message_from_binary_file, and new classes~email.parser.BytesFeedParserand~email.parser.BytesParserallow binary message data to be parsed into model objects. -
Given bytes input to the model,
~email.message.Message.get_payloadwill by default decode a message body that has aContent-Transfer-Encodingof 8bit using the charset specified in the MIME headers and return the resulting string. -
Given bytes input to the model,
~email.generator.Generatorwill convert message bodies that have aContent-Transfer-Encodingof 8bit to instead have a 7bitContent-Transfer-Encoding.Headers with unencoded non-ASCII bytes are deemed to be
2047-encoded using the unknown-8bit character set. -
A new class
~email.generator.BytesGeneratorproduces bytes as output, preserving any unchanged non-ASCII data that was present in the input used to build the model, including message bodies with aContent-Transfer-Encodingof 8bit. -
The
smtplib~smtplib.SMTPclass now accepts a byte string for the msg argument to the~smtplib.SMTP.sendmailmethod, and a new method,~smtplib.SMTP.send_messageaccepts a~email.message.Messageobject and can optionally obtain the from_addr and to_addrs addresses directly from the object.
(Proposed and implemented by R. David Murray, 4661 and 10321.)
elementtree
The xml.etree.ElementTree package and its !xml.etree.cElementTree counterpart have been updated to version 1.3.
Several new and useful functions and methods have been added:
xml.etree.ElementTree.fromstringlistwhich builds an XML document from a sequence of fragmentsxml.etree.ElementTree.register_namespacefor registering a global namespace prefixxml.etree.ElementTree.tostringlistfor string representation including all sublistsxml.etree.ElementTree.Element.extendfor appending a sequence of zero or more elementsxml.etree.ElementTree.Element.iterfindsearches an element and subelementsxml.etree.ElementTree.Element.itertextcreates a text iterator over an element and its subelementsxml.etree.ElementTree.TreeBuilder.endcloses the current elementxml.etree.ElementTree.TreeBuilder.doctypehandles a doctype declaration
Two methods have been deprecated:
!xml.etree.ElementTree.getchildrenuselist(elem)instead.!xml.etree.ElementTree.getiteratoruseElement.iterinstead.
For details of the update, see Introducing ElementTree on Fredrik Lundh's website.
(Contributed by Florent Xicluna and Fredrik Lundh, 6472.)
functools
-
The
functoolsmodule includes a new decorator for caching function calls.functools.lru_cachecan save repeated queries to an external resource whenever the results are expected to be the same.For example, adding a caching decorator to a database query function can save database accesses for popular searches:
>>> import functools >>> @functools.lru_cache(maxsize=300) ... def get_phone_number(name): ... c = conn.cursor() ... c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,)) ... return c.fetchone()[0]
>>> for name in user_requests: # doctest: +SKIP ... get_phone_number(name) # cached lookup
To help with choosing an effective cache size, the wrapped function is instrumented for tracking cache statistics:
>>> get_phone_number.cache_info() # doctest: +SKIP CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)
If the phonelist table gets updated, the outdated contents of the cache can be cleared with:
>>> get_phone_number.cache_clear()
(Contributed by Raymond Hettinger and incorporating design ideas from Jim Baker, Miki Tebeka, and Nick Coghlan; see recipe 498245, recipe 577479,
10586, and10593.) -
The
functools.wrapsdecorator now adds a__wrapped__attribute pointing to the original callable function. This allows wrapped functions to be introspected. It also copies~function.__annotations__if defined. And now it also gracefully skips over missing attributes such as~function.__doc__which might not be defined for the wrapped callable.In the above example, the cache can be removed by recovering the original function:
>>> get_phone_number = get_phone_number.__wrapped__ # uncached function
(By Nick Coghlan and Terrence Cole;
9567,3445, and8814.) -
To help write classes with rich comparison methods, a new decorator
functools.total_orderingwill use existing equality and inequality methods to fill in the remaining methods.For example, supplying __eq__ and __lt__ will enable
~functools.total_orderingto fill-in __le__, __gt__ and __ge__:@total_ordering class Student: def __eq__(self, other): return ((self.lastname.lower(), self.firstname.lower()) == (other.lastname.lower(), other.firstname.lower())) def __lt__(self, other): return ((self.lastname.lower(), self.firstname.lower()) < (other.lastname.lower(), other.firstname.lower()))With the total_ordering decorator, the remaining comparison methods are filled in automatically.
(Contributed by Raymond Hettinger.)
-
To aid in porting programs from Python 2, the
functools.cmp_to_keyfunction converts an old-style comparison function to modernkey function:>>> # locale-aware sort order >>> sorted(iterable, key=cmp_to_key(locale.strcoll)) # doctest: +SKIP
For sorting examples and a brief sorting tutorial, see the Sorting HowTo tutorial.
(Contributed by Raymond Hettinger.)
itertools
-
The
itertoolsmodule has a new~itertools.accumulatefunction modeled on APL's scan operator and Numpy's accumulate function:>>> from itertools import accumulate >>> list(accumulate([8, 2, 50])) [8, 10, 60]
>>> prob_dist = [0.1, 0.4, 0.2, 0.3] >>> list(accumulate(prob_dist)) # cumulative probability distribution [0.1, 0.5, 0.7, 1.0]
For an example using
~itertools.accumulate, see theexamples for the random module <random-examples>.(Contributed by Raymond Hettinger and incorporating design suggestions from Mark Dickinson.)
collections
-
The
collections.Counterclass now has two forms of in-place subtraction, the existing -= operator for saturating subtraction and the new~collections.Counter.subtractmethod for regular subtraction. The former is suitable for multisets which only have positive counts, and the latter is more suitable for use cases that allow negative counts:>>> from collections import Counter >>> tally = Counter(dogs=5, cats=3) >>> tally -= Counter(dogs=2, cats=8) # saturating subtraction >>> tally Counter({'dogs': 3})
>>> tally = Counter(dogs=5, cats=3) >>> tally.subtract(dogs=2, cats=8) # regular subtraction >>> tally Counter({'dogs': 3, 'cats': -5})
(Contributed by Raymond Hettinger.)
-
The
collections.OrderedDictclass has a new method~collections.OrderedDict.move_to_endwhich takes an existing key and moves it to either the first or last position in the ordered sequence.The default is to move an item to the last position. This is equivalent of renewing an entry with
od[k] = od.pop(k).A fast move-to-end operation is useful for resequencing entries. For example, an ordered dictionary can be used to track order of access by aging entries from the oldest to the most recently accessed.
>>> from collections import OrderedDict >>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e']) >>> list(d) ['a', 'b', 'X', 'd', 'e'] >>> d.move_to_end('X') >>> list(d) ['a', 'b', 'd', 'e', 'X']
(Contributed by Raymond Hettinger.)
-
The
collections.dequeclass grew two new methods~collections.deque.countand~collections.deque.reversethat make them more substitutable forlistobjects:>>> from collections import deque >>> d = deque('simsalabim') >>> d.count('s') 2 >>> d.reverse() >>> d deque(['m', 'i', 'b', 'a', 'l', 'a', 's', 'm', 'i', 's'])
(Contributed by Raymond Hettinger.)
threading
The threading module has a new ~threading.Barrier synchronization class for making multiple threads wait until all of them have reached a common barrier point. Barriers are useful for making sure that a task with multiple preconditions does not run until all of the predecessor tasks are complete.
Barriers can work with an arbitrary number of threads. This is a generalization of a Rendezvous which is defined for only two threads.
Implemented as a two-phase cyclic barrier, ~threading.Barrier objects are suitable for use in loops. The separate filling and draining phases assure that all threads get released (drained) before any one of them can loop back and re-enter the barrier. The barrier fully resets after each cycle.
Example of using barriers:
from threading import Barrier, Thread
def get_votes(site):
ballots = conduct_election(site)
all_polls_closed.wait() # do not count until all polls are closed
totals = summarize(ballots)
publish(site, totals)
all_polls_closed = Barrier(len(sites))
for site in sites:
Thread(target=get_votes, args=(site,)).start()
In this example, the barrier enforces a rule that votes cannot be counted at any polling site until all polls are closed. Notice how a solution with a barrier is similar to one with threading.Thread.join, but the threads stay alive and continue to do work (summarizing ballots) after the barrier point is crossed.
If any of the predecessor tasks can hang or be delayed, a barrier can be created with an optional timeout parameter. Then if the timeout period elapses before all the predecessor tasks reach the barrier point, all waiting threads are released and a ~threading.BrokenBarrierError exception is raised:
def get_votes(site):
ballots = conduct_election(site)
try:
all_polls_closed.wait(timeout=midnight - time.now())
except BrokenBarrierError:
lockbox = seal_ballots(ballots)
queue.put(lockbox)
else:
totals = summarize(ballots)
publish(site, totals)
In this example, the barrier enforces a more robust rule. If some election sites do not finish before midnight, the barrier times-out and the ballots are sealed and deposited in a queue for later handling.
See Barrier Synchronization Patterns for more examples of how barriers can be used in parallel computing. Also, there is a simple but thorough explanation of barriers in The Little Book of Semaphores, section 3.6.
(Contributed by Kristján Valur Jónsson with an API review by Jeffrey Yasskin in 8777.)
datetime and time
-
The
datetimemodule has a new type~datetime.timezonethat implements the~datetime.tzinfointerface by returning a fixed UTC offset and timezone name. This makes it easier to create timezone-aware datetime objects:>>> import datetime as dt >>> dt.datetime.now(dt.timezone.utc) datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc) >>> dt.datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z") datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc) -
Also,
~datetime.timedeltaobjects can now be multiplied byfloatand divided byfloatandintobjects. And~datetime.timedeltaobjects can now divide one another. -
The
datetime.date.strftimemethod is no longer restricted to years after 1900. The new supported year range is from 1000 to 9999 inclusive. -
Whenever a two-digit year is used in a time tuple, the interpretation has been governed by
!time.accept2dyear. The default isTruewhich means that for a two-digit year, the century is guessed according to the POSIX rules governing the%ystrptime format.Starting with Py3.2, use of the century guessing heuristic will emit a
DeprecationWarning. Instead, it is recommended that!time.accept2dyearbe set toFalseso that large date ranges can be used without guesswork:>>> import time, warnings >>> warnings.resetwarnings() # remove the default warning filters >>> time.accept2dyear = True # guess whether 11 means 11 or 2011 >>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0)) Warning (from warnings module): ... DeprecationWarning: Century info guessed for a 2-digit year. 'Fri Jan 1 12:34:56 2011' >>> time.accept2dyear = False # use the full range of allowable dates >>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0)) 'Fri Jan 1 12:34:56 11'Several functions now have significantly expanded date ranges. When
!time.accept2dyearis false, thetime.asctimefunction will accept any year that fits in a C int, while thetime.mktimeandtime.strftimefunctions will accept the full range supported by the corresponding operating system functions.
(Contributed by Alexander Belopolsky and Victor Stinner in 1289118, 5094, 6641, 2706, 1777412, 8013, and 10827.)
math
The math module has been updated with six new functions inspired by the C99 standard.
The ~math.isfinite function provides a reliable and fast way to detect special values. It returns True for regular numbers and False for Nan or Infinity:
>>> from math import isfinite >>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))] [True, True, False, False]
The ~math.expm1 function computes e**x-1 for small values of x without incurring the loss of precision that usually accompanies the subtraction of nearly equal quantities:
>>> from math import expm1 >>> expm1(0.013671875) # more accurate way to compute e**x-1 for a small x 0.013765762467652909
The ~math.erf function computes a probability integral or Gaussian error function. The complementary error function, ~math.erfc, is 1 - erf(x):
>>> from math import erf, erfc, sqrt >>> erf(1.0/sqrt(2.0)) # portion of normal distribution within 1 standard deviation 0.682689492137086 >>> erfc(1.0/sqrt(2.0)) # portion of normal distribution outside 1 standard deviation 0.31731050786291404 >>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0)) 1.0
The ~math.gamma function is a continuous extension of the factorial function. See https://en.wikipedia.org/wiki/Gamma_function for details. Because the function is related to factorials, it grows large even for small values of x, so there is also a ~math.lgamma function for computing the natural logarithm of the gamma function:
>>> from math import gamma, lgamma >>> gamma(7.0) # six factorial 720.0 >>> lgamma(801.0) # log(800 factorial) 4551.950730698041
(Contributed by Mark Dickinson.)
abc
The abc module now supports ~abc.abstractclassmethod and ~abc.abstractstaticmethod.
These tools make it possible to define an abstract base class that requires a particular classmethod or staticmethod to be implemented:
class Temperature(metaclass=abc.ABCMeta):
@abc.abstractclassmethod
def from_fahrenheit(cls, t):
...
@abc.abstractclassmethod
def from_celsius(cls, t):
...
(Patch submitted by Daniel Urban; 5867.)
io
The io.BytesIO has a new method, ~io.BytesIO.getbuffer, which provides functionality similar to memoryview. It creates an editable view of the data without making a copy. The buffer's random access and support for slice notation are well-suited to in-place editing:
>>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11
>>> def change_location(buffer, record_number, location):
... start = record_number * REC_LEN + LOC_START
... buffer[start: start+LOC_LEN] = location
>>> import io
>>> byte_stream = io.BytesIO(
... b'G3805 storeroom Main chassis '
... b'X7899 shipping Reserve cog '
... b'L6988 receiving Primary sprocket'
... )
>>> buffer = byte_stream.getbuffer()
>>> change_location(buffer, 1, b'warehouse ')
>>> change_location(buffer, 0, b'showroom ')
>>> print(byte_stream.getvalue())
b'G3805 showroom Main chassis '
b'X7899 warehouse Reserve cog '
b'L6988 receiving Primary sprocket'
(Contributed by Antoine Pitrou in 5506.)
reprlib
When writing a ~object.__repr__ method for a custom container, it is easy to forget to handle the case where a member refers back to the container itself. Python's builtin objects such as list and set handle self-reference by displaying "..." in the recursive part of the representation string.
To help write such ~object.__repr__ methods, the reprlib module has a new decorator, ~reprlib.recursive_repr, for detecting recursive calls to !__repr__ and substituting a placeholder string instead:
>>> class MyList(list):
... @recursive_repr()
... def __repr__(self):
... return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
(Contributed by Raymond Hettinger in 9826 and 9840.)
logging
In addition to dictionary-based configuration described above, the logging package has many other improvements.
The logging documentation has been augmented by a basic tutorial <logging-basic-tutorial>, an advanced tutorial <logging-advanced-tutorial>, and a cookbook <logging-cookbook> of logging recipes. These documents are the fastest way to learn about logging.
The logging.basicConfig set-up function gained a style argument to support three different types of string formatting. It defaults to "%" for traditional %-formatting, can be set to "{" for the new str.format style, or can be set to "$" for the shell-style formatting provided by string.Template. The following three configurations are equivalent:
>>> from logging import basicConfig
>>> basicConfig(style='%', format="%(name)s -> %(levelname)s: %(message)s")
>>> basicConfig(style='{', format="{name} -> {levelname} {message}")
>>> basicConfig(style='$', format="$name -> $levelname: $message")
If no configuration is set-up before a logging event occurs, there is now a default configuration using a ~logging.StreamHandler directed to sys.stderr for events of WARNING level or higher. Formerly, an event occurring before a configuration was set-up would either raise an exception or silently drop the event depending on the value of logging.raiseExceptions. The new default handler is stored in logging.lastResort.
The use of filters has been simplified. Instead of creating a ~logging.Filter object, the predicate can be any Python callable that returns True or False.
There were a number of other improvements that add flexibility and simplify configuration. See the module documentation for a full listing of changes in Python 3.2.
csv
The csv module now supports a new dialect, ~csv.unix_dialect, which applies quoting for all fields and a traditional Unix style with '\n' as the line terminator. The registered dialect name is unix.
The csv.DictWriter has a new method, ~csv.DictWriter.writeheader for writing-out an initial row to document the field names:
>>> import csv, sys
>>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')
>>> w.writeheader()
"name","dept"
>>> w.writerows([
... {'name': 'tom', 'dept': 'accounting'},
... {'name': 'susan', 'dept': 'Salesl'}])
"tom","accounting"
"susan","sales"
(New dialect suggested by Jay Talbot in 5975, and the new method suggested by Ed Abraham in 1537721.)
contextlib
There is a new and slightly mind-blowing tool ~contextlib.ContextDecorator that is helpful for creating a context manager that does double duty as a function decorator.
As a convenience, this new functionality is used by ~contextlib.contextmanager so that no extra effort is needed to support both roles.
The basic idea is that both context managers and function decorators can be used for pre-action and post-action wrappers. Context managers wrap a group of statements using a with statement, and function decorators wrap a group of statements enclosed in a function. So, occasionally there is a need to write a pre-action or post-action wrapper that can be used in either role.
For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, the ~contextlib.contextmanager provides both capabilities in a single definition:
from contextlib import contextmanager
import logging
logging.basicConfig(level=logging.INFO)
@contextmanager
def track_entry_and_exit(name):
logging.info('Entering: %s', name)
yield
logging.info('Exiting: %s', name)
Formerly, this would have only been usable as a context manager:
with track_entry_and_exit('widget loader'):
print('Some time consuming activity goes here')
load_widget()
Now, it can be used as a decorator as well:
@track_entry_and_exit('widget loader')
def activity():
print('Some time consuming activity goes here')
load_widget()
Trying to fulfill two roles at once places some limitations on the technique. Context managers normally have the flexibility to return an argument usable by a with statement, but there is no parallel for function decorators.
In the above example, there is not a clean way for the track_entry_and_exit context manager to return a logging instance for use in the body of enclosed statements.
(Contributed by Michael Foord in 9110.)
decimal and fractions
Mark Dickinson crafted an elegant and efficient scheme for assuring that different numeric datatypes will have the same hash value whenever their actual values are equal (8188):
assert hash(Fraction(3, 2)) == hash(1.5) == \
hash(Decimal("1.5")) == hash(complex(1.5, 0))
Some of the hashing details are exposed through a new attribute, sys.hash_info, which describes the bit width of the hash value, the prime modulus, the hash values for infinity and nan, and the multiplier used for the imaginary part of a number:
>>> sys.hash_info # doctest: +SKIP sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)
An early decision to limit the interoperability of various numeric types has been relaxed. It is still unsupported (and ill-advised) to have implicit mixing in arithmetic expressions such as Decimal('1.1') + float('1.1') because the latter loses information in the process of constructing the binary float. However, since existing floating-point value can be converted losslessly to either a decimal or rational representation, it makes sense to add them to the constructor and to support mixed-type comparisons.
- The
decimal.Decimalconstructor now acceptsfloatobjects directly so there in no longer a need to use the~decimal.Decimal.from_floatmethod (8257). - Mixed type comparisons are now fully supported so that
~decimal.Decimalobjects can be directly compared withfloatandfractions.Fraction(2531and8188).
Similar changes were made to fractions.Fraction so that the ~fractions.Fraction.from_float and ~fractions.Fraction.from_decimal methods are no longer needed (8294):
>>> from decimal import Decimal >>> from fractions import Fraction >>> Decimal(1.1) Decimal('1.100000000000000088817841970012523233890533447265625') >>> Fraction(1.1) Fraction(2476979795053773, 2251799813685248)
Another useful change for the decimal module is that the Context.clamp <decimal.Context.clamp> attribute is now public. This is useful in creating contexts that correspond to the decimal interchange formats specified in IEEE 754 (see 8540).
(Contributed by Mark Dickinson and Raymond Hettinger.)
ftp
The ftplib.FTP class now supports the context management protocol to unconditionally consume socket.error exceptions and to close the FTP connection when done:
>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
... ftp.login()
... ftp.dir()
...
'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .
dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 ..
dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS
dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora
Other file-like objects such as mmap.mmap and fileinput.input also grew auto-closing context managers:
with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
for line in f:
process(line)
(Contributed by Tarek Ziadé and Giampaolo Rodolà in 4972, and by Georg Brandl in 8046 and 1286.)
The ~ftplib.FTP_TLS class now accepts a context parameter, which is a ssl.SSLContext object allowing bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure.
(Contributed by Giampaolo Rodolà; 8806.)
popen
The os.popen and subprocess.Popen functions now support with statements for auto-closing of the file descriptors.
(Contributed by Antoine Pitrou and Brian Curtin in 7461 and 10554.)
select
The select module now exposes a new, constant attribute, ~select.PIPE_BUF, which gives the minimum number of bytes which are guaranteed not to block when select.select says a pipe is ready for writing.
>>> import select >>> select.PIPE_BUF # doctest: +SKIP 512
(Available on Unix systems. Patch by Sébastien Sablé in 9862)
gzip and zipfile
gzip.GzipFile now implements the io.BufferedIOBase abstract base class (except for truncate()). It also has a ~gzip.GzipFile.peek method and supports unseekable as well as zero-padded file objects.
The gzip module also gains the ~gzip.compress and ~gzip.decompress functions for easier in-memory compression and decompression. Keep in mind that text needs to be encoded as bytes before compressing and decompressing:
>>> import gzip >>> s = 'Three shall be the number thou shalt count, ' >>> s += 'and the number of the counting shall be three' >>> b = s.encode() # convert to utf-8 >>> len(b) 89 >>> c = gzip.compress(b) >>> len(c) 77 >>> gzip.decompress(c).decode()[:42] # decompress and convert to text 'Three shall be the number thou shalt count'
(Contributed by Anand B. Pillai in 3488; and by Antoine Pitrou, Nir Aides and Brian Curtin in 9962, 1675951, 7471 and 2846.)
Also, the zipfile.ZipExtFile <zipfile.ZipFile.open> class was reworked internally to represent files stored inside an archive. The new implementation is significantly faster and can be wrapped in an io.BufferedReader object for more speedups. It also solves an issue where interleaved calls to read and readline gave the wrong results.
(Patch submitted by Nir Aides in 7610.)
tarfile
The ~tarfile.TarFile class can now be used as a context manager. In addition, its ~tarfile.TarFile.add method has a new option, filter, that controls which files are added to the archive and allows the file metadata to be edited.
The new filter option replaces the older, less flexible exclude parameter which is now deprecated. If specified, the optional filter parameter needs to be a keyword argument. The user-supplied filter function accepts a ~tarfile.TarInfo object and returns an updated ~tarfile.TarInfo object, or if it wants the file to be excluded, the function can return None:
>>> import tarfile, glob
>>> def myfilter(tarinfo):
... if tarinfo.isfile(): # only save real files
... tarinfo.uname = 'monty' # redact the user name
... return tarinfo
>>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
... for filename in glob.glob('*.txt'):
... tf.add(filename, filter=myfilter)
... tf.list()
-rw-r--r-- monty/501 902 2011-01-26 17:59:11 annotations.txt
-rw-r--r-- monty/501 123 2011-01-26 17:59:11 general_questions.txt
-rw-r--r-- monty/501 3514 2011-01-26 17:59:11 prion.txt
-rw-r--r-- monty/501 124 2011-01-26 17:59:11 py_todo.txt
-rw-r--r-- monty/501 1399 2011-01-26 17:59:11 semaphore_notes.txt
(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in 6856.)
hashlib
The hashlib module has two new constant attributes listing the hashing algorithms guaranteed to be present in all implementations and those available on the current implementation:
>>> import hashlib
>>> hashlib.algorithms_guaranteed
{'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'}
>>> hashlib.algorithms_available
{'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', 'sha256',
'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',
'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',
'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'}
(Suggested by Carl Chenet in 7418.)
ast
The ast module has a wonderful a general-purpose tool for safely evaluating expression strings using the Python literal syntax. The ast.literal_eval function serves as a secure alternative to the builtin eval function which is easily abused. Python 3.2 adds bytes and set literals to the list of supported types: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
>>> from ast import literal_eval
>>> request = "{'req': 3, 'func': 'pow', 'args': (2, 0.5)}"
>>> literal_eval(request)
{'args': (2, 0.5), 'req': 3, 'func': 'pow'}
>>> request = "os.system('do something harmful')"
>>> literal_eval(request)
Traceback (most recent call last):
...
ValueError: malformed node or string: <_ast.Call object at 0x101739a10>
(Implemented by Benjamin Peterson and Georg Brandl.)
os
Different operating systems use various encodings for filenames and environment variables. The os module provides two new functions, ~os.fsencode and ~os.fsdecode, for encoding and decoding filenames:
>>> import os >>> filename = 'Sehenswürdigkeiten' >>> os.fsencode(filename) b'Sehenswxc3xbcrdigkeiten'
Some operating systems allow direct access to encoded bytes in the environment. If so, the os.supports_bytes_environ constant will be true.
For direct access to encoded environment variables (if available), use the new os.getenvb function or use os.environb which is a bytes version of os.environ.
(Contributed by Victor Stinner.)
shutil
The shutil.copytree function has two new options:
- ignore_dangling_symlinks: when
symlinks=Falseso that the function copies a file pointed to by a symlink, not the symlink itself. This option will silence the error raised if the file doesn't exist. - copy_function: is a callable that will be used to copy files.
shutil.copy2is used by default.
(Contributed by Tarek Ziadé.)
In addition, the shutil module now supports archiving operations <archiving-operations> for zipfiles, uncompressed tarfiles, gzipped tarfiles, and bzipped tarfiles. And there are functions for registering additional archiving file formats (such as xz compressed tarfiles or custom formats).
The principal functions are ~shutil.make_archive and ~shutil.unpack_archive. By default, both operate on the current directory (which can be set by os.chdir) and on any sub-directories. The archive filename needs to be specified with a full pathname. The archiving step is non-destructive (the original files are left unchanged).
>>> import shutil, pprint
>>> os.chdir('mydata') # change to the source directory
>>> f = shutil.make_archive('/var/backup/mydata',
... 'zip') # archive the current directory
>>> f # show the name of archive
'/var/backup/mydata.zip'
>>> os.chdir('tmp') # change to an unpacking
>>> shutil.unpack_archive('/var/backup/mydata.zip') # recover the data
>>> pprint.pprint(shutil.get_archive_formats()) # display known formats
[('bztar', "bzip2'ed tar-file"),
('gztar', "gzip'ed tar-file"),
('tar', 'uncompressed tar file'),
('zip', 'ZIP file')]
>>> shutil.register_archive_format( # register a new archive format
... name='xz',
... function=xz.compress, # callable archiving function
... extra_args=[('level', 8)], # arguments to the function
... description='xz compression'
... )
(Contributed by Tarek Ziadé.)
sqlite3
The sqlite3 module was updated to pysqlite version 2.6.0. It has two new capabilities.
- The
!sqlite3.Connection.in_transitattribute is true if there is an active transaction for uncommitted changes. - The
sqlite3.Connection.enable_load_extensionandsqlite3.Connection.load_extensionmethods allows you to load SQLite extensions from ".so" files. One well-known extension is the fulltext-search extension distributed with SQLite.
(Contributed by R. David Murray and Shashwat Anand; 8845.)
html
A new html module was introduced with only a single function, ~html.escape, which is used for escaping reserved characters from HTML markup:
>>> import html >>> html.escape('x > 2 && x < 7') 'x > 2 && x < 7'
socket
The socket module has two new improvements.
- Socket objects now have a
~socket.socket.detachmethod which puts the socket into closed state without actually closing the underlying file descriptor. The latter can then be reused for other purposes. (Added by Antoine Pitrou;8524.) socket.create_connectionnow supports the context management protocol to unconditionally consumesocket.errorexceptions and to close the socket when done. (Contributed by Giampaolo Rodolà;9794.)
ssl
The ssl module added a number of features to satisfy common requirements for secure (encrypted, authenticated) internet connections:
- A new class,
~ssl.SSLContext, serves as a container for persistent SSL data, such as protocol settings, certificates, private keys, and various other options. It includes a~ssl.SSLContext.wrap_socketfor creating an SSL socket from an SSL context. - A new function,
!ssl.match_hostname, supports server identity verification for higher-level protocols by implementing the rules of HTTPS (from2818) which are also suitable for other protocols. - The
ssl.wrap_socket() <ssl.SSLContext.wrap_socket>constructor function now takes a ciphers argument. The ciphers string lists the allowed encryption algorithms using the format described in the OpenSSL documentation. - When linked against recent versions of OpenSSL, the
sslmodule now supports the Server Name Indication extension to the TLS protocol, allowing multiple "virtual hosts" using different certificates on a single IP port. This extension is only supported in client mode, and is activated by passing the server_hostname argument tossl.SSLContext.wrap_socket. - Various options have been added to the
sslmodule, such as~ssl.OP_NO_SSLv2which disables the insecure and obsolete SSLv2 protocol. - The extension now loads all the OpenSSL ciphers and digest algorithms. If some SSL certificates cannot be verified, they are reported as an "unknown algorithm" error.
- The version of OpenSSL being used is now accessible using the module attributes
ssl.OPENSSL_VERSION(a string),ssl.OPENSSL_VERSION_INFO(a 5-tuple), andssl.OPENSSL_VERSION_NUMBER(an integer).
(Contributed by Antoine Pitrou in 8850, 1589, 8322, 5639, 4870, 8484, and 8321.)
nntp
The !nntplib module has a revamped implementation with better bytes and text semantics as well as more practical APIs. These improvements break compatibility with the nntplib version in Python 3.1, which was partly dysfunctional in itself.
Support for secure connections through both implicit (using !nntplib.NNTP_SSL) and explicit (using !nntplib.NNTP.starttls) TLS has also been added.
(Contributed by Antoine Pitrou in 9360 and Andrew Vant in 1926.)
certificates
http.client.HTTPSConnection, urllib.request.HTTPSHandler and urllib.request.urlopen now take optional arguments to allow for server certificate checking against a set of Certificate Authorities, as recommended in public uses of HTTPS.
(Added by Antoine Pitrou, 9003.)
imaplib
Support for explicit TLS on standard IMAP4 connections has been added through the new imaplib.IMAP4.starttls method.
(Contributed by Lorenzo M. Catucci and Antoine Pitrou, 4471.)
http.client
There were a number of small API improvements in the http.client module. The old-style HTTP 0.9 simple responses are no longer supported and the strict parameter is deprecated in all classes.
The ~http.client.HTTPConnection and ~http.client.HTTPSConnection classes now have a source_address parameter for a (host, port) tuple indicating where the HTTP connection is made from.
Support for certificate checking and HTTPS virtual hosts were added to ~http.client.HTTPSConnection.
The ~http.client.HTTPConnection.request method on connection objects allowed an optional body argument so that a file object could be used to supply the content of the request. Conveniently, the body argument now also accepts an iterable object so long as it includes an explicit Content-Length header. This extended interface is much more flexible than before.
To establish an HTTPS connection through a proxy server, there is a new ~http.client.HTTPConnection.set_tunnel method that sets the host and port for HTTP Connect tunneling.
To match the behavior of http.server, the HTTP client library now also encodes headers with ISO-8859-1 (Latin-1) encoding. It was already doing that for incoming headers, so now the behavior is consistent for both incoming and outgoing traffic. (See work by Armin Ronacher in 10980.)
unittest
The unittest module has a number of improvements supporting test discovery for packages, easier experimentation at the interactive prompt, new testcase methods, improved diagnostic messages for test failures, and better method names.
-
The command-line call
python -m unittestcan now accept file paths instead of module names for running specific tests (10620). The new test discovery can find tests within packages, locating any test importable from the top-level directory. The top-level directory can be specified with the-toption, a pattern for matching files with-p, and a directory to start discovery with-s:$ python -m unittest discover -s my_proj_dir -p _test.py(Contributed by Michael Foord.)
-
Experimentation at the interactive prompt is now easier because the
unittest.TestCaseclass can now be instantiated without arguments:>>> from unittest import TestCase >>> TestCase().assertEqual(pow(2, 3), 8)
(Contributed by Michael Foord.)
-
The
unittestmodule has two new methods,~unittest.TestCase.assertWarnsand~unittest.TestCase.assertWarnsRegexto verify that a given warning type is triggered by the code under test:with self.assertWarns(DeprecationWarning): legacy_function('XYZ')(Contributed by Antoine Pitrou,
9754.)Another new method,
~unittest.TestCase.assertCountEqualis used to compare two iterables to determine if their element counts are equal (whether the same elements are present with the same number of occurrences regardless of order):def test_anagram(self): self.assertCountEqual('algorithm', 'logarithm')(Contributed by Raymond Hettinger.)
-
A principal feature of the unittest module is an effort to produce meaningful diagnostics when a test fails. When possible, the failure is recorded along with a diff of the output. This is especially helpful for analyzing log files of failed test runs. However, since diffs can sometime be voluminous, there is a new
~unittest.TestCase.maxDiffattribute that sets maximum length of diffs displayed. -
In addition, the method names in the module have undergone a number of clean-ups.
For example,
~unittest.TestCase.assertRegexis the new name for!assertRegexpMatcheswhich was misnamed because the test usesre.search, notre.match. Other methods using regular expressions are now named using short form "Regex" in preference to "Regexp" -- this matches the names used in other unittest implementations, matches Python's old name for theremodule, and it has unambiguous camel-casing.(Contributed by Raymond Hettinger and implemented by Ezio Melotti.)
-
To improve consistency, some long-standing method aliases are being deprecated in favor of the preferred names:
Old Name Preferred Name !assert_.assertTrue!assertEquals.assertEqual!assertNotEquals.assertNotEqual!assertAlmostEquals.assertAlmostEqual!assertNotAlmostEquals.assertNotAlmostEqualLikewise, the
TestCase.fail*methods deprecated in Python 3.1 are expected to be removed in Python 3.3.(Contributed by Ezio Melotti;
9424.) -
The
!assertDictContainsSubsetmethod was deprecated because it was misimplemented with the arguments in the wrong order. This created hard-to-debug optical illusions where tests likeTestCase().assertDictContainsSubset({'a':1, 'b':2}, {'a':1})would fail.(Contributed by Raymond Hettinger.)
random
The integer methods in the random module now do a better job of producing uniform distributions. Previously, they computed selections with int(n*random()) which had a slight bias whenever n was not a power of two. Now, multiple selections are made from a range up to the next power of two and a selection is kept only when it falls within the range 0 <= x < n. The functions and methods affected are ~random.randrange, ~random.randint, ~random.choice, ~random.shuffle and ~random.sample.
(Contributed by Raymond Hettinger; 9025.)
poplib
~poplib.POP3_SSL class now accepts a context parameter, which is a ssl.SSLContext object allowing bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure.
(Contributed by Giampaolo Rodolà; 8807.)
asyncore
!asyncore.dispatcher now provides a !handle_accepted method returning a (sock, addr) pair which is called when a connection has actually been established with a new remote endpoint. This is supposed to be used as a replacement for old !handle_accept and avoids the user to call !accept directly.
(Contributed by Giampaolo Rodolà; 6706.)
tempfile
The tempfile module has a new context manager, ~tempfile.TemporaryDirectory which provides easy deterministic cleanup of temporary directories:
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary dir:', tmpdirname)
(Contributed by Neil Schemenauer and Nick Coghlan; 5178.)
inspect
-
The
inspectmodule has a new function~inspect.getgeneratorstateto easily identify the current state of a generator-iterator:>>> from inspect import getgeneratorstate >>> def gen(): ... yield 'demo' ... >>> g = gen() >>> getgeneratorstate(g) 'GEN_CREATED' >>> next(g) 'demo' >>> getgeneratorstate(g) 'GEN_SUSPENDED' >>> next(g, None) >>> getgeneratorstate(g) 'GEN_CLOSED'(Contributed by Rodolpho Eckhardt and Nick Coghlan,
10220.) -
To support lookups without the possibility of activating a dynamic attribute, the
inspectmodule has a new function,~inspect.getattr_static. Unlikehasattr, this is a true read-only search, guaranteed not to change state while it is searching:>>> class A: ... @property ... def f(self): ... print('Running') ... return 10 ... >>> a = A() >>> getattr(a, 'f') Running 10 >>> inspect.getattr_static(a, 'f') <property object at 0x1022bd788>
(Contributed by Michael Foord.)
pydoc
The pydoc module now provides a much-improved web server interface, as well as a new command-line option -b to automatically open a browser window to display that server:
$ pydoc3.2 -b
(Contributed by Ron Adam; 2001.)
dis
The dis module gained two new functions for inspecting code, ~dis.code_info and ~dis.show_code. Both provide detailed code object information for the supplied function, method, source code string or code object. The former returns a string and the latter prints it:
>>> import dis, random
>>> dis.show_code(random.choice)
Name: choice
Filename: /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/random.py
Argument count: 2
Kw-only arguments: 0
Number of locals: 3
Stack size: 11
Flags: OPTIMIZED, NEWLOCALS, NOFREE
Constants:
0: 'Choose a random element from a non-empty sequence.'
1: 'Cannot choose from an empty sequence'
Names:
0: _randbelow
1: len
2: ValueError
3: IndexError
Variable names:
0: self
1: seq
2: i
In addition, the ~dis.dis function now accepts string arguments so that the common idiom dis(compile(s, '', 'eval')) can be shortened to dis(s):
>>> dis('3*x+1 if x%2==1 else x//2')
1 0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (2)
6 BINARY_MODULO
7 LOAD_CONST 1 (1)
10 COMPARE_OP 2 (==)
13 POP_JUMP_IF_FALSE 28
16 LOAD_CONST 2 (3)
19 LOAD_NAME 0 (x)
22 BINARY_MULTIPLY
23 LOAD_CONST 1 (1)
26 BINARY_ADD
27 RETURN_VALUE
>> 28 LOAD_NAME 0 (x)
31 LOAD_CONST 0 (2)
34 BINARY_FLOOR_DIVIDE
35 RETURN_VALUE
Taken together, these improvements make it easier to explore how CPython is implemented and to see for yourself what the language syntax does under-the-hood.
(Contributed by Nick Coghlan in 9147.)
dbm
All database modules now support the !get and !setdefault methods.
(Suggested by Ray Allen in 9523.)
ctypes
A new type, ctypes.c_ssize_t represents the C ssize_t datatype.
site
The site module has three new functions useful for reporting on the details of a given Python installation.
~site.getsitepackageslists all global site-packages directories.~site.getuserbasereports on the user's base directory where data can be stored.~site.getusersitepackagesreveals the user-specific site-packages directory path.
>>> import site
>>> site.getsitepackages()
['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',
'/Library/Python/3.2/site-packages']
>>> site.getuserbase()
'/Users/raymondhettinger/Library/Python/3.2'
>>> site.getusersitepackages()
'/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'
Conveniently, some of site's functionality is accessible directly from the command-line:
$ python -m site --user-base
/Users/raymondhettinger/.local
$ python -m site --user-site
/Users/raymondhettinger/.local/lib/python3.2/site-packages
(Contributed by Tarek Ziadé in 6693.)
sysconfig
The new sysconfig module makes it straightforward to discover installation paths and configuration variables that vary across platforms and installations.
The module offers access simple access functions for platform and version information:
~sysconfig.get_platformreturning values like linux-i586 or macosx-10.6-ppc.~sysconfig.get_python_versionreturns a Python version string such as "3.2".
It also provides access to the paths and variables corresponding to one of seven named schemes used by distutils. Those include posix_prefix, posix_home, posix_user, nt, nt_user, os2, os2_home:
~sysconfig.get_pathsmakes a dictionary containing installation paths for the current installation scheme.~sysconfig.get_config_varsreturns a dictionary of platform specific variables.
There is also a convenient command-line interface:
C:\Python32>python -m sysconfig
Platform: "win32"
Python version: "3.2"
Current installation scheme: "nt"
Paths:
data = "C:\Python32"
include = "C:\Python32\Include"
platinclude = "C:\Python32\Include"
platlib = "C:\Python32\Lib\site-packages"
platstdlib = "C:\Python32\Lib"
purelib = "C:\Python32\Lib\site-packages"
scripts = "C:\Python32\Scripts"
stdlib = "C:\Python32\Lib"
Variables:
BINDIR = "C:\Python32"
BINLIBDEST = "C:\Python32\Lib"
EXE = ".exe"
INCLUDEPY = "C:\Python32\Include"
LIBDEST = "C:\Python32\Lib"
SO = ".pyd"
VERSION = "32"
abiflags = ""
base = "C:\Python32"
exec_prefix = "C:\Python32"
platbase = "C:\Python32"
prefix = "C:\Python32"
projectbase = "C:\Python32"
py_version = "3.2"
py_version_nodot = "32"
py_version_short = "3.2"
srcdir = "C:\Python32"
userbase = "C:\Documents and Settings\Raymond\Application Data\Python"
(Moved out of Distutils by Tarek Ziadé.)
pdb
The pdb debugger module gained a number of usability improvements:
pdb.pynow has a-coption that executes commands as given in a.pdbrcscript file.- A
.pdbrcscript file can containcontinueandnextcommands that continue debugging. - The
~pdb.Pdbclass constructor now accepts a nosigint argument. - New commands:
l(list),ll(long list)andsourcefor listing source code. - New commands:
displayandundisplayfor showing or hiding the value of an expression if it has changed. - New command:
interactfor starting an interactive interpreter containing the global and local names found in the current scope. - Breakpoints can be cleared by breakpoint number.
(Contributed by Georg Brandl, Antonio Cuni and Ilya Sandler.)
configparser
The configparser module was modified to improve usability and predictability of the default parser and its supported INI syntax. The old !ConfigParser class was removed in favor of !SafeConfigParser which has in turn been renamed to ~configparser.ConfigParser. Support for inline comments is now turned off by default and section or option duplicates are not allowed in a single configuration source.
Config parsers gained a new API based on the mapping protocol:
>>> parser = ConfigParser()
>>> parser.read_string("""
... [DEFAULT]
... location = upper left
... visible = yes
... editable = no
... color = blue
...
... [main]
... title = Main Menu
... color = green
...
... [options]
... title = Options
... """)
>>> parser['main']['color']
'green'
>>> parser['main']['editable']
'no'
>>> section = parser['options']
>>> section['title']
'Options'
>>> section['title'] = 'Options (editable: %(editable)s)'
>>> section['title']
'Options (editable: no)'
The new API is implemented on top of the classical API, so custom parser subclasses should be able to use it without modifications.
The INI file structure accepted by config parsers can now be customized. Users can specify alternative option/value delimiters and comment prefixes, change the name of the DEFAULT section or switch the interpolation syntax.
There is support for pluggable interpolation including an additional interpolation handler ~configparser.ExtendedInterpolation:
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},
... 'custom': {'prefix': '/usr/local'}})
>>> parser.read_string("""
... [buildout]
... parts =
... zope9
... instance
... find-links =
... ${buildout:directory}/downloads/dist
...
... [zope9]
... recipe = plone.recipe.zope9install
... location = /opt/zope
...
... [instance]
... recipe = plone.recipe.zope9instance
... zope9-location = ${zope9:location}
... zope-conf = ${custom:prefix}/etc/zope.conf
... """)
>>> parser['buildout']['find-links']
'\n/home/ambv/zope9/downloads/dist'
>>> parser['instance']['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance = parser['instance']
>>> instance['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance['zope9-location']
'/opt/zope'
A number of smaller features were also introduced, like support for specifying encoding in read operations, specifying fallback values for get-functions, or reading directly from dictionaries and strings.
(All changes contributed by Łukasz Langa.)
urllib.parse
A number of usability improvements were made for the urllib.parse module.
The ~urllib.parse.urlparse function now supports IPv6 addresses as described in 2732:
>>> import urllib.parse >>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') # doctest: +NORMALIZE_WHITESPACE ParseResult(scheme='http', netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]', path='/foo/', params='', query='', fragment='')
The ~urllib.parse.urldefrag function now returns a named tuple:
>>> r = urllib.parse.urldefrag('http://python.org/about/#target')
>>> r
DefragResult(url='http://python.org/about/', fragment='target')
>>> r[0]
'http://python.org/about/'
>>> r.fragment
'target'
And, the ~urllib.parse.urlencode function is now much more flexible, accepting either a string or bytes type for the query argument. If it is a string, then the safe, encoding, and error parameters are sent to ~urllib.parse.quote_plus for encoding:
>>> urllib.parse.urlencode([
... ('type', 'telenovela'),
... ('name', '¿Dónde Está Elisa?')],
... encoding='latin-1')
'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'
As detailed in parsing-ascii-encoded-bytes, all the urllib.parse functions now accept ASCII-encoded byte strings as input, so long as they are not mixed with regular strings. If ASCII-encoded byte strings are given as parameters, the return types will also be an ASCII-encoded byte strings:
>>> urllib.parse.urlparse(b'http://www.python.org:80/about/') # doctest: +NORMALIZE_WHITESPACE ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80', path=b'/about/', params=b'', query=b'', fragment=b'')
(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in 2987, 5468, and 9873.)
mailbox
Thanks to a concerted effort by R. David Murray, the mailbox module has been fixed for Python 3.2. The challenge was that mailbox had been originally designed with a text interface, but email messages are best represented with bytes because various parts of a message may have different encodings.
The solution harnessed the email package's binary support for parsing arbitrary email messages. In addition, the solution required a number of API changes.
As expected, the ~mailbox.Mailbox.add method for mailbox.Mailbox objects now accepts binary input.
~io.StringIO and text file input are deprecated. Also, string input will fail early if non-ASCII characters are used. Previously it would fail when the email was processed in a later step.
There is also support for binary output. The ~mailbox.Mailbox.get_file method now returns a file in the binary mode (where it used to incorrectly set the file to text-mode). There is also a new ~mailbox.Mailbox.get_bytes method that returns a bytes representation of a message corresponding to a given key.
It is still possible to get non-binary output using the old API's ~mailbox.Mailbox.get_string method, but that approach is not very useful. Instead, it is best to extract messages from a ~mailbox.Message object or to load them from binary input.
(Contributed by R. David Murray, with efforts from Steffen Daode Nurpmeso and an initial patch by Victor Stinner in 9124.)
turtledemo
The demonstration code for the turtle module was moved from the Demo directory to main library. It includes over a dozen sample scripts with lively displays. Being on sys.path, it can now be run directly from the command-line:
$ python -m turtledemo
(Moved from the Demo directory by Alexander Belopolsky in 10199.)
Multi-threading
-
The mechanism for serializing execution of concurrently running Python threads (generally known as the
GILor Global Interpreter Lock) has been rewritten. Among the objectives were more predictable switching intervals and reduced overhead due to lock contention and the number of ensuing system calls. The notion of a "check interval" to allow thread switches has been abandoned and replaced by an absolute duration expressed in seconds. This parameter is tunable throughsys.setswitchinterval. It currently defaults to 5 milliseconds.Additional details about the implementation can be read from a python-dev mailing-list message (however, "priority requests" as exposed in this message have not been kept for inclusion).
(Contributed by Antoine Pitrou.)
-
Regular and recursive locks now accept an optional timeout argument to their
~threading.Lock.acquiremethod. (Contributed by Antoine Pitrou;7316.) -
Similarly,
threading.Semaphore.acquirealso gained a timeout argument. (Contributed by Torsten Landschoff;850728.) -
Regular and recursive lock acquisitions can now be interrupted by signals on platforms using Pthreads. This means that Python programs that deadlock while acquiring locks can be successfully killed by repeatedly sending SIGINT to the process (by pressing
Ctrl+Cin most shells). (Contributed by Reid Kleckner;8844.)
Optimizations
A number of small performance enhancements have been added:
-
Python's peephole optimizer now recognizes patterns such
x in {1, 2, 3}as being a test for membership in a set of constants. The optimizer recasts thesetas afrozensetand stores the pre-built constant.Now that the speed penalty is gone, it is practical to start writing membership tests using set-notation. This style is both semantically clear and operationally fast:
extension = name.rpartition('.')[2] if extension in {'xml', 'html', 'xhtml', 'css'}: handle(name)(Patch and additional tests contributed by Dave Malcolm;
6690). -
Serializing and unserializing data using the
picklemodule is now several times faster.(Contributed by Alexandre Vassalotti, Antoine Pitrou and the Unladen Swallow team in
9410and3873.) -
The Timsort algorithm used in
list.sortandsortednow runs faster and uses less memory when called with akey function. Previously, every element of a list was wrapped with a temporary object that remembered the key value associated with each element. Now, two arrays of keys and values are sorted in parallel. This saves the memory consumed by the sort wrappers, and it saves time lost to delegating comparisons.(Patch by Daniel Stutzbach in
9915.) -
JSON decoding performance is improved and memory consumption is reduced whenever the same string is repeated for multiple keys. Also, JSON encoding now uses the C speedups when the
sort_keysargument is true.(Contributed by Antoine Pitrou in
7451and by Raymond Hettinger and Antoine Pitrou in10314.) -
Recursive locks (created with the
threading.RLockAPI) now benefit from a C implementation which makes them as fast as regular locks, and between 10x and 15x faster than their previous pure Python implementation.(Contributed by Antoine Pitrou;
3001.) -
The fast-search algorithm in stringlib is now used by the
~str.split,~str.rsplit,~str.splitlinesand~str.replacemethods onbytes,bytearrayandstrobjects. Likewise, the algorithm is also used by~str.rfind,~str.rindex,~str.rsplitand~str.rpartition.(Patch by Florent Xicluna in
7622and7462.) -
Integer to string conversions now work two "digits" at a time, reducing the number of division and modulo operations.
(
6713by Gawain Bolton, Mark Dickinson, and Victor Stinner.)
There were several other minor optimizations. Set differencing now runs faster when one operand is much larger than the other (patch by Andress Bennetts in 8685). The !array.repeat method has a faster implementation (1569291 by Alexander Belopolsky). The ~http.server.BaseHTTPRequestHandler has more efficient buffering (3709 by Andrew Schaaf). The operator.attrgetter function has been sped-up (10160 by Christos Georgiou). And ~configparser.ConfigParser loads multi-line arguments a bit faster (7113 by Łukasz Langa).
Unicode
Python has been updated to Unicode 6.0.0. The update to the standard adds over 2,000 new characters including emoji symbols which are important for mobile phones.
In addition, the updated standard has altered the character properties for two Kannada characters (U+0CF1, U+0CF2) and one New Tai Lue numeric character (U+19DA), making the former eligible for use in identifiers while disqualifying the latter. For more information, see Unicode Character Database Changes.
Codecs
Support was added for cp720 Arabic DOS encoding (1616979).
MBCS encoding no longer ignores the error handler argument. In the default strict mode, it raises an UnicodeDecodeError when it encounters an undecodable byte sequence and an UnicodeEncodeError for an unencodable character.
The MBCS codec supports 'strict' and 'ignore' error handlers for decoding, and 'strict' and 'replace' for encoding.
To emulate Python3.1 MBCS encoding, select the 'ignore' handler for decoding and the 'replace' handler for encoding.
On Mac OS X, Python decodes command line arguments with 'utf-8' rather than the locale encoding.
By default, tarfile uses 'utf-8' encoding on Windows (instead of 'mbcs') and the 'surrogateescape' error handler on all operating systems.
Documentation
The documentation continues to be improved.
-
A table of quick links has been added to the top of lengthy sections such as
built-in-funcs. In the case ofitertools, the links are accompanied by tables of cheatsheet-style summaries to provide an overview and memory jog without having to read all of the docs. -
In some cases, the pure Python source code can be a helpful adjunct to the documentation, so now many modules now feature quick links to the latest version of the source code. For example, the
functoolsmodule documentation has a quick link at the top labeled:Source code
Lib/functools.py.(Contributed by Raymond Hettinger; see rationale.)
-
The docs now contain more examples and recipes. In particular,
remodule has an extensive section,re-examples. Likewise, theitertoolsmodule continues to be updated with newitertools-recipes. -
The
datetimemodule now has an auxiliary implementation in pure Python. No functionality was changed. This just provides an easier-to-read alternate implementation.(Contributed by Alexander Belopolsky in
9528.) -
The unmaintained
Demodirectory has been removed. Some demos were integrated into the documentation, some were moved to theTools/demodirectory, and others were removed altogether.(Contributed by Georg Brandl in
7962.)
IDLE
Code Repository
In addition to the existing Subversion code repository at https://svn.python.org there is now a Mercurial repository at [https://hg.python.org/\](https://hg.python.org/) .
After the 3.2 release, there are plans to switch to Mercurial as the primary repository. This distributed version control system should make it easier for members of the community to create and share external changesets. See 385 for details.
To learn to use the new version control system, see the Quick Start or the Guide to Mercurial Workflows.
Build and C API Changes
Changes to Python's build process and to the C API include:
-
The idle, pydoc and 2to3 scripts are now installed with a version-specific suffix on
make altinstall(10679). -
The C functions that access the Unicode Database now accept and return characters from the full Unicode range, even on narrow unicode builds (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and others). A visible difference in Python is that
unicodedata.numericnow returns the correct value for large code points, andreprmay consider more characters as printable.(Reported by Bupjoe Lee and fixed by Amaury Forgeot D'Arc;
5127.) -
Computed gotos are now enabled by default on supported compilers (which are detected by the configure script). They can still be disabled selectively by specifying
--without-computed-gotos.(Contributed by Antoine Pitrou;
9203.) -
The option
--with-wctype-functionswas removed. The built-in unicode database is now used for all functions.(Contributed by Amaury Forgeot D'Arc;
9210.) -
Hash values are now values of a new type,
Py_hash_t, which is defined to be the same size as a pointer. Previously they were of type long, which on some 64-bit operating systems is still only 32 bits long. As a result of this fix,setanddictcan now hold more than2**32entries on builds with 64-bit pointers (previously, they could grow to that size but their performance degraded catastrophically).(Suggested by Raymond Hettinger and implemented by Benjamin Peterson;
9778.) -
A new macro
!Py_VA_COPYcopies the state of the variable argument list. It is equivalent to C99 va_copy but available on all Python platforms (2443). -
A new C API function
!PySys_SetArgvExallows an embedded interpreter to setsys.argvwithout also modifyingsys.path(5753). -
!PyEval_CallObjectis now only available in macro form. The function declaration, which was kept for backwards compatibility reasons, is now removed -- the macro was introduced in 1997 (8276). -
There is a new function
PyLong_AsLongLongAndOverflowwhich is analogous toPyLong_AsLongAndOverflow. They both serve to convert Pythonintinto a native fixed-width type while providing detection of cases where the conversion won't fit (7767). -
The
PyUnicode_CompareWithASCIIStringfunction now returns not equal if the Python string is NUL terminated. -
There is a new function
PyErr_NewExceptionWithDocthat is likePyErr_NewExceptionbut allows a docstring to be specified. This lets C exceptions have the same self-documenting capabilities as their pure Python counterparts (7033). -
When compiled with the
--with-valgrindoption, the pymalloc allocator will be automatically disabled when running under Valgrind. This gives improved memory leak detection when running under Valgrind, while taking advantage of pymalloc at other times (2422). -
Removed the
O?format from the PyArg_Parse functions. The format is no longer used and it had never been documented (8837).
There were a number of other small changes to the C-API. See the Misc/NEWS file for a complete list.
Also, there were a number of updates to the Mac OS X build, see Mac/BuildScript/README.txt for details. For users running a 32/64-bit build, there is a known problem with the default Tcl/Tk on Mac OS X 10.6. Accordingly, we recommend installing an updated alternative such as ActiveState Tcl/Tk 8.5.9. See https://www.python.org/download/mac/tcltk/ for additional details.
Porting to Python 3.2
This section lists previously described changes and other bugfixes that may require changes to your code:
-
The
configparsermodule has a number of clean-ups. The major change is to replace the old!ConfigParserclass with long-standing preferred alternative!SafeConfigParser. In addition there are a number of smaller incompatibilities:- The interpolation syntax is now validated on
~configparser.ConfigParser.getand~configparser.ConfigParser.setoperations. In the default interpolation scheme, only two tokens with percent signs are valid:%(name)sand%%, the latter being an escaped percent sign. - The
~configparser.ConfigParser.setand~configparser.ConfigParser.add_sectionmethods now verify that values are actual strings. Formerly, unsupported types could be introduced unintentionally. - Duplicate sections or options from a single source now raise either
~configparser.DuplicateSectionErroror~configparser.DuplicateOptionError. Formerly, duplicates would silently overwrite a previous entry. - Inline comments are now disabled by default so now the ; character can be safely used in values.
- Comments now can be indented. Consequently, for ; or # to appear at the start of a line in multiline values, it has to be interpolated. This keeps comment prefix characters in values from being mistaken as comments.
""is now a valid value and is no longer automatically converted to an empty string. For empty strings, use"option ="in a line.
- The interpolation syntax is now validated on
-
The
!nntplibmodule was reworked extensively, meaning that its APIs are often incompatible with the 3.1 APIs. -
bytearrayobjects can no longer be used as filenames; instead, they should be converted tobytes. -
The
!array.tostringand!array.fromstringhave been renamed toarray.tobytes() <array.array.tobytes>andarray.frombytes() <array.array.frombytes>for clarity. The old names have been deprecated. (See8990.) -
PyArg_Parse*()functions:- "t#" format has been removed: use "s#" or "s*" instead
- "w" and "w#" formats has been removed: use "w*" instead
-
The
!PyCObjecttype, deprecated in 3.1, has been removed. To wrap opaque C pointers in Python objects, thePyCapsuleAPI should be used instead; the new type has a well-defined interface for passing typing safety information and a less complicated signature for calling a destructor. -
The
!sys.setfilesystemencodingfunction was removed because it had a flawed design. -
The
random.seedfunction and method now salt string seeds with an sha512 hash function. To access the previous version of seed in order to reproduce Python 3.1 sequences, set the version argument to 1,random.seed(s, version=1). -
The previously deprecated
!string.maketransfunction has been removed in favor of the static methodsbytes.maketransandbytearray.maketrans. This change solves the confusion around which types were supported by thestringmodule. Now,str,bytes, andbytearrayeach have their own maketrans and translate methods with intermediate translation tables of the appropriate type.(Contributed by Georg Brandl;
5675.) -
The previously deprecated
!contextlib.nestedfunction has been removed in favor of a plainwithstatement which can accept multiple context managers. The latter technique is faster (because it is built-in), and it does a better job finalizing multiple context managers when one of them raises an exception:with open('mylog.txt') as infile, open('a.out', 'w') as outfile: for line in infile: if '<critical>' in line: outfile.write(line)(Contributed by Georg Brandl and Mattias Brändström; appspot issue 53094.)
-
struct.packnow only allows bytes for thesstring pack code. Formerly, it would accept text arguments and implicitly encode them to bytes using UTF-8. This was problematic because it made assumptions about the correct encoding and because a variable-length encoding can fail when writing to fixed length segment of a structure.Code such as
struct.pack('<6sHHBBB', 'GIF87a', x, y)should be rewritten with to use bytes instead of text,struct.pack('<6sHHBBB', b'GIF87a', x, y).(Discovered by David Beazley and fixed by Victor Stinner;
10783.) -
The
xml.etree.ElementTree <xml.etree.ElementTree.ElementTree>class now raises anxml.etree.ElementTree.ParseErrorwhen a parse fails. Previously it raised anxml.parsers.expat.ExpatError. -
The new, longer
strvalue on floats may break doctests which rely on the old output format. -
In
subprocess.Popen, the default value for close_fds is nowTrueunder Unix; under Windows, it isTrueif the three standard streams are set toNone,Falseotherwise. Previously, close_fds was alwaysFalseby default, which produced difficult to solve bugs or race conditions when open file descriptors would leak into the child process. -
Support for legacy HTTP 0.9 has been removed from
urllib.requestandhttp.client. Such support is still present on the server side (inhttp.server).(Contributed by Antoine Pitrou,
10711.) -
SSL sockets in timeout mode now raise
socket.timeoutwhen a timeout occurs, rather than a generic~ssl.SSLError.(Contributed by Antoine Pitrou,
10272.) -
The misleading functions
!PyEval_AcquireLockand!PyEval_ReleaseLockhave been officially deprecated. The thread-state aware APIs (such asPyEval_SaveThreadandPyEval_RestoreThread) should be used instead. -
Due to security risks,
!asyncore.handle_accepthas been deprecated, and a new function,!asyncore.handle_accepted, was added to replace it.(Contributed by Giampaolo Rodola in
6706.) -
Due to the new
GILimplementation,!PyEval_InitThreadscannot be called beforePy_Initializeanymore.
What's New In Python 3.3
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Mercurial log when researching a change.
This article explains the new features in Python 3.3, compared to 3.2. Python 3.3 was released on September 29, 2012. For full details, see the changelog.
398 - Python 3.3 Release Schedule
Summary -- Release highlights
New syntax features:
- New
yield fromexpression forgenerator delegation <pep-380>. - The
u'unicode'syntax is accepted again forstrobjects.
New library modules:
faulthandler(helps debugging low-level crashes)ipaddress(high-level objects representing IP addresses and masks)lzma(compress data using the XZ / LZMA algorithm)unittest.mock(replace parts of your system under test with mock objects)venv(Pythonvirtual environments <pep-405>, as in the popularvirtualenvpackage)
New built-in features:
- Reworked
I/O exception hierarchy <pep-3151>.
Implementation improvements:
- Rewritten
import machinery <importlib>based onimportlib. - More compact
unicode strings <pep-393>. - More compact
attribute dictionaries <pep-412>.
Significantly Improved Library Modules:
- C Accelerator for the
decimal <new-decimal>module. - Better unicode handling in the
email <new-email>module (provisional <provisional package>).
Security improvements:
- Hash randomization is switched on by default.
Please read on for a comprehensive list of user-facing changes.
PEP 405: Virtual Environments
Virtual environments help create separate Python setups while sharing a system-wide base install, for ease of maintenance. Virtual environments have their own set of private site packages (i.e. locally installed libraries), and are optionally segregated from the system-wide site packages. Their concept and implementation are inspired by the popular virtualenv third-party package, but benefit from tighter integration with the interpreter core.
This PEP adds the venv module for programmatic access, and the pyvenv script for command-line access and administration. The Python interpreter checks for a pyvenv.cfg, file whose existence signals the base of a virtual environment's directory tree.
405 - Python Virtual Environments
PEP written by Carl Meyer; implementation by Carl Meyer and Vinay Sajip
PEP 420: Implicit Namespace Packages
Native support for package directories that don't require __init__.py marker files and can automatically span multiple path segments (inspired by various third party approaches to namespace packages, as described in 420)
420 - Implicit Namespace Packages
PEP written by Eric V. Smith; implementation by Eric V. Smith and Barry Warsaw
PEP 3118: New memoryview implementation and buffer protocol documentation
The implementation of 3118 has been significantly improved.
The new memoryview implementation comprehensively fixes all ownership and lifetime issues of dynamically allocated fields in the Py_buffer struct that led to multiple crash reports. Additionally, several functions that crashed or returned incorrect results for non-contiguous or multi-dimensional input have been fixed.
The memoryview object now has a PEP-3118 compliant getbufferproc() that checks the consumer's request type. Many new features have been added, most of them work in full generality for non-contiguous arrays and arrays with suboffsets.
The documentation has been updated, clearly spelling out responsibilities for both exporters and consumers. Buffer request flags are grouped into basic and compound flags. The memory layout of non-contiguous and multi-dimensional NumPy-style arrays is explained.
Features
- All native single character format specifiers in struct module syntax (optionally prefixed with '@') are now supported.
- With some restrictions, the cast() method allows changing of format and shape of C-contiguous arrays.
- Multi-dimensional list representations are supported for any array type.
- Multi-dimensional comparisons are supported for any array type.
- One-dimensional memoryviews of hashable (read-only) types with formats B, b or c are now hashable. (Contributed by Antoine Pitrou in
13411.) - Arbitrary slicing of any 1-D arrays type is supported. For example, it is now possible to reverse a memoryview in O(1) by using a negative step.
API changes
- The maximum number of dimensions is officially limited to 64.
- The representation of empty shape, strides and suboffsets is now an empty tuple instead of
None. - Accessing a memoryview element with format 'B' (unsigned bytes) now returns an integer (in accordance with the struct module syntax). For returning a bytes object the view must be cast to 'c' first.
- memoryview comparisons now use the logical structure of the operands and compare all array elements by value. All format strings in struct module syntax are supported. Views with unrecognised format strings are still permitted, but will always compare as unequal, regardless of view contents.
- For further changes see Build and C API Changes and Porting C code.
(Contributed by Stefan Krah in 10181.)
3118 - Revising the Buffer Protocol
PEP 393: Flexible String Representation
The Unicode string type is changed to support multiple internal representations, depending on the character with the largest Unicode ordinal (1, 2, or 4 bytes) in the represented string. This allows a space-efficient representation in common cases, but gives access to full UCS-4 on all systems. For compatibility with existing APIs, several representations may exist in parallel; over time, this compatibility should be phased out.
On the Python side, there should be no downside to this change.
On the C API side, 393 is fully backward compatible. The legacy API should remain available at least five years. Applications using the legacy API will not fully benefit of the memory reduction, or - worse - may use a bit more memory, because Python may have to maintain two versions of each string (in the legacy format and in the new efficient storage).
Functionality
Changes introduced by 393 are the following:
- Python now always supports the full range of Unicode code points, including non-BMP ones (i.e. from
U+0000toU+10FFFF). The distinction between narrow and wide builds no longer exists and Python now behaves like a wide build, even under Windows. - With the death of narrow builds, the problems specific to narrow builds have also been fixed, for example:
lennow always returns 1 for non-BMP characters, solen('\U0010FFFF') == 1;- surrogate pairs are not recombined in string literals, so
'\uDBFF\uDFFF' != '\U0010FFFF'; - indexing or slicing non-BMP characters returns the expected value, so
'\U0010FFFF'[0]now returns'\U0010FFFF'and not'\uDBFF'; - all other functions in the standard library now correctly handle non-BMP code points.
- The value of
sys.maxunicodeis now always1114111(0x10FFFFin hexadecimal). The!PyUnicode_GetMaxfunction still returns either0xFFFFor0x10FFFFfor backward compatibility, and it should not be used with the new Unicode API (see13054). - The
./configureflag--with-wide-unicodehas been removed.
Performance and resource usage
The storage of Unicode strings now depends on the highest code point in the string:
- pure ASCII and Latin1 strings (
U+0000-U+00FF) use 1 byte per code point; - BMP strings (
U+0000-U+FFFF) use 2 bytes per code point; - non-BMP strings (
U+10000-U+10FFFF) use 4 bytes per code point.
The net effect is that for most applications, memory usage of string storage should decrease significantly - especially compared to former wide unicode builds - as, in many cases, strings will be pure ASCII even in international contexts (because many strings store non-human language data, such as XML fragments, HTTP headers, JSON-encoded data, etc.). We also hope that it will, for the same reasons, increase CPU cache efficiency on non-trivial applications. The memory usage of Python 3.3 is two to three times smaller than Python 3.2, and a little bit better than Python 2.7, on a Django benchmark (see the PEP for details).
393 - Flexible String Representation
PEP written by Martin von Löwis; implementation by Torsten Becker and Martin von Löwis.
PEP 397: Python Launcher for Windows
The Python 3.3 Windows installer now includes a py launcher application that can be used to launch Python applications in a version independent fashion.
This launcher is invoked implicitly when double-clicking *.py files. If only a single Python version is installed on the system, that version will be used to run the file. If multiple versions are installed, the most recent version is used by default, but this can be overridden by including a Unix-style "shebang line" in the Python script.
The launcher can also be used explicitly from the command line as the py application. Running py follows the same version selection rules as implicitly launching scripts, but a more specific version can be selected by passing appropriate arguments (such as -3 to request Python 3 when Python 2 is also installed, or -2.6 to specifically request an earlier Python version when a more recent version is installed).
In addition to the launcher, the Windows installer now includes an option to add the newly installed Python to the system PATH. (Contributed by Brian Curtin in 3561.)
397 - Python Launcher for Windows
PEP written by Mark Hammond and Martin v. Löwis; implementation by Vinay Sajip.
Launcher documentation: launcher
Installer PATH modification: windows-path-mod
PEP 3151: Reworking the OS and IO exception hierarchy
The hierarchy of exceptions raised by operating system errors is now both simplified and finer-grained.
You don't have to worry anymore about choosing the appropriate exception type between OSError, IOError, EnvironmentError, WindowsError, !mmap.error, socket.error or select.error. All these exception types are now only one: OSError. The other names are kept as aliases for compatibility reasons.
Also, it is now easier to catch a specific error condition. Instead of inspecting the errno attribute (or args[0]) for a particular constant from the errno module, you can catch the adequate OSError subclass. The available subclasses are the following:
BlockingIOErrorChildProcessErrorConnectionErrorFileExistsErrorFileNotFoundErrorInterruptedErrorIsADirectoryErrorNotADirectoryErrorPermissionErrorProcessLookupErrorTimeoutError
And the ConnectionError itself has finer-grained subclasses:
BrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetError
Thanks to the new exceptions, common usages of the errno can now be avoided. For example, the following code written for Python 3.2:
from errno import ENOENT, EACCES, EPERM
try:
with open("document.txt") as f:
content = f.read()
except IOError as err:
if err.errno == ENOENT:
print("document.txt file is missing")
elif err.errno in (EACCES, EPERM):
print("You are not allowed to read document.txt")
else:
raise
can now be written without the errno import and without manual inspection of exception attributes:
try:
with open("document.txt") as f:
content = f.read()
except FileNotFoundError:
print("document.txt file is missing")
except PermissionError:
print("You are not allowed to read document.txt")
3151 - Reworking the OS and IO Exception Hierarchy
PEP written and implemented by Antoine Pitrou
single: yield; yield from (in What's New)
PEP 380: Syntax for Delegating to a Subgenerator
PEP 380 adds the yield from expression, allowing a generator to delegate part of its operations to another generator. This allows a section of code containing yield to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.
While designed primarily for use in delegating to a subgenerator, the yield from expression actually allows delegation to arbitrary subiterators.
For simple iterators, yield from iterable is essentially just a shortened form of for item in iterable: yield item:
>>> def g(x):
... yield from range(x, 0, -1)
... yield from range(x)
...
>>> list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
However, unlike an ordinary loop, yield from allows subgenerators to receive sent and thrown values directly from the calling scope, and return a final value to the outer generator:
>>> def accumulate():
... tally = 0
... while 1:
... next = yield
... if next is None:
... return tally
... tally += next
...
>>> def gather_tallies(tallies):
... while 1:
... tally = yield from accumulate()
... tallies.append(tally)
...
>>> tallies = []
>>> acc = gather_tallies(tallies)
>>> next(acc) # Ensure the accumulator is ready to accept values
>>> for i in range(4):
... acc.send(i)
...
>>> acc.send(None) # Finish the first tally
>>> for i in range(5):
... acc.send(i)
...
>>> acc.send(None) # Finish the second tally
>>> tallies
[6, 10]
The main principle driving this change is to allow even generators that are designed to be used with the send and throw methods to be split into multiple subgenerators as easily as a single large function can be split into multiple subfunctions.
380 - Syntax for Delegating to a Subgenerator
PEP written by Greg Ewing; implementation by Greg Ewing, integrated into 3.3 by Renaud Blanch, Ryan Kelly and Nick Coghlan; documentation by Zbigniew Jędrzejewski-Szmek and Nick Coghlan
PEP 409: Suppressing exception context
PEP 409 introduces new syntax that allows the display of the chained exception context to be disabled. This allows cleaner error messages in applications that convert between exception types:
>>> class D:
... def __init__(self, extra):
... self._extra_attributes = extra
... def __getattr__(self, attr):
... try:
... return self._extra_attributes[attr]
... except KeyError:
... raise AttributeError(attr) from None
...
>>> D({}).x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __getattr__
AttributeError: x
Without the from None suffix to suppress the cause, the original exception would be displayed by default:
>>> class C:
... def __init__(self, extra):
... self._extra_attributes = extra
... def __getattr__(self, attr):
... try:
... return self._extra_attributes[attr]
... except KeyError:
... raise AttributeError(attr)
...
>>> C({}).x
Traceback (most recent call last):
File "<stdin>", line 6, in __getattr__
KeyError: 'x'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __getattr__
AttributeError: x
No debugging capability is lost, as the original exception context remains available if needed (for example, if an intervening library has incorrectly suppressed valuable underlying details):
>>> try:
... D({}).x
... except AttributeError as exc:
... print(repr(exc.__context__))
...
KeyError('x',)
409 - Suppressing exception context
PEP written by Ethan Furman; implemented by Ethan Furman and Nick Coghlan.
PEP 414: Explicit Unicode literals
To ease the transition from Python 2 for Unicode aware Python applications that make heavy use of Unicode literals, Python 3.3 once again supports the "u" prefix for string literals. This prefix has no semantic significance in Python 3, it is provided solely to reduce the number of purely mechanical changes in migrating to Python 3, making it easier for developers to focus on the more significant semantic changes (such as the stricter default separation of binary and text data).
414 - Explicit Unicode literals
PEP written by Armin Ronacher.
PEP 3155: Qualified name for classes and functions
Functions and class objects have a new ~definition.__qualname__ attribute representing the "path" from the module top-level to their definition. For global functions and classes, this is the same as ~definition.__name__. For other functions and classes, it provides better information about where they were actually defined, and how they might be accessible from the global scope.
Example with (non-bound) methods:
>>> class C:
... def meth(self):
... pass
...
>>> C.meth.__name__
'meth'
>>> C.meth.__qualname__
'C.meth'
Example with nested classes:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.D.__name__
'D'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__name__
'meth'
>>> C.D.meth.__qualname__
'C.D.meth'
Example with nested functions:
>>> def outer():
... def inner():
... pass
... return inner
...
>>> outer().__name__
'inner'
>>> outer().__qualname__
'outer.<locals>.inner'
The string representation of those objects is also changed to include the new, more precise information:
>>> str(C.D)
"<class '__main__.C.D'>"
>>> str(C.D.meth)
'<function C.D.meth at 0x7f46b9fe31e0>'
3155 - Qualified name for classes and functions
PEP written and implemented by Antoine Pitrou.
PEP 412: Key-Sharing Dictionary
Dictionaries used for the storage of objects' attributes are now able to share part of their internal storage between each other (namely, the part which stores the keys and their respective hashes). This reduces the memory consumption of programs creating many instances of non-builtin types.
412 - Key-Sharing Dictionary
PEP written and implemented by Mark Shannon.
PEP 362: Function Signature Object
A new function inspect.signature makes introspection of python callables easy and straightforward. A broad range of callables is supported: python functions, decorated or not, classes, and functools.partial objects. New classes inspect.Signature, inspect.Parameter and inspect.BoundArguments hold information about the call signatures, such as, annotations, default values, parameters kinds, and bound arguments, which considerably simplifies writing decorators and any code that validates or amends calling signatures or arguments.
362: - Function Signature Object
PEP written by Brett Cannon, Yury Selivanov, Larry Hastings, Jiwon Seo; implemented by Yury Selivanov.
PEP 421: Adding sys.implementation
A new attribute on the sys module exposes details specific to the implementation of the currently running interpreter. The initial set of attributes on sys.implementation are name, version, hexversion, and cache_tag.
The intention of sys.implementation is to consolidate into one namespace the implementation-specific data used by the standard library. This allows different Python implementations to share a single standard library code base much more easily. In its initial state, sys.implementation holds only a small portion of the implementation-specific data. Over time that ratio will shift in order to make the standard library more portable.
One example of improved standard library portability is cache_tag. As of Python 3.3, sys.implementation.cache_tag is used by importlib to support 3147 compliance. Any Python implementation that uses importlib for its built-in import system may use cache_tag to control the caching behavior for modules.
SimpleNamespace
The implementation of sys.implementation also introduces a new type to Python: types.SimpleNamespace. In contrast to a mapping-based namespace, like dict, SimpleNamespace is attribute-based, like object. However, unlike object, SimpleNamespace instances are writable. This means that you can add, remove, and modify the namespace through normal attribute access.
421 - Adding sys.implementation
PEP written and implemented by Eric Snow.
Using importlib as the Implementation of Import
2377 - Replace __import__ w/ importlib.__import__ 13959 - Re-implement parts of !imp in pure Python 14605 - Make import machinery explicit 14646 - Require loaders set __loader__ and __package__
The __import__ function is now powered by importlib.__import__. This work leads to the completion of "phase 2" of 302. There are multiple benefits to this change. First, it has allowed for more of the machinery powering import to be exposed instead of being implicit and hidden within the C code. It also provides a single implementation for all Python VMs supporting Python 3.3 to use, helping to end any VM-specific deviations in import semantics. And finally it eases the maintenance of import, allowing for future growth to occur.
For the common user, there should be no visible change in semantics. For those whose code currently manipulates import or calls import programmatically, the code changes that might possibly be required are covered in the Porting Python code section of this document.
New APIs
One of the large benefits of this work is the exposure of what goes into making the import statement work. That means the various importers that were once implicit are now fully exposed as part of the importlib package.
The abstract base classes defined in importlib.abc have been expanded to properly delineate between meta path finders <meta path finder> and path entry finders <path entry finder> by introducing importlib.abc.MetaPathFinder and importlib.abc.PathEntryFinder, respectively. The old ABC of !importlib.abc.Finder is now only provided for backwards-compatibility and does not enforce any method requirements.
In terms of finders, importlib.machinery.FileFinder exposes the mechanism used to search for source and bytecode files of a module. Previously this class was an implicit member of sys.path_hooks.
For loaders, the new abstract base class importlib.abc.FileLoader helps write a loader that uses the file system as the storage mechanism for a module's code. The loader for source files (importlib.machinery.SourceFileLoader), sourceless bytecode files (importlib.machinery.SourcelessFileLoader), and extension modules (importlib.machinery.ExtensionFileLoader) are now available for direct use.
ImportError now has name and path attributes which are set when there is relevant data to provide. The message for failed imports will also provide the full name of the module now instead of just the tail end of the module's name.
The importlib.invalidate_caches function will now call the method with the same name on all finders cached in sys.path_importer_cache to help clean up any stored state as necessary.
Visible Changes
For potential required changes to code, see the Porting Python code section.
Beyond the expanse of what importlib now exposes, there are other visible changes to import. The biggest is that sys.meta_path and sys.path_hooks now store all of the meta path finders and path entry hooks used by import. Previously the finders were implicit and hidden within the C code of import instead of being directly exposed. This means that one can now easily remove or change the order of the various finders to fit one's needs.
Another change is that all modules have a __loader__ attribute, storing the loader used to create the module. 302 has been updated to make this attribute mandatory for loaders to implement, so in the future once 3rd-party loaders have been updated people will be able to rely on the existence of the attribute. Until such time, though, import is setting the module post-load.
Loaders are also now expected to set the __package__ attribute from 366. Once again, import itself is already setting this on all loaders from importlib and import itself is setting the attribute post-load.
None is now inserted into sys.path_importer_cache when no finder can be found on sys.path_hooks. Since !imp.NullImporter is not directly exposed on sys.path_hooks it could no longer be relied upon to always be available to use as a value representing no finder found.
All other changes relate to semantic changes which should be taken into consideration when updating code for Python 3.3, and thus should be read about in the Porting Python code section of this document.
(Implementation by Brett Cannon)
Other Language Changes
Some smaller changes made to the core Python language are:
-
Added support for Unicode name aliases and named sequences. Both
unicodedata.lookupand'\N{...}'now resolve name aliases, andunicodedata.lookupresolves named sequences too.(Contributed by Ezio Melotti in
12753.) -
Unicode database updated to UCD version 6.1.0
-
Equality comparisons on
rangeobjects now return a result reflecting the equality of the underlying sequences generated by those range objects. (13201) -
The
count(),find(),rfind(),index()andrindex()methods ofbytesandbytearrayobjects now accept an integer between 0 and 255 as their first argument.(Contributed by Petri Lehtinen in
12170.) -
The
rjust(),ljust(), andcenter()methods ofbytesandbytearraynow accept abytearrayfor thefillargument. (Contributed by Petri Lehtinen in12380.) -
New methods have been added to
listandbytearray:copy()andclear()(10516). Consequently,~collections.abc.MutableSequencenow also defines a!clearmethod (11388). -
Raw bytes literals can now be written
rb"..."as well asbr"...".(Contributed by Antoine Pitrou in
13748.) -
dict.setdefaultnow does only one lookup for the given key, making it atomic when used with built-in types.(Contributed by Filip Gruszczyński in
13521.) -
The error messages produced when a function call does not match the function signature have been significantly improved.
(Contributed by Benjamin Peterson.)
A Finer-Grained Import Lock
Previous versions of CPython have always relied on a global import lock. This led to unexpected annoyances, such as deadlocks when importing a module would trigger code execution in a different thread as a side-effect. Clumsy workarounds were sometimes employed, such as the !PyImport_ImportModuleNoBlock C API function.
In Python 3.3, importing a module takes a per-module lock. This correctly serializes importation of a given module from multiple threads (preventing the exposure of incompletely initialized modules), while eliminating the aforementioned annoyances.
(Contributed by Antoine Pitrou in 9260.)
Builtin functions and types
opengets a new opener parameter: the underlying file descriptor for the file object is then obtained by calling opener with (file, flags). It can be used to use custom flags likeos.O_CLOEXECfor example. The'x'mode was added: open for exclusive creation, failing if the file already exists.print: added the flush keyword argument. If the flush keyword argument is true, the stream is forcibly flushed.hash: hash randomization is enabled by default, seeobject.__hash__andPYTHONHASHSEED.- The
strtype gets a new~str.casefoldmethod: return a casefolded copy of the string, casefolded strings may be used for caseless matching. For example,'ß'.casefold()returns'ss'. - The sequence documentation has been substantially rewritten to better explain the binary/text sequence distinction and to provide specific documentation sections for the individual builtin sequence types (
4966).
New Modules
faulthandler
This new debug module faulthandler contains functions to dump Python tracebacks explicitly, on a fault (a crash like a segmentation fault), after a timeout, or on a user signal. Call faulthandler.enable to install fault handlers for the ~signal.SIGSEGV, ~signal.SIGFPE, ~signal.SIGABRT, ~signal.SIGBUS, and ~signal.SIGILL signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using -X faulthandler command line option.
Example of a segmentation fault on Linux:
$ python -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault
Current thread 0x00007fb899f39700:
File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
File "<stdin>", line 1 in <module>
Segmentation fault
ipaddress
The new ipaddress module provides tools for creating and manipulating objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e. an IP address associated with a specific IP subnet).
(Contributed by Google and Peter Moody in 3144.)
lzma
The newly added lzma module provides data compression and decompression using the LZMA algorithm, including support for the .xz and .lzma file formats.
(Contributed by Nadeem Vawda and Per Øyvind Karlsen in 6715.)
Improved Modules
abc
Improved support for abstract base classes containing descriptors composed with abstract methods. The recommended approach to declaring abstract descriptors is now to provide !__isabstractmethod__ as a dynamically updated property. The built-in descriptors have been updated accordingly.
abc.abstractpropertyhas been deprecated, usepropertywithabc.abstractmethodinstead.abc.abstractclassmethodhas been deprecated, useclassmethodwithabc.abstractmethodinstead.abc.abstractstaticmethodhas been deprecated, usestaticmethodwithabc.abstractmethodinstead.
(Contributed by Darren Dale in 11610.)
abc.ABCMeta.register now returns the registered subclass, which means it can now be used as a class decorator (10868).
array
The array module supports the long long type using q and Q type codes.
(Contributed by Oren Tirosh and Hirokazu Yamamoto in 1172711.)
base64
ASCII-only Unicode strings are now accepted by the decoding functions of the base64 modern interface. For example, base64.b64decode('YWJj') returns b'abc'. (Contributed by Catalin Iacob in 13641.)
binascii
In addition to the binary objects they normally accept, the a2b_ functions now all also accept ASCII-only strings as input. (Contributed by Antoine Pitrou in 13637.)
bz2
The bz2 module has been rewritten from scratch. In the process, several new features have been added:
-
New
bz2.openfunction: open a bzip2-compressed file in binary or text mode. -
bz2.BZ2Filecan now read from and write to arbitrary file-like objects, by means of its constructor's fileobj argument.(Contributed by Nadeem Vawda in
5863.) -
bz2.BZ2Fileandbz2.decompresscan now decompress multi-stream inputs (such as those produced by thepbzip2tool).bz2.BZ2Filecan now also be used to create this type of file, using the'a'(append) mode.(Contributed by Nir Aides in
1625.) -
bz2.BZ2Filenow implements all of theio.BufferedIOBaseAPI, except for the!detachand!truncatemethods.
codecs
The ~encodings.mbcs codec has been rewritten to handle correctly replace and ignore error handlers on all Windows versions. The ~encodings.mbcs codec now supports all error handlers, instead of only replace to encode and ignore to decode.
A new Windows-only codec has been added: cp65001 (13216). It is the Windows code page 65001 (Windows UTF-8, CP_UTF8). For example, it is used by sys.stdout if the console output code page is set to cp65001 (e.g., using chcp 65001 command).
Multibyte CJK decoders now resynchronize faster. They only ignore the first byte of an invalid byte sequence. For example, b'\xff\n'.decode('gb2312', 'replace') now returns a \n after the replacement character.
(12016)
Incremental CJK codec encoders are no longer reset at each call to their encode() methods. For example:
>>> import codecs
>>> encoder = codecs.getincrementalencoder('hz')('strict')
>>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
b'~{NpJ)l6HK!#~} Bye.'
This example gives b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.' with older Python versions.
(12100)
The unicode_internal codec has been deprecated.
collections
Addition of a new ~collections.ChainMap class to allow treating a number of mappings as a single unit. (Written by Raymond Hettinger for 11089, made public in 11297.)
The abstract base classes have been moved in a new collections.abc module, to better differentiate between the abstract and the concrete collections classes. Aliases for ABCs are still present in the collections module to preserve existing imports. (11085)
The ~collections.Counter class now supports the unary + and - operators, as well as the in-place operators +=, -=, |=, and &=. (Contributed by Raymond Hettinger in 13121.)
contextlib
~contextlib.ExitStack now provides a solid foundation for programmatic manipulation of context managers and similar cleanup functionality. Unlike the previous contextlib.nested API (which was deprecated and removed), the new API is designed to work correctly regardless of whether context managers acquire their resources in their __init__ method (for example, file objects) or in their __enter__ method (for example, synchronisation objects from the threading module).
(13585)
crypt
Addition of salt and modular crypt format (hashing method) and the !mksalt function to the !crypt module.
(10924)
curses
- If the
cursesmodule is linked to the ncursesw library, use Unicode functions when Unicode strings or characters are passed (e.g.!waddwstr), and bytes functions otherwise (e.g.!waddstr). - Use the locale encoding instead of
utf-8to encode Unicode strings. curses.windowhas a newcurses.window.encodingattribute.- The
curses.windowclass has a new~curses.window.get_wchmethod to get a wide character - The
cursesmodule has a new~curses.unget_wchfunction to push a wide character so the next~curses.window.get_wchwill return it
(Contributed by Iñigo Serna in 6755.)
datetime
- Equality comparisons between naive and aware
~datetime.datetimeinstances now returnFalseinstead of raisingTypeError(15006). - New
datetime.datetime.timestampmethod: Return POSIX timestamp corresponding to the~datetime.datetimeinstance. - The
datetime.datetime.strftimemethod supports formatting years older than 1000. - The
datetime.datetime.astimezonemethod can now be called without arguments to convert datetime instance to the system timezone.
decimal
7652 - integrate fast native decimal arithmetic.
C-module and libmpdec written by Stefan Krah.
The new C version of the decimal module integrates the high speed libmpdec library for arbitrary precision correctly rounded decimal floating-point arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.
Performance gains range from 10x for database applications to 100x for numerically intensive applications. These numbers are expected gains for standard precisions used in decimal floating-point arithmetic. Since the precision is user configurable, the exact figures may vary. For example, in integer bignum arithmetic the differences can be significantly higher.
The following table is meant as an illustration. Benchmarks are available at https://www.bytereef.org/mpdecimal/quickstart.html.
decimal.py
decimal
speedup
pi
42.02s
0.345s
120x
telco
172.19s
5.68s
30x
psycopg
3.57s
0.29s
12x
Features
- The
~decimal.FloatOperationsignal optionally enables stricter semantics for mixing floats and Decimals. - If Python is compiled without threads, the C version automatically disables the expensive thread local context machinery. In this case, the variable
~decimal.HAVE_THREADSis set toFalse.
API changes
-
The C module has the following context limits, depending on the machine architecture:
32-bit
64-bit
~decimal.MAX_PREC425000000999999999999999999~decimal.MAX_EMAX425000000999999999999999999~decimal.MIN_EMIN-425000000-999999999999999999 -
In the context templates (
~decimal.DefaultContext,~decimal.BasicContextand~decimal.ExtendedContext) the magnitude of~decimal.Context.Emaxand~decimal.Context.Eminhas changed to999999. -
The
~decimal.Decimalconstructor in decimal.py does not observe the context limits and converts values with arbitrary exponents or precision exactly. Since the C version has internal limits, the following scheme is used: If possible, values are converted exactly, otherwise~decimal.InvalidOperationis raised and the result is NaN. In the latter case it is always possible to use~decimal.Context.create_decimalin order to obtain a rounded or inexact value. -
The power function in decimal.py is always correctly rounded. In the C version, it is defined in terms of the correctly rounded
~decimal.Decimal.expand~decimal.Decimal.lnfunctions, but the final result is only "almost always correctly rounded". -
In the C version, the context dictionary containing the signals is a
~collections.abc.MutableMapping. For speed reasons,~decimal.Context.flagsand~decimal.Context.trapsalways refer to the same~collections.abc.MutableMappingthat the context was initialized with. If a new signal dictionary is assigned,~decimal.Context.flagsand~decimal.Context.trapsare updated with the new values, but they do not reference the RHS dictionary. -
Pickling a
~decimal.Contextproduces a different output in order to have a common interchange format for the Python and C versions. -
The order of arguments in the
~decimal.Contextconstructor has been changed to match the order displayed byrepr. -
The
watchexpparameter in the~decimal.Decimal.quantizemethod is deprecated.
Policy Framework
The email package now has a ~email.policy framework. A ~email.policy.Policy is an object with several methods and properties that control how the email package behaves. The primary policy for Python 3.3 is the ~email.policy.Compat32 policy, which provides backward compatibility with the email package in Python 3.2. A policy can be specified when an email message is parsed by a ~email.parser, or when a ~email.message.Message object is created, or when an email is serialized using a ~email.generator. Unless overridden, a policy passed to a parser is inherited by all the Message object and sub-objects created by the parser. By default a generator will use the policy of the Message object it is serializing. The default policy is ~email.policy.compat32.
The minimum set of controls implemented by all policy objects are:
|l|L|
| max_line_length | The maximum length, excluding the linesep character(s), individual lines may have when a Message is serialized. Defaults to 78. |
| linesep | The character used to separate individual lines when a Message is serialized. Defaults to \n. |
| cte_type | 7bit or 8bit. 8bit applies only to a Bytes generator, and means that non-ASCII may be used where allowed by the protocol (or where it exists in the original input). |
| raise_on_defect | Causes a parser to raise error when defects are encountered instead of adding them to the Message object's defects list. |
A new policy instance, with new settings, is created using the ~email.policy.Policy.clone method of policy objects. clone takes any of the above controls as keyword arguments. Any control not specified in the call retains its default value. Thus you can create a policy that uses \r\n linesep characters like this:
mypolicy = compat32.clone(linesep='\r\n')
Policies can be used to make the generation of messages in the format needed by your application simpler. Instead of having to remember to specify linesep='\r\n' in all the places you call a generator, you can specify it once, when you set the policy used by the parser or the Message, whichever your program uses to create Message objects. On the other hand, if you need to generate messages in multiple forms, you can still specify the parameters in the appropriate generator call. Or you can have custom policy instances for your different cases, and pass those in when you create the generator.
Provisional Policy with New Header API
While the policy framework is worthwhile all by itself, the main motivation for introducing it is to allow the creation of new policies that implement new features for the email package in a way that maintains backward compatibility for those who do not use the new policies. Because the new policies introduce a new API, we are releasing them in Python 3.3 as a provisional policy <provisional package>. Backwards incompatible changes (up to and including removal of the code) may occur if deemed necessary by the core developers.
The new policies are instances of ~email.policy.EmailPolicy, and add the following additional controls:
|l|L|
| refold_source | Controls whether or not headers parsed by a ~email.parser are refolded by the ~email.generator. It can be none, long, or all. The default is long, which means that source headers with a line longer than max_line_length get refolded. none means no line get refolded, and all means that all lines get refolded. |
| header_factory | A callable that take a name and value and produces a custom header object. |
The header_factory is the key to the new features provided by the new policies. When one of the new policies is used, any header retrieved from a Message object is an object produced by the header_factory, and any time you set a header on a Message it becomes an object produced by header_factory. All such header objects have a name attribute equal to the header name. Address and Date headers have additional attributes that give you access to the parsed data of the header. This means you can now do things like this:
>>> m = Message(policy=SMTP)
>>> m['To'] = 'Éric <foo@example.com>'
>>> m['to']
'Éric <foo@example.com>'
>>> m['to'].addresses
(Address(display_name='Éric', username='foo', domain='example.com'),)
>>> m['to'].addresses[0].username
'foo'
>>> m['to'].addresses[0].display_name
'Éric'
>>> m['Date'] = email.utils.localtime()
>>> m['Date'].datetime
datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
>>> m['Date']
'Fri, 25 May 2012 21:44:27 -0400'
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
You will note that the unicode display name is automatically encoded as utf-8 when the message is serialized, but that when the header is accessed directly, you get the unicode version. This eliminates any need to deal with the email.header ~email.header.decode_header or ~email.header.make_header functions.
You can also create addresses from parts:
>>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
... Address('Sally', 'sally', 'example.com')]),
... Address('Bonzo', addr_spec='bonz@laugh.com')]
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>
Decoding to unicode is done automatically:
>>> m2 = message_from_string(str(m))
>>> m2['to']
'Éric <foo@example.com>'
When you parse a message, you can use the addresses and groups attributes of the header objects to access the groups and individual addresses:
>>> m2['cc'].addresses
(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))
>>> m2['cc'].groups
(Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))
In summary, if you use one of the new policies, header manipulation works the way it ought to: your application works with unicode strings, and the email package transparently encodes and decodes the unicode to and from the RFC standard Content Transfer Encodings.
Other API Changes
New ~email.parser.BytesHeaderParser, added to the ~email.parser module to complement ~email.parser.HeaderParser and complete the Bytes API.
New utility functions:
~email.utils.format_datetime: given a~datetime.datetime, produce a string formatted for use in an email header.~email.utils.parsedate_to_datetime: given a date string from an email header, convert it into an aware~datetime.datetime, or a naive~datetime.datetimeif the offset is-0000.~email.utils.localtime: With no argument, returns the current local time as an aware~datetime.datetimeusing the local~datetime.timezone. Given an aware~datetime.datetime, converts it into an aware~datetime.datetimeusing the local~datetime.timezone.
ftplib
ftplib.FTPnow accepts asource_addresskeyword argument to specify the(host, port)to use as the source address in the bind call when creating the outgoing socket. (Contributed by Giampaolo Rodolà in8594.)- The
~ftplib.FTP_TLSclass now provides a new~ftplib.FTP_TLS.cccfunction to revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports. (Contributed by Giampaolo Rodolà in12139.) - Added
ftplib.FTP.mlsdmethod which provides a parsable directory listing format and deprecatesftplib.FTP.nlstandftplib.FTP.dir. (Contributed by Giampaolo Rodolà in11072.)
functools
The functools.lru_cache decorator now accepts a typed keyword argument (that defaults to False to ensure that it caches values of different types that compare equal in separate cache slots. (Contributed by Raymond Hettinger in 13227.)
gc
It is now possible to register callbacks invoked by the garbage collector before and after collection using the new ~gc.callbacks list.
hmac
A new ~hmac.compare_digest function has been added to prevent side channel attacks on digests through timing analysis. (Contributed by Nick Coghlan and Christian Heimes in 15061.)
http
http.server.BaseHTTPRequestHandler now buffers the headers and writes them all at once when ~http.server.BaseHTTPRequestHandler.end_headers is called. A new method ~http.server.BaseHTTPRequestHandler.flush_headers can be used to directly manage when the accumulated headers are sent. (Contributed by Andrew Schaaf in 3709.)
http.server now produces valid HTML 4.01 strict output. (Contributed by Ezio Melotti in 13295.)
http.client.HTTPResponse now has a ~http.client.HTTPResponse.readinto method, which means it can be used as an io.RawIOBase class. (Contributed by John Kuhn in 13464.)
html
html.parser.HTMLParser is now able to parse broken markup without raising errors, therefore the strict argument of the constructor and the !HTMLParseError exception are now deprecated. The ability to parse broken markup is the result of a number of bug fixes that are also available on the latest bug fix releases of Python 2.7/3.2. (Contributed by Ezio Melotti in 15114, and 14538, 13993, 13960, 13358, 1745761, 755670, 13357, 12629, 1200313, 670664, 13273, 12888, 7311.)
A new ~html.entities.html5 dictionary that maps HTML5 named character references to the equivalent Unicode character(s) (e.g. html5['gt;'] == '>') has been added to the html.entities module. The dictionary is now also used by ~html.parser.HTMLParser. (Contributed by Ezio Melotti in 11113 and 15156.)
imaplib
The ~imaplib.IMAP4_SSL constructor now accepts an SSLContext parameter to control parameters of the secure channel.
(Contributed by Sijin Joseph in 8808.)
inspect
A new ~inspect.getclosurevars function has been added. This function reports the current binding of all names referenced from the function body and where those names were resolved, making it easier to verify correct internal state when testing code that relies on stateful closures.
(Contributed by Meador Inge and Nick Coghlan in 13062.)
A new ~inspect.getgeneratorlocals function has been added. This function reports the current binding of local variables in the generator's stack frame, making it easier to verify correct internal state when testing generators.
(Contributed by Meador Inge in 15153.)
io
The ~io.open function has a new 'x' mode that can be used to exclusively create a new file, and raise a FileExistsError if the file already exists. It is based on the C11 'x' mode to fopen().
(Contributed by David Townshend in 12760.)
The constructor of the ~io.TextIOWrapper class has a new write_through optional argument. If write_through is True, calls to !write are guaranteed not to be buffered: any data written on the ~io.TextIOWrapper object is immediately handled to its underlying binary buffer.
itertools
~itertools.accumulate now takes an optional func argument for providing a user-supplied binary function.
logging
The ~logging.basicConfig function now supports an optional handlers argument taking an iterable of handlers to be added to the root logger.
A class level attribute !append_nul has been added to ~logging.handlers.SysLogHandler to allow control of the appending of the NUL (\000) byte to syslog records, since for some daemons it is required while for others it is passed through to the log.
math
The math module has a new function, ~math.log2, which returns the base-2 logarithm of x.
(Written by Mark Dickinson in 11888.)
mmap
The ~mmap.mmap.read method is now more compatible with other file-like objects: if the argument is omitted or specified as None, it returns the bytes from the current file position to the end of the mapping. (Contributed by Petri Lehtinen in 12021.)
multiprocessing
The new multiprocessing.connection.wait function allows polling multiple objects (such as connections, sockets and pipes) with a timeout. (Contributed by Richard Oudkerk in 12328.)
multiprocessing.connection.Connection objects can now be transferred over multiprocessing connections. (Contributed by Richard Oudkerk in 4892.)
multiprocessing.Process now accepts a daemon keyword argument to override the default behavior of inheriting the daemon flag from the parent process (6064).
New attribute multiprocessing.Process.sentinel allows a program to wait on multiple ~multiprocessing.Process objects at one time using the appropriate OS primitives (for example, select on posix systems).
New methods multiprocessing.pool.Pool.starmap and ~multiprocessing.pool.Pool.starmap_async provide itertools.starmap equivalents to the existing multiprocessing.pool.Pool.map and ~multiprocessing.pool.Pool.map_async functions. (Contributed by Hynek Schlawack in 12708.)
nntplib
The !nntplib.NNTP class now supports the context management protocol to unconditionally consume socket.error exceptions and to close the NNTP connection when done:
>>> from nntplib import NNTP
>>> with NNTP('news.gmane.org') as n:
... n.group('gmane.comp.python.committers')
...
('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
>>>
(Contributed by Giampaolo Rodolà in 9795.)
os
-
The
osmodule has a new~os.pipe2function that makes it possible to create a pipe with~os.O_CLOEXECor~os.O_NONBLOCKflags set atomically. This is especially useful to avoid race conditions in multi-threaded programs. -
The
osmodule has a new~os.sendfilefunction which provides an efficient "zero-copy" way for copying data from one file (or socket) descriptor to another. The phrase "zero-copy" refers to the fact that all of the copying of data between the two descriptors is done entirely by the kernel, with no copying of data into userspace buffers.~os.sendfilecan be used to efficiently copy data from a file on disk to a network socket, e.g. for downloading a file.(Patch submitted by Ross Lagerwall and Giampaolo Rodolà in
10882.) -
To avoid race conditions like symlink attacks and issues with temporary files and directories, it is more reliable (and also faster) to manipulate file descriptors instead of file names. Python 3.3 enhances existing functions and introduces new functions to work on file descriptors (
4761,10755and14626).- The
osmodule has a new~os.fwalkfunction similar to~os.walkexcept that it also yields file descriptors referring to the directories visited. This is especially useful to avoid symlink races. - The following functions get new optional dir_fd (
paths relative to directory descriptors <dir_fd>) and/or follow_symlinks (not following symlinks <follow_symlinks>):~os.access,~os.chflags,~os.chmod,~os.chown,~os.link,~os.lstat,~os.mkdir,~os.mkfifo,~os.mknod,~os.open,~os.readlink,~os.remove,~os.rename,~os.replace,~os.rmdir,~os.stat,~os.symlink,~os.unlink,~os.utime. Platform support for using these parameters can be checked via the setsos.supports_dir_fdandos.supports_follow_symlinks. - The following functions now support a file descriptor for their path argument:
~os.chdir,~os.chmod,~os.chown,~os.execve,~os.listdir,~os.pathconf,~os.path.exists,~os.stat,~os.statvfs,~os.utime. Platform support for this can be checked via theos.supports_fdset.
- The
-
~os.accessaccepts aneffective_idskeyword argument to turn on using the effective uid/gid rather than the real uid/gid in the access check. Platform support for this can be checked via the~os.supports_effective_idsset. -
The
osmodule has two new functions:~os.getpriorityand~os.setpriority. They can be used to get or set process niceness/priority in a fashion similar toos.nicebut extended to all processes instead of just the current one.(Patch submitted by Giampaolo Rodolà in
10784.) -
The new
os.replacefunction allows cross-platform renaming of a file with overwriting the destination. Withos.rename, an existing destination file is overwritten under POSIX, but raises an error under Windows. (Contributed by Antoine Pitrou in8828.) -
The stat family of functions (
~os.stat,~os.fstat, and~os.lstat) now support reading a file's timestamps with nanosecond precision. Symmetrically,~os.utimecan now write file timestamps with nanosecond precision. (Contributed by Larry Hastings in14127.) -
The new
os.get_terminal_sizefunction queries the size of the terminal attached to a file descriptor. See alsoshutil.get_terminal_size. (Contributed by Zbigniew Jędrzejewski-Szmek in13609.)
- New functions to support Linux extended attributes (
12720):~os.getxattr,~os.listxattr,~os.removexattr,~os.setxattr. - New interface to the scheduler. These functions control how a process is allocated CPU time by the operating system. New functions:
~os.sched_get_priority_max,~os.sched_get_priority_min,~os.sched_getaffinity,~os.sched_getparam,~os.sched_getscheduler,~os.sched_rr_get_interval,~os.sched_setaffinity,~os.sched_setparam,~os.sched_setscheduler,~os.sched_yield, - New functions to control the file system:
~os.posix_fadvise: Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations.~os.posix_fallocate: Ensures that enough disk space is allocated for a file.~os.sync: Force write of everything to disk.
- Additional new posix functions:
~os.lockf: Apply, test or remove a POSIX lock on an open file descriptor.~os.pread: Read from a file descriptor at an offset, the file offset remains unchanged.~os.pwrite: Write to a file descriptor from an offset, leaving the file offset unchanged.~os.readv: Read from a file descriptor into a number of writable buffers.~os.truncate: Truncate the file corresponding to path, so that it is at most length bytes in size.~os.waitid: Wait for the completion of one or more child processes.~os.writev: Write the contents of buffers to a file descriptor, where buffers is an arbitrary sequence of buffers.~os.getgrouplist(9344): Return list of group ids that specified user belongs to.
~os.timesand~os.uname: Return type changed from a tuple to a tuple-like object with named attributes.- Some platforms now support additional constants for the
~os.lseekfunction, such asos.SEEK_HOLEandos.SEEK_DATA. - New constants
~os.RTLD_LAZY,~os.RTLD_NOW,~os.RTLD_GLOBAL,~os.RTLD_LOCAL,~os.RTLD_NODELETE,~os.RTLD_NOLOAD, and~os.RTLD_DEEPBINDare available on platforms that support them. These are for use with thesys.setdlopenflagsfunction, and supersede the similar constants defined inctypesand!DLFCN. (Contributed by Victor Stinner in13226.) os.symlinknow accepts (and ignores) thetarget_is_directorykeyword argument on non-Windows platforms, to ease cross-platform support.
pdb
Tab-completion is now available not only for command names, but also their arguments. For example, for the break command, function and file names are completed.
(Contributed by Georg Brandl in 14210)
pickle
pickle.Pickler objects now have an optional ~pickle.Pickler.dispatch_table attribute allowing per-pickler reduction functions to be set.
(Contributed by Richard Oudkerk in 14166.)
pydoc
The Tk GUI and the !serve function have been removed from the pydoc module: pydoc -g and !serve have been deprecated in Python 3.2.
re
str regular expressions now support \u and \U escapes.
(Contributed by Serhiy Storchaka in 3665.)
sched
~sched.scheduler.runnow accepts a blocking parameter which when set to false makes the method execute the scheduled events due to expire soonest (if any) and then return immediately. This is useful in case you want to use the~sched.schedulerin non-blocking applications. (Contributed by Giampaolo Rodolà in13449.)~sched.schedulerclass can now be safely used in multi-threaded environments. (Contributed by Josiah Carlson and Giampaolo Rodolà in8684.)- timefunc and delayfunct parameters of
~sched.schedulerclass constructor are now optional and defaults totime.timeandtime.sleeprespectively. (Contributed by Chris Clark in13245.) ~sched.scheduler.enterand~sched.scheduler.enterabsargument parameter is now optional. (Contributed by Chris Clark in13245.)~sched.scheduler.enterand~sched.scheduler.enterabsnow accept a kwargs parameter. (Contributed by Chris Clark in13245.)
select
Solaris and derivative platforms have a new class select.devpoll for high performance asynchronous sockets via /dev/poll. (Contributed by Jesús Cea Avión in 6397.)
shlex
The previously undocumented helper function quote from the !pipes modules has been moved to the shlex module and documented. ~shlex.quote properly escapes all characters in a string that might be otherwise given special meaning by the shell.
shutil
- New functions:
~shutil.disk_usage: provides total, used and free disk space statistics. (Contributed by Giampaolo Rodolà in12442.)~shutil.chown: allows one to change user and/or group of the given path also specifying the user/group names and not only their numeric ids. (Contributed by Sandro Tosi in12191.)shutil.get_terminal_size: returns the size of the terminal window to which the interpreter is attached. (Contributed by Zbigniew Jędrzejewski-Szmek in13609.)
~shutil.copy2and~shutil.copystatnow preserve file timestamps with nanosecond precision on platforms that support it. They also preserve file "extended attributes" on Linux. (Contributed by Larry Hastings in14127and15238.)- Several functions now take an optional
symlinksargument: when that parameter is true, symlinks aren't dereferenced and the operation instead acts on the symlink itself (or creates one, if relevant). (Contributed by Hynek Schlawack in12715.) - When copying files to a different file system,
~shutil.movenow handles symlinks the way the posixmvcommand does, recreating the symlink rather than copying the target file contents. (Contributed by Jonathan Niehof in9993.)~shutil.movenow also returns thedstargument as its result. ~shutil.rmtreeis now resistant to symlink attacks on platforms which support the newdir_fdparameter inos.openandos.unlink. (Contributed by Martin von Löwis and Hynek Schlawack in4489.)
signal
- The
signalmodule has new functions:~signal.pthread_sigmask: fetch and/or change the signal mask of the calling thread (Contributed by Jean-Paul Calderone in8407);~signal.pthread_kill: send a signal to a thread;~signal.sigpending: examine pending functions;~signal.sigwait: wait a signal;~signal.sigwaitinfo: wait for a signal, returning detailed information about it;~signal.sigtimedwait: like~signal.sigwaitinfobut with a timeout.
- The signal handler writes the signal number as a single byte instead of a nul byte into the wakeup file descriptor. So it is possible to wait more than one signal and know which signals were raised.
signal.signalandsignal.siginterruptraise an OSError, instead of a RuntimeError: OSError has an errno attribute.
smtpd
The !smtpd module now supports 5321 (extended SMTP) and 1870 (size extension). Per the standard, these extensions are enabled if and only if the client initiates the session with an EHLO command.
(Initial ELHO support by Alberto Trevino. Size extension by Juhana Jauhiainen. Substantial additional work on the patch contributed by Michele Orrù and Dan Boswell. 8739)
smtplib
The ~smtplib.SMTP, ~smtplib.SMTP_SSL, and ~smtplib.LMTP classes now accept a source_address keyword argument to specify the (host, port) to use as the source address in the bind call when creating the outgoing socket. (Contributed by Paulo Scardine in 11281.)
~smtplib.SMTP now supports the context management protocol, allowing an SMTP instance to be used in a with statement. (Contributed by Giampaolo Rodolà in 11289.)
The ~smtplib.SMTP_SSL constructor and the ~smtplib.SMTP.starttls method now accept an SSLContext parameter to control parameters of the secure channel. (Contributed by Kasun Herath in 8809.)
socket
-
The
~socket.socketclass now exposes additional methods to process ancillary data when supported by the underlying platform:~socket.socket.sendmsg~socket.socket.recvmsg~socket.socket.recvmsg_into
(Contributed by David Watson in
6560, based on an earlier patch by Heiko Wundram) -
The
~socket.socketclass now supports the PF_CAN protocol family (https://en.wikipedia.org/wiki/Socketcan), on Linux (https://lwn.net/Articles/253425).(Contributed by Matthias Fuchs, updated by Tiago Gonçalves in
10141.) -
The
~socket.socketclass now supports the PF_RDS protocol family (https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets and https://oss.oracle.com/projects/rds). -
The
~socket.socketclass now supports thePF_SYSTEMprotocol family on OS X. (Contributed by Michael Goderbauer in13777.) -
New function
~socket.sethostnameallows the hostname to be set on Unix systems if the calling process has sufficient privileges. (Contributed by Ross Lagerwall in10866.)
socketserver
~socketserver.BaseServer now has an overridable method ~socketserver.BaseServer.service_actions that is called by the ~socketserver.BaseServer.serve_forever method in the service loop. ~socketserver.ForkingMixIn now uses this to clean up zombie child processes. (Contributed by Justin Warkentin in 11109.)
sqlite3
New sqlite3.Connection method ~sqlite3.Connection.set_trace_callback can be used to capture a trace of all sql commands processed by sqlite. (Contributed by Torsten Landschoff in 11688.)
ssl
-
The
sslmodule has two new random generation functions:~ssl.RAND_bytes: generate cryptographically strong pseudo-random bytes.!RAND_pseudo_bytes: generate pseudo-random bytes.
(Contributed by Victor Stinner in
12049.) -
The
sslmodule now exposes a finer-grained exception hierarchy in order to make it easier to inspect the various kinds of errors. (Contributed by Antoine Pitrou in11183.) -
~ssl.SSLContext.load_cert_chainnow accepts a password argument to be used if the private key is encrypted. (Contributed by Adam Simpkins in12803.) -
Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is now supported through the
~ssl.SSLContext.load_dh_paramsand~ssl.SSLContext.set_ecdh_curvemethods. (Contributed by Antoine Pitrou in13626and13627.) -
SSL sockets have a new
~ssl.SSLSocket.get_channel_bindingmethod allowing the implementation of certain authentication mechanisms such as SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in12551.) -
You can query the SSL compression algorithm used by an SSL socket, thanks to its new
~ssl.SSLSocket.compressionmethod. The new attribute~ssl.OP_NO_COMPRESSIONcan be used to disable compression. (Contributed by Antoine Pitrou in13634.) -
Support has been added for the Next Protocol Negotiation extension using the
ssl.SSLContext.set_npn_protocolsmethod. (Contributed by Colin Marc in14204.) -
SSL errors can now be introspected more easily thanks to
~ssl.SSLError.libraryand~ssl.SSLError.reasonattributes. (Contributed by Antoine Pitrou in14837.) -
The
~ssl.get_server_certificatefunction now supports IPv6. (Contributed by Charles-François Natali in11811.) -
New attribute
~ssl.OP_CIPHER_SERVER_PREFERENCEallows setting SSLv3 server sockets to use the server's cipher ordering preference rather than the client's (13635).
stat
The undocumented tarfile.filemode function has been moved to stat.filemode. It can be used to convert a file's mode to a string of the form '-rwxrwxrwx'.
(Contributed by Giampaolo Rodolà in 14807.)
struct
The struct module now supports ssize_t and size_t via the new codes n and N, respectively. (Contributed by Antoine Pitrou in 3163.)
subprocess
Command strings can now be bytes objects on posix platforms. (Contributed by Victor Stinner in 8513.)
A new constant ~subprocess.DEVNULL allows suppressing output in a platform-independent fashion. (Contributed by Ross Lagerwall in 5870.)
sys
The sys module has a new ~sys.thread_info named tuple holding information about the thread implementation (11223).
tarfile
tarfile now supports lzma encoding via the lzma module. (Contributed by Lars Gustäbel in 5689.)
tempfile
tempfile.SpooledTemporaryFile's !truncate method now accepts a size parameter. (Contributed by Ryan Kelly in 9957.)
textwrap
The textwrap module has a new ~textwrap.indent that makes it straightforward to add a common prefix to selected lines in a block of text (13857).
threading
threading.Condition, threading.Semaphore, threading.BoundedSemaphore, threading.Event, and threading.Timer, all of which used to be factory functions returning a class instance, are now classes and may be subclassed. (Contributed by Éric Araujo in 10968.)
The threading.Thread constructor now accepts a daemon keyword argument to override the default behavior of inheriting the daemon flag value from the parent thread (6064).
The formerly private function _thread.get_ident is now available as the public function threading.get_ident. This eliminates several cases of direct access to the _thread module in the stdlib. Third party code that used _thread.get_ident should likewise be changed to use the new public interface.
time
The 418 added new functions to the time module:
~time.get_clock_info: Get information on a clock.~time.monotonic: Monotonic clock (cannot go backward), not affected by system clock updates.~time.perf_counter: Performance counter with the highest available resolution to measure a short duration.~time.process_time: Sum of the system and user CPU time of the current process.
Other new functions:
~time.clock_getres,~time.clock_gettimeand~time.clock_settimefunctions withCLOCK_{xxx}constants. (Contributed by Victor Stinner in10278.)
To improve cross platform consistency, ~time.sleep now raises a ValueError when passed a negative sleep value. Previously this was an error on posix, but produced an infinite sleep on Windows.
types
Add a new types.MappingProxyType class: Read-only proxy of a mapping. (14386)
The new functions types.new_class and types.prepare_class provide support for 3115 compliant dynamic type creation. (14588)
unittest
.assertRaises, .assertRaisesRegex, .assertWarns, and .assertWarnsRegex now accept a keyword argument msg when used as context managers. (Contributed by Ezio Melotti and Winston Ewert in 10775.)
unittest.TestCase.run now returns the ~unittest.TestResult object.
urllib
The ~urllib.request.Request class, now accepts a method argument used by ~urllib.request.Request.get_method to determine what HTTP method should be used. For example, this will send a 'HEAD' request:
>>> urlopen(Request('https://www.python.org', method='HEAD'))
(1673007)
webbrowser
The webbrowser module supports more "browsers": Google Chrome (named chrome, chromium, chrome-browser or chromium-browser depending on the version and operating system), and the generic launchers xdg-open, from the FreeDesktop.org project, and gvfs-open, which is the default URI handler for GNOME 3. (The former contributed by Arnaud Calmettes in 13620, the latter by Matthias Klose in 14493.)
xml.etree.ElementTree
The xml.etree.ElementTree module now imports its C accelerator by default; there is no longer a need to explicitly import !xml.etree.cElementTree (this module stays for backwards compatibility, but is now deprecated). In addition, the iter family of methods of ~xml.etree.ElementTree.Element has been optimized (rewritten in C). The module's documentation has also been greatly improved with added examples and a more detailed reference.
zlib
New attribute zlib.Decompress.eof makes it possible to distinguish between a properly formed compressed stream and an incomplete or truncated one. (Contributed by Nadeem Vawda in 12646.)
New attribute zlib.ZLIB_RUNTIME_VERSION reports the version string of the underlying zlib library that is loaded at runtime. (Contributed by Torsten Landschoff in 12306.)
Optimizations
Major performance enhancements have been added:
-
Thanks to
393, some operations on Unicode strings have been optimized:- the memory footprint is divided by 2 to 4 depending on the text
- encode an ASCII string to UTF-8 doesn't need to encode characters anymore, the UTF-8 representation is shared with the ASCII representation
- the UTF-8 encoder has been optimized
- repeating a single ASCII letter and getting a substring of an ASCII string is 4 times faster
-
UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster.
(Contributed by Serhiy Storchaka,
14624,14738and15026.)
Build and C API Changes
Changes to Python's build process and to the C API include:
Deprecated
Unsupported Operating Systems
OS/2 and VMS are no longer supported due to the lack of a maintainer.
Windows 2000 and Windows platforms which set COMSPEC to command.com are no longer supported due to maintenance burden.
OSF support, which was deprecated in 3.2, has been completely removed.
Deprecated Python modules, functions and methods
- Passing a non-empty string to
object.__format__()is deprecated, and will produce aTypeErrorin Python 3.4 (9856). - The
unicode_internalcodec has been deprecated because of the393, use UTF-8, UTF-16 (utf-16-leorutf-16-be), or UTF-32 (utf-32-leorutf-32-be) ftplib.FTP.nlstandftplib.FTP.dir: useftplib.FTP.mlsd!platform.popen: use thesubprocessmodule. Check especially thesubprocess-replacementssection (11377).13374: The Windows bytes API has been deprecated in theosmodule. Use Unicode filenames, instead of bytes filenames, to not depend on the ANSI code page anymore and to support any filename.13988: The!xml.etree.cElementTreemodule is deprecated. The accelerator is used automatically whenever available.- The behaviour of
!time.clockdepends on the platform: use the newtime.perf_counterortime.process_timefunction instead, depending on your requirements, to have a well defined behaviour. - The
!os.stat_float_timesfunction is deprecated. abcmodule:abc.abstractpropertyhas been deprecated, usepropertywithabc.abstractmethodinstead.abc.abstractclassmethodhas been deprecated, useclassmethodwithabc.abstractmethodinstead.abc.abstractstaticmethodhas been deprecated, usestaticmethodwithabc.abstractmethodinstead.
importlibpackage:importlib.abc.SourceLoader.path_mtimeis now deprecated in favour ofimportlib.abc.SourceLoader.path_statsas bytecode files now store both the modification time and size of the source file the bytecode file was compiled from.
Deprecated functions and types of the C API
The Py_UNICODE has been deprecated by 393 and will be removed in Python 4. All functions using this type are deprecated:
Unicode functions and methods using Py_UNICODE and Py_UNICODE* types:
!PyUnicode_FromUnicode: usePyUnicode_FromWideCharorPyUnicode_FromKindAndData!PyUnicode_AS_UNICODE,!PyUnicode_AsUnicode,!PyUnicode_AsUnicodeAndSize: usePyUnicode_AsWideCharString!PyUnicode_AS_DATA: usePyUnicode_DATAwithPyUnicode_READandPyUnicode_WRITE!PyUnicode_GET_SIZE,!PyUnicode_GetSize: usePyUnicode_GET_LENGTHorPyUnicode_GetLength!PyUnicode_GET_DATA_SIZE: usePyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)(only work on ready strings)!PyUnicode_AsUnicodeCopy: usePyUnicode_AsUCS4CopyorPyUnicode_AsWideCharString!PyUnicode_GetMax
Functions and macros manipulating Py_UNICODE* strings:
!Py_UNICODE_strlen(): usePyUnicode_GetLengthorPyUnicode_GET_LENGTH!Py_UNICODE_strcat(): usePyUnicode_CopyCharactersorPyUnicode_FromFormat!Py_UNICODE_strcpy(),!Py_UNICODE_strncpy(),!Py_UNICODE_COPY(): usePyUnicode_CopyCharactersorPyUnicode_Substring!Py_UNICODE_strcmp(): usePyUnicode_Compare!Py_UNICODE_strncmp(): usePyUnicode_Tailmatch!Py_UNICODE_strchr(),!Py_UNICODE_strrchr(): usePyUnicode_FindChar!Py_UNICODE_FILL(): usePyUnicode_Fill!Py_UNICODE_MATCH
Encoders:
!PyUnicode_Encode: use!PyUnicode_AsEncodedObject!PyUnicode_EncodeUTF7!PyUnicode_EncodeUTF8: usePyUnicode_AsUTF8orPyUnicode_AsUTF8String!PyUnicode_EncodeUTF32!PyUnicode_EncodeUTF16!PyUnicode_EncodeUnicodeEscapeusePyUnicode_AsUnicodeEscapeString!PyUnicode_EncodeRawUnicodeEscapeusePyUnicode_AsRawUnicodeEscapeString!PyUnicode_EncodeLatin1: usePyUnicode_AsLatin1String!PyUnicode_EncodeASCII: usePyUnicode_AsASCIIString!PyUnicode_EncodeCharmap!PyUnicode_TranslateCharmap!PyUnicode_EncodeMBCS: usePyUnicode_AsMBCSStringorPyUnicode_EncodeCodePage(withCP_ACPcode_page)!PyUnicode_EncodeDecimal,!PyUnicode_TransformDecimalToASCII
Deprecated features
The array module's 'u' format code is now deprecated and will be removed in Python 4 together with the rest of the (Py_UNICODE) API.
Porting to Python 3.3
This section lists previously described changes and other bugfixes that may require changes to your code.
Porting Python code
- Hash randomization is enabled by default. Set the
PYTHONHASHSEEDenvironment variable to0to disable hash randomization. See also theobject.__hash__method. 12326: On Linux, sys.platform doesn't contain the major version anymore. It is now always 'linux', instead of 'linux2' or 'linux3' depending on the Linux version used to build Python. Replace sys.platform == 'linux2' with sys.platform.startswith('linux'), or directly sys.platform == 'linux' if you don't need to support older Python versions.13847,14180:timeanddatetime:OverflowErroris now raised instead ofValueErrorif a timestamp is out of range.OSErroris now raised if C functionsgmtimeorlocaltimefailed.- The default finders used by import now utilize a cache of what is contained within a specific directory. If you create a Python source file or sourceless bytecode file, make sure to call
importlib.invalidate_cachesto clear out the cache for the finders to notice the new file. ImportErrornow uses the full name of the module that was attempted to be imported. Doctests that check ImportErrors' message will need to be updated to use the full name of the module instead of just the tail of the name.- The index argument to
__import__now defaults to 0 instead of -1 and no longer support negative values. It was an oversight when328was implemented that the default value remained -1. If you need to continue to perform a relative import followed by an absolute import, then perform the relative import using an index of 1, followed by another import using an index of 0. It is preferred, though, that you useimportlib.import_modulerather than call__import__directly. __import__no longer allows one to use an index value other than 0 for top-level modules. E.g.__import__('sys', level=1)is now an error.- Because
sys.meta_pathandsys.path_hooksnow have finders on them by default, you will most likely want to uselist.insertinstead oflist.appendto add to those lists. - Because
Noneis now inserted intosys.path_importer_cache, if you are clearing out entries in the dictionary of paths that do not have a finder, you will need to remove keys paired with values ofNoneand!imp.NullImporterto be backwards-compatible. This will lead to extra overhead on older versions of Python that re-insertNoneintosys.path_importer_cachewhere it represents the use of implicit finders, but semantically it should not change anything. !importlib.abc.Finderno longer specifies afind_module()abstract method that must be implemented. If you were relying on subclasses to implement that method, make sure to check for the method's existence first. You will probably want to check forfind_loader()first, though, in the case of working withpath entry finders <path entry finder>.pkgutilhas been converted to useimportlibinternally. This eliminates many edge cases where the old behaviour of the302import emulation failed to match the behaviour of the real import system. The import emulation itself is still present, but is now deprecated. Thepkgutil.iter_importersandpkgutil.walk_packagesfunctions special case the standard import hooks so they are still supported even though they do not provide the non-standarditer_modules()method.- A longstanding RFC-compliance bug (
1079) in the parsing done byemail.header.decode_headerhas been fixed. Code that uses the standard idiom to convert encoded headers into unicode (str(make_header(decode_header(h))) will see no change, but code that looks at the individual tuples returned by decode_header will see that whitespace that precedes or followsASCIIsections is now included in theASCIIsection. Code that builds headers usingmake_headershould also continue to work without change, sincemake_headercontinues to add whitespace betweenASCIIand non-ASCIIsections if it is not already present in the input strings. email.utils.formataddrnow does the correct content transfer encoding when passed non-ASCIIdisplay names. Any code that depended on the previous buggy behavior that preserved the non-ASCIIunicode in the formatted output string will need to be changed (1690608).poplib.POP3.quitmay now raise protocol errors like all otherpoplibmethods. Code that assumesquitdoes not raisepoplib.error_protoerrors may need to be changed if errors onquitare encountered by a particular application (11291).- The
strictargument toemail.parser.Parser, deprecated since Python 2.4, has finally been removed. - The deprecated method
unittest.TestCase.assertSameElementshas been removed. - The deprecated variable
time.accept2dyearhas been removed. - The deprecated
Context._clampattribute has been removed from thedecimalmodule. It was previously replaced by the public attribute~decimal.Context.clamp. (See8540.) - The undocumented internal helper class
SSLFakeFilehas been removed fromsmtplib, since its functionality has long been provided directly bysocket.socket.makefile. - Passing a negative value to
time.sleepon Windows now raises an error instead of sleeping forever. It has always raised an error on posix. - The
ast.__version__constant has been removed. If you need to make decisions affected by the AST version, usesys.version_infoto make the decision. - Code that used to work around the fact that the
threadingmodule used factory functions by subclassing the private classes will need to change to subclass the now-public classes. - The undocumented debugging machinery in the threading module has been removed, simplifying the code. This should have no effect on production code, but is mentioned here in case any application debug frameworks were interacting with it (
13550).
Porting C code
-
In the course of changes to the buffer API the undocumented
!smalltablemember of thePy_bufferstructure has been removed and the layout of the!PyMemoryViewObjecthas changed.All extensions relying on the relevant parts in
memoryobject.horobject.hmust be rebuilt. -
Due to
PEP 393 <pep-393>, thePy_UNICODEtype and all functions using this type are deprecated (but will stay available for at least five years). If you were using low-level Unicode APIs to construct and access unicode objects and you want to benefit of the memory footprint reduction provided by393, you have to convert your code to the newUnicode API <../c-api/unicode>.However, if you only have been using high-level functions such as
PyUnicode_Concat(),PyUnicode_JoinorPyUnicode_FromFormat(), your code will automatically take advantage of the new unicode representations. -
PyImport_GetMagicNumbernow returns-1upon failure. -
As a negative value for the level argument to
__import__is no longer valid, the same now holds forPyImport_ImportModuleLevel. This also means that the value of level used byPyImport_ImportModuleExis now0instead of-1.
Building C extensions
-
The range of possible file names for C extensions has been narrowed. Very rarely used spellings have been suppressed: under POSIX, files named
xxxmodule.so,xxxmodule.abi3.soandxxxmodule.cpython-*.soare no longer recognized as implementing thexxxmodule. If you had been generating such files, you have to switch to the other spellings (i.e., remove themodulestring from the file names).(implemented in
14040.)
Command Line Switch Changes
-
The -Q command-line flag and related artifacts have been removed. Code checking sys.flags.division_warning will need updating.
(
10998, contributed by Éric Araujo.) -
When
pythonis started with-S,import sitewill no longer add site-specific paths to the module search paths. In previous versions, it did.(
11591, contributed by Carl Meyer with editions by Éric Araujo.)
What's New In Python 3.4
* Anyone can add text to this document, but the maintainer reserves the right to rewrite any additions. In particular, for obscure or esoteric features, the maintainer may reduce any addition to a simple reference to the new documentation rather than explaining the feature inline.
* While the maintainer will periodically go through Misc/NEWS and add changes, it's best not to rely on this. We know from experience that any changes that aren't in the What's New documentation around the time of the original release will remain largely unknown to the community for years, even if they're added later. We also know from experience that other priorities can arise, and the maintainer will run out of time to do updates -- in such cases, end users will be much better served by partial notifications that at least give a hint about new features to investigate.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. The What's New should focus on changes that are visible to Python users and that require a feature release (i.e. most bug fixes should only be recorded in Misc/NEWS)
* PEPs should not be marked Final until they have an entry in What's New. A placeholder entry that is just a section header and a link to the PEP (e.g "
397has been implemented") is acceptable. If a PEP has been implemented and noted in What's New, don't forget to mark it as Final!* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to add just a very brief note about a change. For example: "The
~socket.transmogrify()function was added to thesocketmodule." The maintainer will research the change and write the necessary text (if appropriate). The advantage of doing this is that even if no more descriptive text is ever added, readers will at least have a notification that the new feature exists and a link to the relevant documentation.* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
The
~socket.transmogrify()function was added to thesocketmodule. (Contributed by P.Y. Developer in12345.)This saves the maintainer the effort of going through the Mercurial log when researching a change.
* Cross referencing tip:
mod.attrwill display asmod.attr, while~mod.attrwill display asattr.
This article explains the new features in Python 3.4, compared to 3.3. Python 3.4 was released on March 16, 2014. For full details, see the changelog.
429 -- Python 3.4 Release Schedule
Summary -- Release Highlights
New syntax features:
- No new syntax features were added in Python 3.4.
Other new features:
pip should always be available <whatsnew-pep-453>(453).Newly created file descriptors are non-inheritable <whatsnew-pep-446>(446).- command line option for
isolated mode <whatsnew-isolated-mode>(16499). improvements in the handling of codecs <codec-handling-improvements>that are not text encodings (multiple issues).A ModuleSpec Type <whatsnew-pep-451>for the Import System (451). (Affects importer authors.)- The
marshalformat has been mademore compact and efficient <whatsnew-marshal-3>(16475).
New library modules:
asyncio:New provisional API for asynchronous IO <whatsnew-asyncio>(3156).ensurepip:Bootstrapping the pip installer <whatsnew-ensurepip>(453).enum:Support for enumeration types <whatsnew-enum>(435).pathlib:Object-oriented filesystem paths <whatsnew-pathlib>(428).selectors:High-level and efficient I/O multiplexing <whatsnew-selectors>, built upon theselectmodule primitives (part of3156).statistics: A basicnumerically stable statistics library <whatsnew-statistics>(450).tracemalloc:Trace Python memory allocations <whatsnew-tracemalloc>(454).
Significantly improved library modules:
Single-dispatch generic functions <whatsnew-singledispatch>infunctools(443).- New
pickleprotocol 4 <whatsnew-protocol-4>(3154). multiprocessingnow hasan option to avoid using os.fork on Unix <whatsnew-multiprocessing-no-fork>(8713).emailhas a new submodule,~email.contentmanager, and a new~email.message.Messagesubclass (~email.message.EmailMessage) thatsimplify MIME handling <whatsnew_email_contentmanager>(18891).- The
inspectandpydocmodules are now capable of correct introspection of a much wider variety of callable objects, which improves the output of the Pythonhelpsystem. - The
ipaddressmodule API has been declared stable
Security improvements:
Secure and interchangeable hash algorithm <whatsnew-pep-456>(456).Make newly created file descriptors non-inheritable <whatsnew-pep-446>(446) to avoid leaking file descriptors to child processes.- New command line option for
isolated mode <whatsnew-isolated-mode>, (16499). multiprocessingnow hasan option to avoid using os.fork on Unix <whatsnew-multiprocessing-no-fork>. spawn and forkserver are more secure because they avoid sharing data with child processes.multiprocessingchild processes on Windows no longer inherit all of the parent's inheritable handles, only the necessary ones.- A new
hashlib.pbkdf2_hmacfunction provides the PKCS#5 password-based key derivation function 2. TLSv1.1 and TLSv1.2 support <whatsnew-tls-11-12>forssl.Retrieving certificates from the Windows system cert store support <whatsnew34-win-cert-store>forssl.Server-side SNI (Server Name Indication) support <whatsnew34-sni>forssl.- The
ssl.SSLContextclass has alot of improvements <whatsnew34-sslcontext>. - All modules in the standard library that support SSL now support server certificate verification, including hostname matching (
!ssl.match_hostname) and CRLs (Certificate Revocation lists, seessl.SSLContext.load_verify_locations).
CPython implementation improvements:
Safe object finalization <whatsnew-pep-442>(442).- Leveraging
442, in most casesmodule globals are no longer set to None during finalization <whatsnew-pep-442>(18214). Configurable memory allocators <whatsnew-pep-445>(445).Argument Clinic <whatsnew-pep-436>(436).
Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.
New Features
PEP 453: Explicit Bootstrapping of PIP in Python Installations
Bootstrapping pip By Default
The new ensurepip module (defined in 453) provides a standard cross-platform mechanism to bootstrap the pip installer into Python installations and virtual environments. The version of pip included with Python 3.4.0 is pip 1.5.4, and future 3.4.x maintenance releases will update the bundled version to the latest version of pip that is available at the time of creating the release candidate.
By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies. On Windows and in virtual environments on all platforms, the unversioned pip command will also be installed. On other platforms, the system wide unversioned pip command typically refers to the separately installed Python 2 version.
The pyvenv command line utility and the venv module make use of the ensurepip module to make pip readily available in virtual environments. When using the command line utility, pip is installed by default, while when using the venv module venv-api installation of pip must be requested explicitly.
For CPython source builds on POSIX systems <building-python-on-unix>, the make install and make altinstall commands bootstrap pip by default. This behaviour can be controlled through configure options, and overridden through Makefile options.
On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip.
As discussed in the PEP <0453#recommendations-for-downstream-distributors> platform packagers may choose not to install these commands by default, as long as, when invoked, they provide clear and simple directions on how to install them on that platform (usually using the system package manager).
[!NOTE] To avoid conflicts between parallel Python 2 and Python 3 installations, only the versioned
pip3andpip3.4commands are bootstrapped by default whenensurepipis invoked directly - the--default-pipoption is needed to also request the unversionedpipcommand.pyvenvand the Windows installer ensure that the unqualifiedpipcommand is made available in those environments, andpipcan always be invoked via the-mswitch rather than directly to avoid ambiguity on systems with multiple Python installations.
Documentation Changes
As part of this change, the installing-index and distributing-index sections of the documentation have been completely redesigned as short getting started and FAQ documents. Most packaging documentation has now been moved out to the Python Packaging Authority maintained Python Packaging User Guide and the documentation of the individual projects.
However, as this migration is currently still incomplete, the legacy versions of those guides remaining available as install-index and setuptools-index.
453 -- Explicit bootstrapping of pip in Python installations
PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.
PEP 446: Newly Created File Descriptors Are Non-Inheritable
446 makes newly created file descriptors non-inheritable <fd_inheritance>. In general, this is the behavior an application will want: when launching a new process, having currently open files also open in the new process can lead to all sorts of hard to find bugs, and potentially to security issues.
However, there are occasions when inheritance is desired. To support these cases, the following new functions and methods are available:
os.get_inheritable,os.set_inheritableos.get_handle_inheritable,os.set_handle_inheritablesocket.socket.get_inheritable,socket.socket.set_inheritable
446 -- Make newly created file descriptors non-inheritable
PEP written and implemented by Victor Stinner.
Improvements to Codec Handling
Since it was first introduced, the codecs module has always been intended to operate as a type-neutral dynamic encoding and decoding system. However, its close coupling with the Python text model, especially the type restricted convenience methods on the builtin str, bytes and bytearray types, has historically obscured that fact.
As a key step in clarifying the situation, the codecs.encode and codecs.decode convenience functions are now properly documented in Python 2.7, 3.3 and 3.4. These functions have existed in the codecs module (and have been covered by the regression test suite) since Python 2.4, but were previously only discoverable through runtime introspection.
Unlike the convenience methods on str, bytes and bytearray, the codecs convenience functions support arbitrary codecs in both Python 2 and Python 3, rather than being limited to Unicode text encodings (in Python 3) or basestring <-> basestring conversions (in Python 2).
In Python 3.4, the interpreter is able to identify the known non-text encodings provided in the standard library and direct users towards these general purpose convenience functions when appropriate:
>>> b"abcdef".decode("hex")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
>>> "hello".encode("rot13")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>> open("foo.txt", encoding="hex")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs
>>> import codecs
>>> codecs.decode(b"abcdefgh", "hex")
Traceback (most recent call last):
File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)
>>> codecs.encode("hello", "bz2")
Traceback (most recent call last):
File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
return (bz2.compress(input), len(input))
File "/usr/lib/python3.4/bz2.py", line 498, in compress
return comp.compress(data) + comp.flush()
TypeError: 'str' does not support the buffer interface
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)
Finally, as the examples above show, these improvements have permitted the restoration of the convenience aliases for the non-Unicode codecs that were themselves restored in Python 3.2. This means that encoding binary data to and from its hexadecimal representation (for example) can now be written as:
>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'
The binary and text transforms provided in the standard library are detailed in binary-transforms and text-transforms.
(Contributed by Nick Coghlan in 7475, 17827, 17828 and 19619.)
PEP 451: A ModuleSpec Type for the Import System
451 provides an encapsulation of the information about a module that the import machinery will use to load it (that is, a module specification). This helps simplify both the import implementation and several import-related APIs. The change is also a stepping stone for several future import-related improvements.
The public-facing changes from the PEP are entirely backward-compatible. Furthermore, they should be transparent to everyone but importer authors. Key finder and loader methods have been deprecated, but they will continue working. New importers should use the new methods described in the PEP. Existing importers should be updated to implement the new methods. See the deprecated-3.4 section for a list of methods that should be replaced and their replacements.
Other Language Changes
Some smaller changes made to the core Python language are:
- Unicode database updated to UCD version 6.3.
minandmaxnow accept a default keyword-only argument that can be used to specify the value they return if the iterable they are evaluating has no elements. (Contributed by Julian Berman in18111.)- Module objects are now
weakly referenceable <mod-weakref>. - Module
__file__attributes (and related values) should now always contain absolute paths by default, with the sole exception of__main__.__file__when a script has been executed directly using a relative path. (Contributed by Brett Cannon in18416.) - All the UTF-* codecs (except UTF-7) now reject surrogates during both encoding and decoding unless the
surrogatepasserror handler is used, with the exception of the UTF-16 decoder (which accepts valid surrogate pairs) and the UTF-16 encoder (which produces them while encoding non-BMP characters). (Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in12892.) - New German EBCDIC
codec <standard-encodings>cp273. (Contributed by Michael Bierenfeld and Andrew Kuchling in1097797.) - New Ukrainian
codec <standard-encodings>cp1125. (Contributed by Serhiy Storchaka in19668.) bytes.join() andbytearray.join() now accept arbitrary buffer objects as arguments. (Contributed by Antoine Pitrou in15958.)- The
intconstructor now accepts any object that has an__index__method for its base argument. (Contributed by Mark Dickinson in16772.) - Frame objects now have a
~frame.clearmethod that clears all references to local variables from the frame. (Contributed by Antoine Pitrou in17934.) memoryviewis now registered as a~collections.abc.Sequence, and supports thereversedbuiltin. (Contributed by Nick Coghlan and Claudiu Popa in18690and19078.)- Signatures reported by
helphave been modified and improved in several cases as a result of the introduction of Argument Clinic and other changes to theinspectandpydocmodules. ~object.__length_hint__is now part of the formal language specification (see424). (Contributed by Armin Ronacher in16148.)
New Modules
asyncio
The new asyncio module (defined in 3156) provides a standard pluggable event loop model for Python, providing solid asynchronous IO support in the standard library, and making it easier for other event loop implementations to interoperate with the standard library and each other.
For Python 3.4, this module is considered a provisional API.
3156 -- Asynchronous IO Support Rebooted: the "asyncio" Module
PEP written and implementation led by Guido van Rossum.
ensurepip
The new ensurepip module is the primary infrastructure for the 453 implementation. In the normal course of events end users will not need to interact with this module, but it can be used to manually bootstrap pip if the automated bootstrapping into an installation or virtual environment was declined.
ensurepip includes a bundled copy of pip, up-to-date as of the first release candidate of the release of CPython with which it ships (this applies to both maintenance releases and feature releases). ensurepip does not access the internet. If the installation has internet access, after ensurepip is run the bundled pip can be used to upgrade pip to a more recent release than the bundled one. (Note that such an upgraded version of pip is considered to be a separately installed package and will not be removed if Python is uninstalled.)
The module is named ensurepip because if called when pip is already installed, it does nothing. It also has an --upgrade option that will cause it to install the bundled copy of pip if the existing installed version of pip is older than the bundled copy.
enum
The new enum module (defined in 435) provides a standard implementation of enumeration types, allowing other modules (such as socket) to provide more informative error messages and better debugging support by replacing opaque integer constants with backwards compatible enumeration values.
435 -- Adding an Enum type to the Python standard library
PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman, implemented by Ethan Furman.
pathlib
The new pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.
For Python 3.4, this module is considered a provisional API.
428 -- The pathlib module -- object-oriented filesystem paths
PEP written and implemented by Antoine Pitrou.
selectors
The new selectors module (created as part of implementing 3156) allows high-level and efficient I/O multiplexing, built upon the select module primitives.
statistics
The new statistics module (defined in 450) offers some core statistics functionality directly in the standard library. This module supports calculation of the mean, median, mode, variance and standard deviation of a data series.
450 -- Adding A Statistics Module To The Standard Library
PEP written and implemented by Steven D'Aprano
tracemalloc
The new tracemalloc module (defined in 454) is a debug tool to trace memory blocks allocated by Python. It provides the following information:
- Trace where an object was allocated
- Statistics on allocated memory blocks per filename and per line number: total size, number and average size of allocated memory blocks
- Compute the differences between two snapshots to detect memory leaks
454 -- Add a new tracemalloc module to trace Python memory allocations
PEP written and implemented by Victor Stinner
Improved Modules
abc
New function abc.get_cache_token can be used to know when to invalidate caches that are affected by changes in the object graph. (Contributed by Łukasz Langa in 16832.)
New class ~abc.ABC has ~abc.ABCMeta as its meta class. Using ABC as a base class has essentially the same effect as specifying metaclass=abc.ABCMeta, but is simpler to type and easier to read. (Contributed by Bruno Dupuis in 16049.)
aifc
The !getparams method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in 17818.)
!aifc.open now supports the context management protocol: when used in a with block, the !close method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchacha in 16486.)
The !writeframesraw and !writeframes methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in 8311.)
argparse
The ~argparse.FileType class now accepts encoding and errors arguments, which are passed through to open. (Contributed by Lucas Maystre in 11175.)
audioop
!audioop now supports 24-bit samples. (Contributed by Serhiy Storchaka in 12866.)
New !byteswap function converts big-endian samples to little-endian and vice versa. (Contributed by Serhiy Storchaka in 19641.)
All !audioop functions now accept any bytes-like object. Strings are not accepted: they didn't work before, now they raise an error right away. (Contributed by Serhiy Storchaka in 16685.)
base64
The encoding and decoding functions in base64 now accept any bytes-like object in cases where it previously required a bytes or bytearray instance. (Contributed by Nick Coghlan in 17839.)
New functions ~base64.a85encode, ~base64.a85decode, ~base64.b85encode, and ~base64.b85decode provide the ability to encode and decode binary data from and to Ascii85 and the git/mercurial Base85 formats, respectively. The a85 functions have options that can be used to make them compatible with the variants of the Ascii85 encoding, including the Adobe variant. (Contributed by Martin Morrison, the Mercurial project, Serhiy Storchaka, and Antoine Pitrou in 17618.)
collections
The .ChainMap.new_child method now accepts an m argument specifying the child map to add to the chain. This allows an existing mapping and/or a custom mapping type to be used for the child. (Contributed by Vinay Sajip in 16613.)
colorsys
The number of digits in the coefficients for the RGB --- YIQ conversions have been expanded so that they match the FCC NTSC versions. The change in results should be less than 1% and may better match results found elsewhere. (Contributed by Brian Landers and Serhiy Storchaka in 14323.)
contextlib
The new contextlib.suppress context manager helps to clarify the intent of code that deliberately suppresses exceptions from a single statement. (Contributed by Raymond Hettinger in 15806 and Zero Piraeus in 19266.)
The new contextlib.redirect_stdout context manager makes it easier for utility scripts to handle inflexible APIs that write their output to sys.stdout and don't provide any options to redirect it. Using the context manager, the sys.stdout output can be redirected to any other stream or, in conjunction with io.StringIO, to a string. The latter can be especially useful, for example, to capture output from a function that was written to implement a command line interface. It is recommended only for utility scripts because it affects the global state of sys.stdout. (Contributed by Raymond Hettinger in 15805.)
The contextlib documentation has also been updated to include a discussion <single-use-reusable-and-reentrant-cms> of the differences between single use, reusable and reentrant context managers.
dbm
dbm.open objects now support the context management protocol. When used in a with statement, the close method of the database object will be called automatically at the end of the block. (Contributed by Claudiu Popa and Nick Coghlan in 19282.)
dis
Functions ~dis.show_code, ~dis.dis, ~dis.distb, and ~dis.disassemble now accept a keyword-only file argument that controls where they write their output.
The dis module is now built around an ~dis.Instruction class that provides object oriented access to the details of each individual bytecode operation.
A new method, ~dis.get_instructions, provides an iterator that emits the Instruction stream for a given piece of Python code. Thus it is now possible to write a program that inspects and manipulates a bytecode object in ways different from those provided by the ~dis module itself. For example:
>>> import dis
>>> for instr in dis.get_instructions(lambda x: x + 1):
... print(instr.opname)
LOAD_FAST
LOAD_CONST
BINARY_ADD
RETURN_VALUE
The various display tools in the dis module have been rewritten to use these new components.
In addition, a new application-friendly class ~dis.Bytecode provides an object-oriented API for inspecting bytecode in both in human-readable form and for iterating over instructions. The ~dis.Bytecode constructor takes the same arguments that ~dis.get_instructions does (plus an optional current_offset), and the resulting object can be iterated to produce ~dis.Instruction objects. But it also has a ~dis.Bytecode.dis method, equivalent to calling ~dis.dis on the constructor argument, but returned as a multi-line string:
>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
>>> for instr in bytecode:
... print('{} ({})'.format(instr.opname, instr.opcode))
LOAD_FAST (124)
LOAD_CONST (100)
BINARY_ADD (23)
RETURN_VALUE (83)
>>> bytecode.dis().splitlines() # doctest: +NORMALIZE_WHITESPACE
[' 1 0 LOAD_FAST 0 (x)',
' --> 3 LOAD_CONST 1 (1)',
' 6 BINARY_ADD',
' 7 RETURN_VALUE']
~dis.Bytecode also has a class method, ~dis.Bytecode.from_traceback, that provides the ability to manipulate a traceback (that is, print(Bytecode.from_traceback(tb).dis()) is equivalent to distb(tb)).
(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in 11816 and Claudiu Popa in 17916.)
New function ~dis.stack_effect computes the effect on the Python stack of a given opcode and argument, information that is not otherwise available. (Contributed by Larry Hastings in 19722.)
doctest
A new option flag <doctest-options>, ~doctest.FAIL_FAST, halts test running as soon as the first failure is detected. (Contributed by R. David Murray and Daniel Urban in 16522.)
The doctest command line interface now uses argparse, and has two new options, -o and -f. -o allows doctest options <doctest-options> to be specified on the command line, and -f is a shorthand for -o FAIL_FAST (to parallel the similar option supported by the unittest CLI). (Contributed by R. David Murray in 11390.)
doctest will now find doctests in extension module __doc__ strings. (Contributed by Zachary Ware in 3158.)
~email.message.Message.as_string now accepts a policy argument to override the default policy of the message when generating a string representation of it. This means that as_string can now be used in more circumstances, instead of having to create and use a ~email.generator in order to pass formatting parameters to its flatten method. (Contributed by R. David Murray in 18600.)
New method ~email.message.Message.as_bytes added to produce a bytes representation of the message in a fashion similar to how as_string produces a string representation. It does not accept the maxheaderlen argument, but does accept the unixfrom and policy arguments. The ~email.message.Message ~email.message.Message.__bytes__ method calls it, meaning that bytes(mymsg) will now produce the intuitive result: a bytes object containing the fully formatted message. (Contributed by R. David Murray in 18600.)
The .Message.set_param message now accepts a replace keyword argument. When specified, the associated header will be updated without changing its location in the list of headers. For backward compatibility, the default is False. (Contributed by R. David Murray in 18891.)
A pair of new subclasses of ~email.message.Message have been added (.EmailMessage and .MIMEPart), along with a new sub-module, ~email.contentmanager and a new ~email.policy attribute ~email.policy.EmailPolicy.content_manager. All documentation is currently in the new module, which is being added as part of email's new provisional API. These classes provide a number of new methods that make extracting content from and inserting content into email messages much easier. For details, see the ~email.contentmanager documentation and the email-examples. These API additions complete the bulk of the work that was planned as part of the email6 project. The currently provisional API is scheduled to become final in Python 3.5 (possibly with a few minor additions in the area of error handling). (Contributed by R. David Murray in 18891.)
filecmp
A new ~filecmp.clear_cache function provides the ability to clear the filecmp comparison cache, which uses os.stat information to determine if the file has changed since the last compare. This can be used, for example, if the file might have been changed and re-checked in less time than the resolution of a particular filesystem's file modification time field. (Contributed by Mark Levitt in 18149.)
New module attribute ~filecmp.DEFAULT_IGNORES provides the list of directories that are used as the default value for the ignore parameter of the ~filecmp.dircmp function. (Contributed by Eli Bendersky in 15442.)
functools
The new ~functools.partialmethod descriptor brings partial argument application to descriptors, just as ~functools.partial provides for normal callables. The new descriptor also makes it easier to get arbitrary callables (including ~functools.partial instances) to behave like normal instance methods when included in a class definition. (Contributed by Alon Horev and Nick Coghlan in 4331.)
The new ~functools.singledispatch decorator brings support for single-dispatch generic functions to the Python standard library. Where object oriented programming focuses on grouping multiple operations on a common set of data into a class, a generic function focuses on grouping multiple implementations of an operation that allows it to work with different kinds of data.
443 -- Single-dispatch generic functions
PEP written and implemented by Łukasz Langa.
~functools.total_ordering now supports a return value of NotImplemented from the underlying comparison function. (Contributed by Katie Miller in 10042.)
A pure-python version of the ~functools.partial function is now in the stdlib; in CPython it is overridden by the C accelerated version, but it is available for other implementations to use. (Contributed by Brian Thorne in 12428.)
gc
New function ~gc.get_stats returns a list of three per-generation dictionaries containing the collections statistics since interpreter startup. (Contributed by Antoine Pitrou in 16351.)
glob
A new function ~glob.escape provides a way to escape special characters in a filename so that they do not become part of the globbing expansion but are instead matched literally. (Contributed by Serhiy Storchaka in 8402.)
hashlib
A new hashlib.pbkdf2_hmac function provides the PKCS#5 password-based key derivation function 2. (Contributed by Christian Heimes in 18582.)
The ~hashlib.hash.name attribute of hashlib hash objects is now a formally supported interface. It has always existed in CPython's hashlib (although it did not return lower case names for all supported hashes), but it was not a public interface and so some other Python implementations have not previously supported it. (Contributed by Jason R. Coombs in 18532.)
hmac
hmac now accepts bytearray as well as bytes for the key argument to the ~hmac.new function, and the msg parameter to both the ~hmac.new function and the ~hmac.HMAC.update method now accepts any type supported by the hashlib module. (Contributed by Jonas Borgström in 18240.)
The digestmod argument to the hmac.new function may now be any hash digest name recognized by hashlib. In addition, the current behavior in which the value of digestmod defaults to MD5 is deprecated: in a future version of Python there will be no default value. (Contributed by Christian Heimes in 17276.)
With the addition of ~hmac.HMAC.block_size and ~hmac.HMAC.name attributes (and the formal documentation of the ~hmac.HMAC.digest_size attribute), the hmac module now conforms fully to the 247 API. (Contributed by Christian Heimes in 18775.)
html
New function ~html.unescape function converts HTML5 character references to the corresponding Unicode characters. (Contributed by Ezio Melotti in 2927.)
~html.parser.HTMLParser accepts a new keyword argument convert_charrefs that, when True, automatically converts all character references. For backward-compatibility, its value defaults to False, but it will change to True in a future version of Python, so you are invited to set it explicitly and update your code to use this new feature. (Contributed by Ezio Melotti in 13633.)
The strict argument of ~html.parser.HTMLParser is now deprecated. (Contributed by Ezio Melotti in 15114.)
http
~http.server.BaseHTTPRequestHandler.send_error now accepts an optional additional explain parameter which can be used to provide an extended error description, overriding the hardcoded default if there is one. This extended error description will be formatted using the ~http.server.BaseHTTPRequestHandler.error_message_format attribute and sent as the body of the error response. (Contributed by Karl Cow in 12921.)
The http.server command line interface <http-server-cli> now has a -b/--bind option that causes the server to listen on a specific address. (Contributed by Malte Swart in 17764.)
idlelib and IDLE
Since idlelib implements the IDLE shell and editor and is not intended for import by other programs, it gets improvements with every release. See Lib/idlelib/NEWS.txt for a cumulative list of changes since 3.3.0, as well as changes made in future 3.4.x releases. This file is also available from the IDLE Help --> About IDLE dialog.
importlib
The ~importlib.abc.InspectLoader ABC defines a new method, ~importlib.abc.InspectLoader.source_to_code that accepts source data and a path and returns a code object. The default implementation is equivalent to compile(data, path, 'exec', dont_inherit=True). (Contributed by Eric Snow and Brett Cannon in 15627.)
~importlib.abc.InspectLoader also now has a default implementation for the ~importlib.abc.InspectLoader.get_code method. However, it will normally be desirable to override the default implementation for performance reasons. (Contributed by Brett Cannon in 18072.)
The ~importlib.reload function has been moved from !imp to importlib as part of the !imp module deprecation. (Contributed by Berker Peksag in 18193.)
importlib.util now has a ~importlib.util.MAGIC_NUMBER attribute providing access to the bytecode version number. This replaces the !get_magic function in the deprecated !imp module. (Contributed by Brett Cannon in 18192.)
New importlib.util functions ~importlib.util.cache_from_source and ~importlib.util.source_from_cache replace the same-named functions in the deprecated !imp module. (Contributed by Brett Cannon in 18194.)
The importlib bootstrap .NamespaceLoader now conforms to the .InspectLoader ABC, which means that runpy and python -m can now be used with namespace packages. (Contributed by Brett Cannon in 18058.)
importlib.util has a new function ~importlib.util.decode_source that decodes source from bytes using universal newline processing. This is useful for implementing .InspectLoader.get_source methods.
importlib.machinery.ExtensionFileLoader now has a ~importlib.machinery.ExtensionFileLoader.get_filename method. This was inadvertently omitted in the original implementation. (Contributed by Eric Snow in 19152.)
inspect
The inspect module now offers a basic command line interface <inspect-module-cli> to quickly display source code and other information for modules, classes and functions. (Contributed by Claudiu Popa and Nick Coghlan in 18626.)
~inspect.unwrap makes it easy to unravel wrapper function chains created by functools.wraps (and any other API that sets the __wrapped__ attribute on a wrapper function). (Contributed by Daniel Urban, Aaron Iles and Nick Coghlan in 13266.)
As part of the implementation of the new enum module, the inspect module now has substantially better support for custom __dir__ methods and dynamic class attributes provided through metaclasses. (Contributed by Ethan Furman in 18929 and 19030.)
~inspect.getfullargspec and !getargspec now use the ~inspect.signature API. This allows them to support a much broader range of callables, including those with __signature__ attributes, those with metadata provided by argument clinic, functools.partial objects and more. Note that, unlike ~inspect.signature, these functions still ignore __wrapped__ attributes, and report the already bound first argument for bound methods, so it is still necessary to update your code to use ~inspect.signature directly if those features are desired. (Contributed by Yury Selivanov in 17481.)
~inspect.signature now supports duck types of CPython functions, which adds support for functions compiled with Cython. (Contributed by Stefan Behnel and Yury Selivanov in 17159.)
ipaddress
ipaddress was added to the standard library in Python 3.3 as a provisional API. With the release of Python 3.4, this qualification has been removed: ipaddress is now considered a stable API, covered by the normal standard library requirements to maintain backwards compatibility.
A new ~ipaddress.IPv4Address.is_global property is True if an address is globally routeable. (Contributed by Peter Moody in 17400.)
logging
The ~logging.handlers.TimedRotatingFileHandler has a new atTime parameter that can be used to specify the time of day when rollover should happen. (Contributed by Ronald Oussoren in 9556.)
~logging.handlers.SocketHandler and ~logging.handlers.DatagramHandler now support Unix domain sockets (by setting port to None). (Contributed by Vinay Sajip in commit ce46195b56a9.)
~logging.config.fileConfig now accepts a configparser.RawConfigParser subclass instance for the fname parameter. This facilitates using a configuration file when logging configuration is just a part of the overall application configuration, or where the application modifies the configuration before passing it to ~logging.config.fileConfig. (Contributed by Vinay Sajip in 16110.)
Logging configuration data received from a socket via the logging.config.listen function can now be validated before being processed by supplying a verification function as the argument to the new verify keyword argument. (Contributed by Vinay Sajip in 15452.)
marshal
The default marshal version has been bumped to 3. The code implementing the new version restores the Python2 behavior of recording only one copy of interned strings and preserving the interning on deserialization, and extends this "one copy" ability to any object type (including handling recursive references). This reduces both the size of .pyc files and the amount of memory a module occupies in memory when it is loaded from a .pyc (or .pyo) file. (Contributed by Kristján Valur Jónsson in 16475, with additional speedups by Antoine Pitrou in 19219.)
mmap
mmap objects are now weakly referenceable <mod-weakref>. (Contributed by Valerie Lambert in 4885.)
multiprocessing
On Unix two new start methods <multiprocessing-start-methods>, spawn and forkserver, have been added for starting processes using multiprocessing. These make the mixing of processes with threads more robust, and the spawn method matches the semantics that multiprocessing has always used on Windows. New function ~multiprocessing.get_all_start_methods reports all start methods available on the platform, ~multiprocessing.get_start_method reports the current start method, and ~multiprocessing.set_start_method sets the start method. (Contributed by Richard Oudkerk in 8713.)
multiprocessing also now has the concept of a context, which determines how child processes are created. New function ~multiprocessing.get_context returns a context that uses a specified start method. It has the same API as the multiprocessing module itself, so you can use it to create ~multiprocessing.pool.Pools and other objects that will operate within that context. This allows a framework and an application or different parts of the same application to use multiprocessing without interfering with each other. (Contributed by Richard Oudkerk in 18999.)
Except when using the old fork start method, child processes no longer inherit unneeded handles/file descriptors from their parents (part of 8713).
multiprocessing now relies on runpy (which implements the -m switch) to initialise __main__ appropriately in child processes when using the spawn or forkserver start methods. This resolves some edge cases where combining multiprocessing, the -m command line switch, and explicit relative imports could cause obscure failures in child processes. (Contributed by Nick Coghlan in 19946.)
operator
New function ~operator.length_hint provides an implementation of the specification for how the ~object.__length_hint__ special method should be used, as part of the 424 formal specification of this language feature. (Contributed by Armin Ronacher in 16148.)
There is now a pure-python version of the operator module available for reference and for use by alternate implementations of Python. (Contributed by Zachary Ware in 16694.)
os
There are new functions to get and set the inheritable flag <fd_inheritance> of a file descriptor (os.get_inheritable, os.set_inheritable) or a Windows handle (os.get_handle_inheritable, os.set_handle_inheritable).
New function ~os.cpu_count reports the number of CPUs available on the platform on which Python is running (or None if the count can't be determined). The multiprocessing.cpu_count function is now implemented in terms of this function). (Contributed by Trent Nelson, Yogesh Chaudhari, Victor Stinner, and Charles-François Natali in 17914.)
os.path.samestat is now available on the Windows platform (and the os.path.samefile implementation is now shared between Unix and Windows). (Contributed by Brian Curtin in 11939.)
os.path.ismount now recognizes volumes mounted below a drive root on Windows. (Contributed by Tim Golden in 9035.)
os.open supports two new flags on platforms that provide them, ~os.O_PATH (un-opened file descriptor), and ~os.O_TMPFILE (unnamed temporary file; as of 3.4.0 release available only on Linux systems with a kernel version of 3.11 or newer that have uapi headers). (Contributed by Christian Heimes in 18673 and Benjamin Peterson, respectively.)
pdb
pdb has been enhanced to handle generators, yield, and yield from in a more useful fashion. This is especially helpful when debugging asyncio based programs. (Contributed by Andrew Svetlov and Xavier de Gaye in 16596.)
The print command has been removed from pdb, restoring access to the Python print function from the pdb command line. Python2's pdb did not have a print command; instead, entering print executed the print statement. In Python3 print was mistakenly made an alias for the pdb p command. p, however, prints the repr of its argument, not the str like the Python2 print command did. Worse, the Python3 pdb print command shadowed the Python3 print function, making it inaccessible at the pdb prompt. (Contributed by Connor Osborn in 18764.)
pickle
pickle now supports (but does not use by default) a new pickle protocol, protocol 4. This new protocol addresses a number of issues that were present in previous protocols, such as the serialization of nested classes, very large strings and containers, and classes whose ~object.__new__ method takes keyword-only arguments. It also provides some efficiency improvements.
3154 -- Pickle protocol 4
PEP written by Antoine Pitrou and implemented by Alexandre Vassalotti.
plistlib
plistlib now has an API that is similar to the standard pattern for stdlib serialization protocols, with new ~plistlib.load, ~plistlib.dump, ~plistlib.loads, and ~plistlib.dumps functions. (The older API is now deprecated.) In addition to the already supported XML plist format (~plistlib.FMT_XML), it also now supports the binary plist format (~plistlib.FMT_BINARY). (Contributed by Ronald Oussoren and others in 14455.)
poplib
Two new methods have been added to poplib: ~poplib.POP3.capa, which returns the list of capabilities advertised by the POP server, and ~poplib.POP3.stls, which switches a clear-text POP3 session into an encrypted POP3 session if the POP server supports it. (Contributed by Lorenzo Catucci in 4473.)
pprint
The pprint module's ~pprint.PrettyPrinter class and its ~pprint.pformat, and ~pprint.pprint functions have a new option, compact, that controls how the output is formatted. Currently setting compact to True means that sequences will be printed with as many sequence elements as will fit within width on each (indented) line. (Contributed by Serhiy Storchaka in 19132.)
Long strings are now wrapped using Python's normal line continuation syntax. (Contributed by Antoine Pitrou in 17150.)
pty
pty.spawn now returns the status value from os.waitpid on the child process, instead of None. (Contributed by Gregory P. Smith.)
pydoc
The pydoc module is now based directly on the inspect.signature introspection API, allowing it to provide signature information for a wider variety of callable objects. This change also means that __wrapped__ attributes are now taken into account when displaying help information. (Contributed by Larry Hastings in 19674.)
The pydoc module no longer displays the self parameter for already bound methods. Instead, it aims to always display the exact current signature of the supplied callable. (Contributed by Larry Hastings in 20710.)
In addition to the changes that have been made to pydoc directly, its handling of custom __dir__ methods and various descriptor behaviours has also been improved substantially by the underlying changes in the inspect module.
As the help builtin is based on pydoc, the above changes also affect the behaviour of help.
re
New ~re.fullmatch function and .Pattern.fullmatch method anchor the pattern at both ends of the string to match. This provides a way to be explicit about the goal of the match, which avoids a class of subtle bugs where $ characters get lost during code changes or the addition of alternatives to an existing regular expression. (Contributed by Matthew Barnett in 16203.)
The repr of regex objects <re-objects> now includes the pattern and the flags; the repr of match objects <match-objects> now includes the start, end, and the part of the string that matched. (Contributed by Hugo Lopes Tavares and Serhiy Storchaka in 13592 and 17087.)
resource
New ~resource.prlimit function, available on Linux platforms with a kernel version of 2.6.36 or later and glibc of 2.13 or later, provides the ability to query or set the resource limits for processes other than the one making the call. (Contributed by Christian Heimes in 16595.)
On Linux kernel version 2.6.36 or later, there are also some new Linux specific constants: ~resource.RLIMIT_MSGQUEUE, ~resource.RLIMIT_NICE, ~resource.RLIMIT_RTPRIO, ~resource.RLIMIT_RTTIME, and ~resource.RLIMIT_SIGPENDING. (Contributed by Christian Heimes in 19324.)
On FreeBSD version 9 and later, there some new FreeBSD specific constants: ~resource.RLIMIT_SBSIZE, ~resource.RLIMIT_SWAP, and ~resource.RLIMIT_NPTS. (Contributed by Claudiu Popa in 19343.)
select
~select.epoll objects now support the context management protocol. When used in a with statement, the ~select.epoll.close method will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in 16488.)
~select.devpoll objects now have ~select.devpoll.fileno and ~select.devpoll.close methods, as well as a new attribute ~select.devpoll.closed. (Contributed by Victor Stinner in 18794.)
shelve
~shelve.Shelf instances may now be used in with statements, and will be automatically closed at the end of the !with block. (Contributed by Filip Gruszczyński in 13896.)
shutil
~shutil.copyfile now raises a specific ~shutil.Error subclass, ~shutil.SameFileError, when the source and destination are the same file, which allows an application to take appropriate action on this specific error. (Contributed by Atsuo Ishimoto and Hynek Schlawack in 1492704.)
smtpd
The !SMTPServer and !SMTPChannel classes now accept a map keyword argument which, if specified, is passed in to !asynchat.async_chat as its map argument. This allows an application to avoid affecting the global socket map. (Contributed by Vinay Sajip in 11959.)
smtplib
~smtplib.SMTPException is now a subclass of OSError, which allows both socket level errors and SMTP protocol level errors to be caught in one try/except statement by code that only cares whether or not an error occurred. (Contributed by Ned Jackson Lovely in 2118.)
socket
The socket module now supports the ~socket.CAN_BCM protocol on platforms that support it. (Contributed by Brian Thorne in 15359.)
Socket objects have new methods to get or set their inheritable flag <fd_inheritance>, ~socket.socket.get_inheritable and ~socket.socket.set_inheritable.
The socket.AF_* and socket.SOCK_* constants are now enumeration values using the new enum module. This allows meaningful names to be printed during debugging, instead of integer "magic numbers".
The ~socket.AF_LINK constant is now available on BSD and OSX.
~socket.inet_pton and ~socket.inet_ntop are now supported on Windows. (Contributed by Atsuo Ishimoto in 7171.)
sqlite3
A new boolean parameter to the ~sqlite3.connect function, uri, can be used to indicate that the database parameter is a uri (see the SQLite URI documentation). (Contributed by poq in 13773.)
ssl
~ssl.PROTOCOL_TLSv1_1 and ~ssl.PROTOCOL_TLSv1_2 (TLSv1.1 and TLSv1.2 support) have been added; support for these protocols is only available if Python is linked with OpenSSL 1.0.1 or later. (Contributed by Michele Orrù and Antoine Pitrou in 16692.)
New function ~ssl.create_default_context provides a standard way to obtain an ~ssl.SSLContext whose settings are intended to be a reasonable balance between compatibility and security. These settings are more stringent than the defaults provided by the ~ssl.SSLContext constructor, and may be adjusted in the future, without prior deprecation, if best-practice security requirements change. The new recommended best practice for using stdlib libraries that support SSL is to use ~ssl.create_default_context to obtain an ~ssl.SSLContext object, modify it if needed, and then pass it as the context argument of the appropriate stdlib API. (Contributed by Christian Heimes in 19689.)
~ssl.SSLContext method ~ssl.SSLContext.load_verify_locations accepts a new optional argument cadata, which can be used to provide PEM or DER encoded certificates directly via strings or bytes, respectively. (Contributed by Christian Heimes in 18138.)
New function ~ssl.get_default_verify_paths returns a named tuple of the paths and environment variables that the ~ssl.SSLContext.set_default_verify_paths method uses to set OpenSSL's default cafile and capath. This can be an aid in debugging default verification issues. (Contributed by Christian Heimes in 18143.)
~ssl.SSLContext has a new method, ~ssl.SSLContext.cert_store_stats, that reports the number of loaded X.509 certs, X.509 CA certs, and certificate revocation lists (crls), as well as a ~ssl.SSLContext.get_ca_certs method that returns a list of the loaded CA certificates. (Contributed by Christian Heimes in 18147.)
If OpenSSL 0.9.8 or later is available, ~ssl.SSLContext has a new attribute ~ssl.SSLContext.verify_flags that can be used to control the certificate verification process by setting it to some combination of the new constants ~ssl.VERIFY_DEFAULT, ~ssl.VERIFY_CRL_CHECK_LEAF, ~ssl.VERIFY_CRL_CHECK_CHAIN, or ~ssl.VERIFY_X509_STRICT. OpenSSL does not do any CRL verification by default. (Contributed by Christien Heimes in 8813.)
New ~ssl.SSLContext method ~ssl.SSLContext.load_default_certs loads a set of default "certificate authority" (CA) certificates from default locations, which vary according to the platform. It can be used to load both TLS web server authentication certificates (purpose=``~ssl.Purpose.SERVER_AUTH) for a client to use to verify a server, and certificates for a server to use in verifying client certificates (purpose=``~ssl.Purpose.CLIENT_AUTH). (Contributed by Christian Heimes in 19292.)
Two new windows-only functions, ~ssl.enum_certificates and ~ssl.enum_crls provide the ability to retrieve certificates, certificate information, and CRLs from the Windows cert store. (Contributed by Christian Heimes in 17134.)
Support for server-side SNI (Server Name Indication) using the new ssl.SSLContext.set_servername_callback method. (Contributed by Daniel Black in 8109.)
The dictionary returned by .SSLSocket.getpeercert contains additional X509v3 extension items: crlDistributionPoints, calIssuers, and OCSP URIs. (Contributed by Christian Heimes in 18379.)
stat
The stat module is now backed by a C implementation in !_stat. A C implementation is required as most of the values aren't standardized and are platform-dependent. (Contributed by Christian Heimes in 11016.)
The module supports new ~stat.ST_MODE flags, ~stat.S_IFDOOR, ~stat.S_IFPORT, and ~stat.S_IFWHT. (Contributed by Christian Hiemes in 11016.)
struct
New function ~struct.iter_unpack and a new struct.Struct.iter_unpack method on compiled formats provide streamed unpacking of a buffer containing repeated instances of a given format of data. (Contributed by Antoine Pitrou in 17804.)
subprocess
~subprocess.check_output now accepts an input argument that can be used to provide the contents of stdin for the command that is run. (Contributed by Zack Weinberg in 16624.)
~subprocess.getoutput and ~subprocess.getstatusoutput now work on Windows. This change was actually inadvertently made in 3.3.4. (Contributed by Tim Golden in 10197.)
sunau
The !getparams method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in 18901.)
!sunau.open now supports the context management protocol: when used in a with block, the close method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in 18878.)
!AU_write.setsampwidth now supports 24 bit samples, thus adding support for writing 24 sample using the module. (Contributed by Serhiy Storchaka in 19261.)
The !writeframesraw and !writeframes methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in 8311.)
sys
New function sys.getallocatedblocks returns the current number of blocks allocated by the interpreter. (In CPython with the default --with-pymalloc setting, this is allocations made through the PyObject_Malloc API.) This can be useful for tracking memory leaks, especially if automated via a test suite. (Contributed by Antoine Pitrou in 13390.)
When the Python interpreter starts in interactive mode <tut-interactive>, it checks for an ~sys.__interactivehook__ attribute on the sys module. If the attribute exists, its value is called with no arguments just before interactive mode is started. The check is made after the PYTHONSTARTUP file is read, so it can be set there. The site module sets it <rlcompleter-config> to a function that enables tab completion and history saving (in ~/.python-history) if the platform supports readline. If you do not want this (new) behavior, you can override it in PYTHONSTARTUP, sitecustomize, or usercustomize by deleting this attribute from sys (or setting it to some other callable). (Contributed by Éric Araujo and Antoine Pitrou in 5845.)
tarfile
The tarfile module now supports a simple tarfile-commandline when called as a script directly or via -m. This can be used to create and extract tarfile archives. (Contributed by Berker Peksag in 13477.)
textwrap
The ~textwrap.TextWrapper class has two new attributes/constructor arguments: ~textwrap.TextWrapper.max_lines, which limits the number of lines in the output, and ~textwrap.TextWrapper.placeholder, which is a string that will appear at the end of the output if it has been truncated because of max_lines. Building on these capabilities, a new convenience function ~textwrap.shorten collapses all of the whitespace in the input to single spaces and produces a single line of a given width that ends with the placeholder (by default, [...]). (Contributed by Antoine Pitrou and Serhiy Storchaka in 18585 and 18725.)
threading
The ~threading.Thread object representing the main thread can be obtained from the new ~threading.main_thread function. In normal conditions this will be the thread from which the Python interpreter was started. (Contributed by Andrew Svetlov in 18882.)
traceback
A new traceback.clear_frames function takes a traceback object and clears the local variables in all of the frames it references, reducing the amount of memory consumed. (Contributed by Andrew Kuchling in 1565525.)
types
A new ~types.DynamicClassAttribute descriptor provides a way to define an attribute that acts normally when looked up through an instance object, but which is routed to the class __getattr__ when looked up through the class. This allows one to have properties active on a class, and have virtual attributes on the class with the same name (see enum for an example). (Contributed by Ethan Furman in 19030.)
urllib
urllib.request now supports data: URLs via the ~urllib.request.DataHandler class. (Contributed by Mathias Panzenböck in 16423.)
The http method that will be used by a ~urllib.request.Request class can now be specified by setting a ~urllib.request.Request.method class attribute on the subclass. (Contributed by Jason R Coombs in 18978.)
~urllib.request.Request objects are now reusable: if the ~urllib.request.Request.full_url or ~urllib.request.Request.data attributes are modified, all relevant internal properties are updated. This means, for example, that it is now possible to use the same ~urllib.request.Request object in more than one .OpenerDirector.open call with different data arguments, or to modify a ~urllib.request.Request's url rather than recomputing it from scratch. There is also a new ~urllib.request.Request.remove_header method that can be used to remove headers from a ~urllib.request.Request. (Contributed by Alexey Kachayev in 16464, Daniel Wozniak in 17485, and Damien Brecht and Senthil Kumaran in 17272.)
~urllib.error.HTTPError objects now have a ~urllib.error.HTTPError.headers attribute that provides access to the HTTP response headers associated with the error. (Contributed by Berker Peksag in 15701.)
unittest
The ~unittest.TestCase class has a new method, ~unittest.TestCase.subTest, that produces a context manager whose with block becomes a "sub-test". This context manager allows a test method to dynamically generate subtests by, say, calling the subTest context manager inside a loop. A single test method can thereby produce an indefinite number of separately identified and separately counted tests, all of which will run even if one or more of them fail. For example:
class NumbersTest(unittest.TestCase):
def test_even(self):
for i in range(6):
with self.subTest(i=i):
self.assertEqual(i % 2, 0)
will result in six subtests, each identified in the unittest verbose output with a label consisting of the variable name i and a particular value for that variable (i=0, i=1, etc). See subtests for the full version of this example. (Contributed by Antoine Pitrou in 16997.)
unittest.main now accepts an iterable of test names for defaultTest, where previously it only accepted a single test name as a string. (Contributed by Jyrki Pulliainen in 15132.)
If ~unittest.SkipTest is raised during test discovery (that is, at the module level in the test file), it is now reported as a skip instead of an error. (Contributed by Zach Ware in 16935.)
~unittest.TestLoader.discover now sorts the discovered files to provide consistent test ordering. (Contributed by Martin Melin and Jeff Ramnani in 16709.)
~unittest.TestSuite now drops references to tests as soon as the test has been run, if the test is successful. On Python interpreters that do garbage collection, this allows the tests to be garbage collected if nothing else is holding a reference to the test. It is possible to override this behavior by creating a ~unittest.TestSuite subclass that defines a custom _removeTestAtIndex method. (Contributed by Tom Wardill, Matt McClure, and Andrew Svetlov in 11798.)
A new test assertion context-manager, ~unittest.TestCase.assertLogs, will ensure that a given block of code emits a log message using the logging module. By default the message can come from any logger and have a priority of INFO or higher, but both the logger name and an alternative minimum logging level may be specified. The object returned by the context manager can be queried for the ~logging.LogRecords and/or formatted messages that were logged. (Contributed by Antoine Pitrou in 18937.)
Test discovery now works with namespace packages (Contributed by Claudiu Popa in 17457.)
unittest.mock objects now inspect their specification signatures when matching calls, which means an argument can now be matched by either position or name, instead of only by position. (Contributed by Antoine Pitrou in 17015.)
~unittest.mock.mock_open objects now have readline and readlines methods. (Contributed by Toshio Kuratomi in 17467.)
venv
venv now includes activation scripts for the csh and fish shells. (Contributed by Andrew Svetlov in 15417.)
~venv.EnvBuilder and the ~venv.create convenience function take a new keyword argument with_pip, which defaults to False, that controls whether or not ~venv.EnvBuilder ensures that pip is installed in the virtual environment. (Contributed by Nick Coghlan in 19552 as part of the 453 implementation.)
wave
The ~wave.Wave_read.getparams method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in 17487.)
wave.open now supports the context management protocol. (Contributed by Claudiu Popa in 17616.)
wave can now write output to unseekable files <wave-write-objects>. (Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in 5202.)
The ~wave.Wave_write.writeframesraw and ~wave.Wave_write.writeframes methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in 8311.)
weakref
New ~weakref.WeakMethod class simulates weak references to bound methods. (Contributed by Antoine Pitrou in 14631.)
New ~weakref.finalize class makes it possible to register a callback to be invoked when an object is garbage collected, without needing to carefully manage the lifecycle of the weak reference itself. (Contributed by Richard Oudkerk in 15528.)
The callback, if any, associated with a ~weakref.ref is now exposed via the ~weakref.ref.__callback__ attribute. (Contributed by Mark Dickinson in 17643.)
xml.etree
A new parser, ~xml.etree.ElementTree.XMLPullParser, allows a non-blocking applications to parse XML documents. An example can be seen at elementtree-pull-parsing. (Contributed by Antoine Pitrou in 17741.)
The xml.etree.ElementTree ~xml.etree.ElementTree.tostring and ~xml.etree.ElementTree.tostringlist functions, and the ~xml.etree.ElementTree.ElementTree ~xml.etree.ElementTree.ElementTree.write method, now have a short_empty_elements keyword-only parameter <keyword-only_parameter> providing control over whether elements with no content are written in abbreviated (<tag />) or expanded (<tag></tag>) form. (Contributed by Ariel Poliak and Serhiy Storchaka in 14377.)
zipfile
The ~zipfile.PyZipFile.writepy method of the ~zipfile.PyZipFile class has a new filterfunc option that can be used to control which directories and files are added to the archive. For example, this could be used to exclude test files from the archive. (Contributed by Christian Tismer in 19274.)
The allowZip64 parameter to ~zipfile.ZipFile and ~zipfile.PyZipFile is now True by default. (Contributed by William Mallard in 17201.)
CPython Implementation Changes
PEP 445: Customization of CPython Memory Allocators
445 adds new C level interfaces to customize memory allocation in the CPython interpreter.
445 -- Add new APIs to customize Python memory allocators
PEP written and implemented by Victor Stinner.
PEP 442: Safe Object Finalization
442 removes the current limitations and quirks of object finalization in CPython. With it, objects with ~object.__del__ methods, as well as generators with finally clauses, can be finalized when they are part of a reference cycle.
As part of this change, module globals are no longer forcibly set to None during interpreter shutdown in most cases, instead relying on the normal operation of the cyclic garbage collector. This avoids a whole class of interpreter-shutdown-time errors, usually involving __del__ methods, that have plagued Python since the cyclic GC was first introduced.
442 -- Safe object finalization
PEP written and implemented by Antoine Pitrou.
PEP 456: Secure and Interchangeable Hash Algorithm
456 follows up on earlier security fix work done on Python's hash algorithm to address certain DOS attacks to which public facing APIs backed by dictionary lookups may be subject. (See 14621 for the start of the current round of improvements.) The PEP unifies CPython's hash code to make it easier for a packager to substitute a different hash algorithm, and switches Python's default implementation to a SipHash implementation on platforms that have a 64 bit data type. Any performance differences in comparison with the older FNV algorithm are trivial.
The PEP adds additional fields to the sys.hash_info named tuple to describe the hash algorithm in use by the currently executing binary. Otherwise, the PEP does not alter any existing CPython APIs.
PEP 436: Argument Clinic
"Argument Clinic" (436) is now part of the CPython build process and can be used to simplify the process of defining and maintaining accurate signatures for builtins and standard library extension modules implemented in C.
Some standard library extension modules have been converted to use Argument Clinic in Python 3.4, and pydoc and inspect have been updated accordingly.
It is expected that signature metadata for programmatic introspection will be added to additional callables implemented in C as part of Python 3.4 maintenance releases.
[!NOTE] The Argument Clinic PEP is not fully up to date with the state of the implementation. This has been deemed acceptable by the release manager and core development team in this case, as Argument Clinic will not be made available as a public API for third party use in Python 3.4.
436 -- The Argument Clinic DSL
PEP written and implemented by Larry Hastings.
Other Build and C API Changes
- The new
PyType_GetSlotfunction has been added to the stable ABI, allowing retrieval of function pointers from named type slots when using the limited API. (Contributed by Martin von Löwis in17162.) - The new
!Py_SetStandardStreamEncodingpre-initialization API allows applications embedding the CPython interpreter to reliably force a particular encoding and error handler for the standard streams. (Contributed by Bastien Montagne and Nick Coghlan in16129.) - Most Python C APIs that don't mutate string arguments are now correctly marked as accepting
const char *rather thanchar *. (Contributed by Serhiy Storchaka in1772673.) - A new shell version of
python-configcan be used even when a python interpreter is not available (for example, in cross compilation scenarios). PyUnicode_FromFormatnow supports width and precision specifications for%s,%A,%U,%V,%S, and%R. (Contributed by Ysj Ray and Victor Stinner in7330.)- New function
PyStructSequence_InitType2supplements the existingPyStructSequence_InitTypefunction. The difference is that it returns0on success and-1on failure. - The CPython source can now be compiled using the address sanity checking features of recent versions of GCC and clang: the false alarms in the small object allocator have been silenced. (Contributed by Dhiru Kholia in
18596.) - The Windows build now uses Address Space Layout Randomization and Data Execution Prevention. (Contributed by Christian Heimes in
16632.) - New function
PyObject_LengthHintis the C API equivalent ofoperator.length_hint. (Contributed by Armin Ronacher in16148.)
Other Improvements
- The
python <using-on-cmdline>command has a newoption <using-on-misc-options>,-I, which causes it to run in "isolated mode", which means thatsys.pathcontains neither the script's directory nor the user'ssite-packagesdirectory, and all!PYTHON*environment variables are ignored (it implies both-sand-E). Other restrictions may also be applied in the future, with the goal being to isolate the execution of a script from the user's environment. This is appropriate, for example, when Python is used to run a system script. On most POSIX systems it can and should be used in the#!line of system scripts. (Contributed by Christian Heimes in16499.) - Tab-completion is now enabled by default in the interactive interpreter on systems that support
readline. History is also enabled by default, and is written to (and read from) the file~/.python-history. (Contributed by Antoine Pitrou and Éric Araujo in5845.) - Invoking the Python interpreter with
--versionnow outputs the version to standard output instead of standard error (18338). Similar changes were made toargparse(18920) and other modules that have script-like invocation capabilities (18922). - The CPython Windows installer now adds
.pyto thePATHEXTvariable when extensions are registered, allowing users to run a python script at the windows command prompt by just typing its name without the.pyextension. (Contributed by Paul Moore in18569.) - A new
maketarget coverage-report will build python, run the test suite, and generate an HTML coverage report for the C codebase usinggcovand lcov. - The
-Roption to thepython regression test suite <regrtest>now also checks for memory allocation leaks, usingsys.getallocatedblocks. (Contributed by Antoine Pitrou in13390.) python -mnow works with namespace packages.- The
statmodule is now implemented in C, which means it gets the values for its constants from the C header files, instead of having the values hard-coded in the python module as was previously the case. - Loading multiple python modules from a single OS module (
.so,.dll) now works correctly (previously it silently returned the first python module in the file). (Contributed by Václav Šmilauer in16421.) - A new opcode,
!LOAD_CLASSDEREF, has been added to fix a bug in the loading of free variables in class bodies that could be triggered by certain uses of__prepare__ <prepare>. (Contributed by Benjamin Peterson in17853.) - A number of MemoryError-related crashes were identified and fixed by Victor Stinner using his
445-basedpyfailmalloctool (18408,18520). - The
pyvenvcommand now accepts a--copiesoption to use copies rather than symlinks even on systems where symlinks are the default. (Contributed by Vinay Sajip in18807.) - The
pyvenvcommand also accepts a--without-pipoption to suppress the otherwise-automatic bootstrapping of pip into the virtual environment. (Contributed by Nick Coghlan in19552as part of the453implementation.) - The encoding name is now optional in the value set for the
PYTHONIOENCODINGenvironment variable. This makes it possible to set just the error handler, without changing the default encoding. (Contributed by Serhiy Storchaka in18818.) - The
bz2,lzma, andgzipmoduleopenfunctions now supportx(exclusive creation) mode. (Contributed by Tim Heaney and Vajrasky Kok in19201,19222, and19223.)
Significant Optimizations
- The UTF-32 decoder is now 3x to 4x faster. (Contributed by Serhiy Storchaka in
14625.) - The cost of hash collisions for sets is now reduced. Each hash table probe now checks a series of consecutive, adjacent key/hash pairs before continuing to make random probes through the hash table. This exploits cache locality to make collision resolution less expensive. The collision resolution scheme can be described as a hybrid of linear probing and open addressing. The number of additional linear probes defaults to nine. This can be changed at compile-time by defining LINEAR_PROBES to be any value. Set LINEAR_PROBES=0 to turn-off linear probing entirely. (Contributed by Raymond Hettinger in
18771.) - The interpreter starts about 30% faster. A couple of measures lead to the speedup. The interpreter loads fewer modules on startup, e.g. the
re,collectionsandlocalemodules and their dependencies are no longer imported by default. The marshal module has been improved to load compiled Python code faster. (Contributed by Antoine Pitrou, Christian Heimes and Victor Stinner in19219,19218,19209,19205and9548.) bz2.BZ2Fileis now as fast or faster than the Python2 version for most cases.lzma.LZMAFilehas also been optimized. (Contributed by Serhiy Storchaka and Nadeem Vawda in16034.)random.getrandbitsis 20%-40% faster for small integers (the most common use case). (Contributed by Serhiy Storchaka in16674.)- By taking advantage of the new storage format for strings, pickling of strings is now significantly faster. (Contributed by Victor Stinner and Antoine Pitrou in
15596.) - A performance issue in
!io.FileIO.readallhas been solved. This particularly affects Windows, and significantly speeds up the case of piping significant amounts of data throughsubprocess. (Contributed by Richard Oudkerk in15758.) html.escapeis now 10x faster. (Contributed by Matt Bryant in18020.)- On Windows, the native
VirtualAllocis now used instead of the CRTmallocinobmalloc. Artificial benchmarks show about a 3% memory savings. os.urandomnow uses a lazily opened persistent file descriptor so as to avoid using many file descriptors when run in parallel from multiple threads. (Contributed by Antoine Pitrou in18756.)
Deprecated
This section covers various APIs and other features that have been deprecated in Python 3.4, and will be removed in Python 3.5 or later. In most (but not all) cases, using the deprecated APIs will produce a DeprecationWarning when the interpreter is run with deprecation warnings enabled (for example, by using -Wd).
Deprecations in the Python API
- As mentioned in
whatsnew-pep-451, a number ofimportlibmethods and functions are deprecated:!importlib.find_loaderis replaced byimportlib.util.find_spec;!importlib.machinery.PathFinder.find_moduleis replaced byimportlib.machinery.PathFinder.find_spec;!importlib.abc.MetaPathFinder.find_moduleis replaced byimportlib.abc.MetaPathFinder.find_spec;!importlib.abc.PathEntryFinder.find_loaderand!find_moduleare replaced byimportlib.abc.PathEntryFinder.find_spec; all of the{xxx}LoaderABCload_modulemethods (importlib.abc.Loader.load_module,importlib.abc.InspectLoader.load_module,importlib.abc.FileLoader.load_module,importlib.abc.SourceLoader.load_module) should no longer be implemented, instead loaders should implement anexec_modulemethod (importlib.abc.Loader.exec_module,importlib.abc.InspectLoader.exec_moduleimportlib.abc.SourceLoader.exec_module) and let the import system take care of the rest; and!importlib.abc.Loader.module_repr,!importlib.util.module_for_loader,!importlib.util.set_loader, and!importlib.util.set_packageare no longer needed because their functions are now handled automatically by the import system. - The
!impmodule is pending deprecation. To keep compatibility with Python 2/3 code bases, the module's removal is currently not scheduled. - The
!formattermodule is pending deprecation and is slated for removal in Python 3.6. MD5as the default digestmod for thehmac.newfunction is deprecated. Python 3.6 will require an explicit digest name or constructor as digestmod argument.- The internal
Netrcclass in theftplibmodule has been documented as deprecated in its docstring for quite some time. It now emits aDeprecationWarningand will be removed completely in Python 3.5. - The undocumented endtime argument to
subprocess.Popen.waitshould not have been exposed and is hopefully not in use; it is deprecated and will mostly likely be removed in Python 3.5. - The strict argument of
~html.parser.HTMLParseris deprecated. - The
plistlib!readPlist,!writePlist,!readPlistFromBytes, and!writePlistToBytesfunctions are deprecated in favor of the corresponding new functions~plistlib.load,~plistlib.dump,~plistlib.loads, and~plistlib.dumps.!Datais deprecated in favor of just using thebytesconstructor. - The
sysconfigkeySOis deprecated, it has been replaced byEXT_SUFFIX. - The
Umode accepted by variousopenfunctions is deprecated. In Python3 it does not do anything useful, and should be replaced by appropriate uses ofio.TextIOWrapper(if needed) and its newline argument. - The parser argument of
xml.etree.ElementTree.iterparsehas been deprecated, as has the html argument of~xml.etree.ElementTree.XMLParser. To prepare for the removal of the latter, all arguments toXMLParsershould be passed by keyword.
Deprecated Features
- Running
idlewith the-nflag (no subprocess) is deprecated. However, the feature will not be removed until18823is resolved. - The site module adding a "site-python" directory to sys.path, if it exists, is deprecated (
19375).
Removed
Operating Systems No Longer Supported
Support for the following operating systems has been removed from the source and build tools:
- OS/2 (
16135). - Windows 2000 (changeset e52df05b496a).
- Windows systems where
COMSPECpoints tocommand.com(14470). - VMS (
16136).
API and Feature Removals
The following obsolete and previously deprecated APIs and features have been removed:
- The unmaintained
Misc/TextMateandMisc/vimdirectories have been removed (see the devguide for suggestions on what to use instead). - The
SOmakefile macro is removed (it was replaced by theSHLIB_SUFFIXandEXT_SUFFIXmacros) (16754). - The
PyThreadState.tick_counterfield has been removed; its value has been meaningless since Python 3.2, when the "new GIL" was introduced (19199). PyLoaderandPyPycLoaderhave been removed fromimportlib. (Contributed by Taras Lyapun in15641.)- The strict argument to
~http.client.HTTPConnectionand~http.client.HTTPSConnectionhas been removed. HTTP 0.9-style "Simple Responses" are no longer supported. - The deprecated
urllib.request.Requestgetter and setter methodsadd_data,has_data,get_data,get_type,get_host,get_selector,set_proxy,get_origin_req_host, andis_unverifiablehave been removed (use direct attribute access instead). - Support for loading the deprecated
TYPE_INT64has been removed frommarshal. (Contributed by Dan Riti in15480.) inspect.Signature: positional-only parameters are now required to have a valid name.object.__format__no longer accepts non-empty format strings, it now raises aTypeErrorinstead. Using a non-empty string has been deprecated since Python 3.2. This change has been made to prevent a situation where previously working (but incorrect) code would start failing if an object gained a __format__ method, which means that your code may now raise aTypeErrorif you are using an's'format code with objects that do not have a __format__ method that handles it. See7994for background.!difflib.SequenceMatcher.isbjunkand!difflib.SequenceMatcher.isbpopularwere deprecated in 3.2, and have now been removed: usex in sm.bjunkandx in sm.bpopular, where sm is a~difflib.SequenceMatcherobject (13248).
Code Cleanups
- The unused and undocumented internal
Scannerclass has been removed from thepydocmodule. - The private and effectively unused
_gestaltmodule has been removed, along with the privateplatformfunctions_mac_ver_lookup,_mac_ver_gstalt, and_bcd2str, which would only have ever been called on badly broken OSX systems (see18393). - The hardcoded copies of certain
statconstants that were included in thetarfilemodule namespace have been removed.
Porting to Python 3.4
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in 'python' Command Behavior
- In a posix shell, setting the
PATHenvironment variable to an empty value is equivalent to not setting it at all. However, settingPYTHONPATHto an empty value was not equivalent to not setting it at all: settingPYTHONPATHto an empty value was equivalent to setting it to., which leads to confusion when reasoning by analogy to howPATHworks. The behavior now conforms to the posix convention forPATH. - The [X refs, Y blocks] output of a debug (
--with-pydebug) build of the CPython interpreter is now off by default. It can be re-enabled using the-X showrefcountoption. (Contributed by Ezio Melotti in17323.) - The python command and most stdlib scripts (as well as
argparse) now output--versioninformation tostdoutinstead ofstderr(for issue list seeother-improvements-3.4above).
Changes in the Python API
- The ABCs defined in
importlib.abcnow either raise the appropriate exception or return a default value instead of raisingNotImplementedErrorblindly. This will only affect code callingsuperand falling through all the way to the ABCs. For compatibility, catch bothNotImplementedErroror the appropriate exception as needed. - The module type now initializes the
~module.__package__and~module.__loader__attributes toNoneby default. To determine if these attributes were set in a backwards-compatible fashion, use e.g.getattr(module, '__loader__', None) is not None. (17115.) !importlib.util.module_for_loadernow sets__loader__and__package__unconditionally to properly support reloading. If this is not desired then you will need to set these attributes manually. You can use!importlib.util.module_to_loadfor module management.- Import now resets relevant attributes (e.g.
__name__,__loader__,__package__,__file__,__cached__) unconditionally when reloading. Note that this restores a pre-3.3 behavior in that it means a module is re-found when re-loaded (19413). - Frozen packages no longer set
__path__to a list containing the package name, they now set it to an empty list. The previous behavior could cause the import system to do the wrong thing on submodule imports if there was also a directory with the same name as the frozen package. The correct way to determine if a module is a package or not is to usehasattr(module, '__path__')(18065). - Frozen modules no longer define a
__file__attribute. It's semantically incorrect for frozen modules to set the attribute as they are not loaded from any explicit location. If you must know that a module comes from frozen code then you can see if the module's__spec__.locationis set to'frozen', check if the loader is a subclass ofimportlib.machinery.FrozenImporter, or if Python 2 compatibility is necessary you can use!imp.is_frozen. py_compile.compilenow raisesFileExistsErrorif the file path it would write to is a symlink or a non-regular file. This is to act as a warning that import will overwrite those files with a regular file regardless of what type of file path they were originally.importlib.abc.SourceLoader.get_sourceno longer raisesImportErrorwhen the source code being loaded triggers aSyntaxErrororUnicodeDecodeError. AsImportErroris meant to be raised only when source code cannot be found but it should, it was felt to be over-reaching/overloading of that meaning when the source code is found but improperly structured. If you were catching ImportError before and wish to continue to ignore syntax or decoding issues, catch all three exceptions now.functools.update_wrapperandfunctools.wrapsnow correctly set the__wrapped__attribute to the function being wrapped, even if that function also had its__wrapped__attribute set. This means__wrapped__attributes now correctly link a stack of decorated functions rather than every__wrapped__attribute in the chain referring to the innermost function. Introspection libraries that assumed the previous behaviour was intentional can useinspect.unwrapto access the first function in the chain that has no__wrapped__attribute.inspect.getfullargspechas been reimplemented on top ofinspect.signatureand hence handles a much wider variety of callable objects than it did in the past. It is expected that additional builtin and extension module callables will gain signature metadata over the course of the Python 3.4 series. Code that assumes thatinspect.getfullargspecwill fail on non-Python callables may need to be adjusted accordingly.importlib.machinery.PathFindernow passes on the current working directory to objects insys.path_hooksfor the empty string. This results insys.path_importer_cachenever containing'', thus iterating throughsys.path_importer_cachebased onsys.pathwill not find all keys. A module's__file__when imported in the current working directory will also now have an absolute path, including when using-mwith the interpreter (except for__main__.__file__when a script has been executed directly using a relative path) (Contributed by Brett Cannon in18416). is specified on the command-line) (18416).- The removal of the strict argument to
~http.client.HTTPConnectionand~http.client.HTTPSConnectionchanges the meaning of the remaining arguments if you are specifying them positionally rather than by keyword. If you've been paying attention to deprecation warnings your code should already be specifying any additional arguments via keywords. - Strings between
from __future__ import ...statements now always raise aSyntaxError. Previously if there was no leading docstring, an interstitial string would sometimes be ignored. This brings CPython into compliance with the language spec; Jython and PyPy already were. (17434). ssl.SSLSocket.getpeercertandssl.SSLSocket.do_handshakenow raise anOSErrorwithENOTCONNwhen theSSLSocketis not connected, instead of the previous behavior of raising anAttributeError. In addition,~ssl.SSLSocket.getpeercertwill raise aValueErrorif the handshake has not yet been done.base64.b32decodenow raises abinascii.Errorwhen the input string contains non-b32-alphabet characters, instead of aTypeError. This particularTypeErrorwas missed when the otherTypeErrors were converted. (Contributed by Serhiy Storchaka in18011.) Note: this change was also inadvertently applied in Python 3.3.3.- The
!fileattribute is now automatically closed when the creating!cgi.FieldStorageinstance is garbage collected. If you were pulling the file object out separately from the!cgi.FieldStorageinstance and not keeping the instance alive, then you should either store the entire!cgi.FieldStorageinstance or read the contents of the file before the!cgi.FieldStorageinstance is garbage collected. - Calling
readorwriteon a closed SSL socket now raises an informativeValueErrorrather than the previous more mysteriousAttributeError(9177). slice.indicesno longer produces anOverflowErrorfor huge values. As a consequence of this fix,slice.indicesnow raises aValueErrorif given a negative length; previously it returned nonsense values (14794).- The
complexconstructor, unlike thecmathfunctions, was incorrectly acceptingfloatvalues if an object's__complex__special method returned one. This now raises aTypeError. (16290.) - The
intconstructor in 3.2 and 3.3 erroneously acceptsfloatvalues for the base parameter. It is unlikely anyone was doing this, but if so, it will now raise aTypeError(16772). - Defaults for keyword-only arguments are now evaluated after defaults for regular keyword arguments, instead of before. Hopefully no one wrote any code that depends on the previous buggy behavior (
16967). - Stale thread states are now cleared after
~os.fork. This may cause some system resources to be released that previously were incorrectly kept perpetually alive (for example, database connections kept in thread-local storage). (17094.) - Parameter names in
__annotations__dicts are now mangled properly, similarly to~function.__kwdefaults__. (Contributed by Yury Selivanov in20625.) hashlib.hash.namenow always returns the identifier in lower case. Previously some builtin hashes had uppercase names, but now that it is a formal public interface the naming has been made consistent (18532).- Because
unittest.TestSuitenow drops references to tests after they are run, test harnesses that reuse a~unittest.TestSuiteto re-run a set of tests may fail. Test suites should not be re-used in this fashion since it means state is retained between test runs, breaking the test isolation thatunittestis designed to provide. However, if the lack of isolation is considered acceptable, the old behavior can be restored by creating a~unittest.TestSuitesubclass that defines a_removeTestAtIndexmethod that does nothing (see.TestSuite.__iter__) (11798). unittestnow usesargparsefor command line parsing. There are certain invalid command forms that used to work that are no longer allowed; in theory this should not cause backward compatibility issues since the disallowed command forms didn't make any sense and are unlikely to be in use.- The
re.split,re.findall, andre.subfunctions, and the~re.Match.groupand~re.Match.groupsmethods ofmatchobjects now always return a bytes object when the string to be matched is abytes-like object. Previously the return type matched the input type, so if your code was depending on the return value being, say, abytearray, you will need to change your code. !audioopfunctions now raise an error immediately if passed string input, instead of failing randomly later on (16685).- The new convert_charrefs argument to
~html.parser.HTMLParsercurrently defaults toFalsefor backward compatibility, but will eventually be changed to default toTrue. It is recommended that you add this keyword, with the appropriate value, to any~html.parser.HTMLParsercalls in your code (13633). - Since the digestmod argument to the
hmac.newfunction will in the future have no default, all calls tohmac.newshould be changed to explicitly specify a digestmod (17276). - Calling
sysconfig.get_config_varwith theSOkey, or lookingSOup in the results of a call tosysconfig.get_config_varsis deprecated. This key should be replaced byEXT_SUFFIXorSHLIB_SUFFIX, depending on the context (19555). - Any calls to
openfunctions that specifyUshould be modified.Uis ineffective in Python3 and will eventually raise an error if used. Depending on the function, the equivalent of its old Python2 behavior can be achieved using either a newline argument, or if necessary by wrapping the stream in~io.TextIOWrapperto use its newline argument (15204). - If you use
pyvenvin a script and desire that pip not be installed, you must add--without-pipto your command invocation. - The default behavior of
json.dumpandjson.dumpswhen an indent is specified has changed: it no longer produces trailing spaces after the item separating commas at the ends of lines. This will matter only if you have tests that are doing white-space-sensitive comparisons of such output (16333). doctestnow looks for doctests in extension module__doc__strings, so if your doctest test discovery includes extension modules that have things that look like doctests in them you may see test failures you've never seen before when running your tests (3158).- The
collections.abcmodule has been slightly refactored as part of the Python startup improvements. As a consequence of this, it is no longer the case that importingcollectionsautomatically importscollections.abc. If your program depended on the (undocumented) implicit import, you will need to add an explicitimport collections.abc(20784).
Changes in the C API
PyEval_EvalFrameEx,PyObject_Repr, andPyObject_Str, along with some other internal C APIs, now include a debugging assertion that ensures they are not used in situations where they may silently discard a currently active exception. In cases where discarding the active exception is expected and desired (for example, because it has already been saved locally withPyErr_Fetchor is being deliberately replaced with a different exception), an explicitPyErr_Clearcall will be needed to avoid triggering the assertion when invoking these operations (directly or indirectly) and running against a version of Python that is compiled with assertions enabled.PyErr_SetImportErrornow setsTypeErrorwhen its msg argument is not set. Previously onlyNULLwas returned with no exception set.- The result of the
PyOS_ReadlineFunctionPointercallback must now be a string allocated byPyMem_RawMallocorPyMem_RawRealloc, orNULLif an error occurred, instead of a string allocated byPyMem_MallocorPyMem_Realloc(16742) PyThread_set_key_valuenow always set the value. In Python 3.3, the function did nothing if the key already exists (if the current value is a non-NULLpointer).- The
f_tstate(thread state) field of thePyFrameObjectstructure has been removed to fix a bug: see14432for the rationale.
Changed in 3.4.3
PEP 476: Enabling certificate verification by default for stdlib http clients
http.client and modules which use it, such as urllib.request and xmlrpc.client, will now verify that the server presents a certificate which is signed by a CA in the platform trust store and whose hostname matches the hostname being requested by default, significantly improving security for many applications.
For applications which require the old previous behavior, they can pass an alternate context:
import urllib.request
import ssl
# This disables all verification
context = ssl._create_unverified_context()
# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")
urllib.request.urlopen("https://invalid-cert", context=context)
What's New In Python 3.5
Editors
Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Mercurial log when researching a change.
This article explains the new features in Python 3.5, compared to 3.4. Python 3.5 was released on September 13, 2015. See the changelog for a full list of changes.
478 - Python 3.5 Release Schedule
Summary -- Release highlights
New syntax features:
PEP 492 <whatsnew-pep-492>, coroutines with async and await syntax.PEP 465 <whatsnew-pep-465>, a new matrix multiplication operator:a @ b.PEP 448 <whatsnew-pep-448>, additional unpacking generalizations.
New library modules:
typing:PEP 484 -- Type Hints <whatsnew-pep-484>.zipapp:PEP 441 Improving Python ZIP Application Support <whatsnew-zipapp>.
New built-in features:
bytes % args,bytearray % args:PEP 461 <whatsnew-pep-461>-- Adding%formatting to bytes and bytearray.- New
bytes.hex,bytearray.hexandmemoryview.hexmethods. (Contributed by Arnon Yaari in9951.) memoryviewnow supports tuple indexing (including multi-dimensional). (Contributed by Antoine Pitrou in23632.)- Generators have a new
gi_yieldfromattribute, which returns the object being iterated byyield fromexpressions. (Contributed by Benno Leslie and Yury Selivanov in24450.) - A new
RecursionErrorexception is now raised when maximum recursion depth is reached. (Contributed by Georg Brandl in19235.)
CPython implementation improvements:
- When the
LC_TYPElocale is the POSIX locale (Clocale),sys.stdinandsys.stdoutnow use thesurrogateescapeerror handler, instead of thestricterror handler. (Contributed by Victor Stinner in19977.) .pyofiles are no longer used and have been replaced by a more flexible scheme that includes the optimization level explicitly in.pycname. (SeePEP 488 overview <whatsnew-pep-488>.)- Builtin and extension modules are now initialized in a multi-phase process, which is similar to how Python modules are loaded. (See
PEP 489 overview <whatsnew-pep-489>.)
Significant improvements in the standard library:
collections.OrderedDictis nowimplemented in C <whatsnew-ordereddict>, which makes it 4 to 100 times faster.- The
sslmodule gainedsupport for Memory BIO <whatsnew-sslmemorybio>, which decouples SSL protocol handling from network IO. - The new
os.scandirfunction provides abetter and significantly faster way <whatsnew-pep-471>of directory traversal. functools.lru_cachehas been mostlyreimplemented in C <whatsnew-lrucache>, yielding much better performance.- The new
subprocess.runfunction provides astreamlined way to run subprocesses <whatsnew-subprocess>. - The
tracebackmodule has been significantlyenhanced <whatsnew-traceback>for improved performance and developer convenience.
Security improvements:
- SSLv3 is now disabled throughout the standard library. It can still be enabled by instantiating a
ssl.SSLContextmanually. (See22638for more details; this change was backported to CPython 3.4 and 2.7.) - HTTP cookie parsing is now stricter, in order to protect against potential injection attacks. (Contributed by Antoine Pitrou in
22796.)
Windows improvements:
- A new installer for Windows has replaced the old MSI. See
using-on-windowsfor more information. - Windows builds now use Microsoft Visual C++ 14.0, and extension modules should use the same.
Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.
New Features
PEP 492 - Coroutines with async and await syntax
492 greatly improves support for asynchronous programming in Python by adding awaitable objects <awaitable>, coroutine functions <coroutine function>, asynchronous iteration <asynchronous iterable>, and asynchronous context managers <asynchronous context manager>.
Coroutine functions are declared using the new async def syntax:
>>> async def coro():
... return 'spam'
Inside a coroutine function, the new await expression can be used to suspend coroutine execution until the result is available. Any object can be awaited, as long as it implements the awaitable protocol by defining the ~object.__await__ method.
PEP 492 also adds async for statement for convenient iteration over asynchronous iterables.
An example of a rudimentary HTTP client written using the new syntax:
import asyncio
async def http_get(domain):
reader, writer = await asyncio.open_connection(domain, 80)
writer.write(b'\r\n'.join([
b'GET / HTTP/1.1',
b'Host: %b' % domain.encode('latin-1'),
b'Connection: close',
b'', b''
]))
async for line in reader:
print('>>>', line)
writer.close()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(http_get('example.com'))
finally:
loop.close()
Similarly to asynchronous iteration, there is a new syntax for asynchronous context managers. The following script:
import asyncio
async def coro(name, lock):
print('coro {}: waiting for lock'.format(name))
async with lock:
print('coro {}: holding the lock'.format(name))
await asyncio.sleep(1)
print('coro {}: releasing the lock'.format(name))
loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
loop.run_until_complete(coros)
finally:
loop.close()
will output:
coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock
Note that both async for and async with can only be used inside a coroutine function declared with async def.
Coroutine functions are intended to be run inside a compatible event loop, such as the asyncio loop <asyncio-event-loop>.
[!NOTE]
3.5.2 Starting with CPython 3.5.2,
__aiter__can directly returnasynchronous iterators <asynchronous iterator>. Returning anawaitableobject will result in aPendingDeprecationWarning.See more details in the
async-iteratorsdocumentation section.
492 -- Coroutines with async and await syntax
PEP written and implemented by Yury Selivanov.
PEP 465 - A dedicated infix operator for matrix multiplication
465 adds the @ infix operator for matrix multiplication. Currently, no builtin Python types implement the new operator, however, it can be implemented by defining ~object.__matmul__, ~object.__rmatmul__, and ~object.__imatmul__ for regular, reflected, and in-place matrix multiplication. The semantics of these methods is similar to that of methods defining other infix arithmetic operators.
Matrix multiplication is a notably common operation in many fields of mathematics, science, engineering, and the addition of @ allows writing cleaner code:
S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)
instead of:
S = dot((dot(H, beta) - r).T,
dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))
NumPy 1.10 has support for the new operator:
>>> import numpy
>>> x = numpy.ones(3)
>>> x
array([ 1., 1., 1.])
>>> m = numpy.eye(3)
>>> m
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x @ m
array([ 1., 1., 1.])
465 -- A dedicated infix operator for matrix multiplication
PEP written by Nathaniel J. Smith; implemented by Benjamin Peterson.
PEP 448 - Additional Unpacking Generalizations
448 extends the allowed uses of the * iterable unpacking operator and ** dictionary unpacking operator. It is now possible to use an arbitrary number of unpackings in function calls <calls>:
>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5
>>> def fn(a, b, c, d):
... print(a, b, c, d)
...
>>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
1 2 3 4
Similarly, tuple, list, set, and dictionary displays allow multiple unpackings (see exprlists and dict):
>>> *range(4), 4
(0, 1, 2, 3, 4)
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}
>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
448 -- Additional Unpacking Generalizations
PEP written by Joshua Landau; implemented by Neil Girdhar, Thomas Wouters, and Joshua Landau.
PEP 461 - percent formatting support for bytes and bytearray
461 adds support for the % interpolation operator <bytes-formatting> to bytes and bytearray.
While interpolation is usually thought of as a string operation, there are cases where interpolation on bytes or bytearrays makes sense, and the work needed to make up for this missing functionality detracts from the overall readability of the code. This issue is particularly important when dealing with wire format protocols, which are often a mixture of binary and ASCII compatible text.
Examples:
>>> b'Hello %b!' % b'World'
b'Hello World!'
>>> b'x=%i y=%f' % (1, 2.5)
b'x=1 y=2.500000'
Unicode is not allowed for %b, but it is accepted by %a (equivalent of repr(obj).encode('ascii', 'backslashreplace')):
>>> b'Hello %b!' % 'World'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'
>>> b'price: %a' % '10€'
b"price: '10\\u20ac'"
Note that %s and %r conversion types, although supported, should only be used in codebases that need compatibility with Python 2.
461 -- Adding % formatting to bytes and bytearray
PEP written by Ethan Furman; implemented by Neil Schemenauer and Ethan Furman.
PEP 484 - Type Hints
Function annotation syntax has been a Python feature since version 3.0 (3107), however the semantics of annotations has been left undefined.
Experience has shown that the majority of function annotation uses were to provide type hints to function parameters and return values. It became evident that it would be beneficial for Python users, if the standard library included the base definitions and tools for type annotations.
484 introduces a provisional module <provisional API> to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.
For example, here is a simple function whose argument and return type are declared in the annotations:
def greeting(name: str) -> str:
return 'Hello ' + name
While these annotations are available at runtime through the usual ~object.__annotations__ attribute, no automatic type checking happens at runtime. Instead, it is assumed that a separate off-line type checker (e.g. mypy) will be used for on-demand source code analysis.
The type system supports unions, generic types, and a special type named ~typing.Any which is consistent with (i.e. assignable to and from) all types.
-
typingmodule documentation -
484-- Type Hints
PEP written by Guido van Rossum, Jukka Lehtosalo, and Łukasz Langa; implemented by Guido van Rossum. -
483-- The Theory of Type Hints
PEP written by Guido van Rossum
PEP 471 - os.scandir() function -- a better and faster directory iterator
471 adds a new directory iteration function, os.scandir, to the standard library. Additionally, os.walk is now implemented using scandir, which makes it 3 to 5 times faster on POSIX systems and 7 to 20 times faster on Windows systems. This is largely achieved by greatly reducing the number of calls to os.stat required to walk a directory tree.
Additionally, scandir returns an iterator, as opposed to returning a list of file names, which improves memory efficiency when iterating over very large directories.
The following example shows a simple use of os.scandir to display all the files (excluding directories) in the given path that don't start with '.'. The entry.is_file() <os.DirEntry.is_file> call will generally not make an additional system call:
for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
471 -- os.scandir() function -- a better and faster directory iterator
PEP written and implemented by Ben Hoyt with the help of Victor Stinner.
PEP 475: Retry system calls failing with EINTR
An errno.EINTR error code is returned whenever a system call, that is waiting for I/O, is interrupted by a signal. Previously, Python would raise InterruptedError in such cases. This meant that, when writing a Python application, the developer had two choices:
- Ignore the
InterruptedError. - Handle the
InterruptedErrorand attempt to restart the interrupted system call at every call site.
The first option makes an application fail intermittently. The second option adds a large amount of boilerplate that makes the code nearly unreadable. Compare:
print("Hello World")
and:
while True:
try:
print("Hello World")
break
except InterruptedError:
continue
475 implements automatic retry of system calls on EINTR. This removes the burden of dealing with EINTR or InterruptedError in user code in most situations and makes Python programs, including the standard library, more robust. Note that the system call is only retried if the signal handler does not raise an exception.
Below is a list of functions which are now retried when interrupted by a signal:
openandio.open;- functions of the
faulthandlermodule; osfunctions:~os.fchdir,~os.fchmod,~os.fchown,~os.fdatasync,~os.fstat,~os.fstatvfs,~os.fsync,~os.ftruncate,~os.mkfifo,~os.mknod,~os.open,~os.posix_fadvise,~os.posix_fallocate,~os.pread,~os.pwrite,~os.read,~os.readv,~os.sendfile,~os.wait3,~os.wait4,~os.wait,~os.waitid,~os.waitpid,~os.write,~os.writev;- special cases:
os.closeandos.dup2now ignore~errno.EINTRerrors; the syscall is not retried (see the PEP for the rationale); selectfunctions:devpoll.poll() <select.devpoll.poll>,epoll.poll() <select.epoll.poll>,kqueue.control() <select.kqueue.control>,poll.poll() <select.poll.poll>,~select.select;- methods of the
~socket.socketclass:~socket.socket.accept,~socket.socket.connect(except for non-blocking sockets),~socket.socket.recv,~socket.socket.recvfrom,~socket.socket.recvmsg,~socket.socket.send,~socket.socket.sendall,~socket.socket.sendmsg,~socket.socket.sendto; signal.sigtimedwaitandsignal.sigwaitinfo;time.sleep.
475 -- Retry system calls failing with EINTR
PEP and implementation written by Charles-François Natali and Victor Stinner, with the help of Antoine Pitrou (the French connection).
PEP 479: Change StopIteration handling inside generators
The interaction of generators and StopIteration in Python 3.4 and earlier was sometimes surprising, and could conceal obscure bugs. Previously, StopIteration raised accidentally inside a generator function was interpreted as the end of the iteration by the loop construct driving the generator.
479 changes the behavior of generators: when a StopIteration exception is raised inside a generator, it is replaced with a RuntimeError before it exits the generator frame. The main goal of this change is to ease debugging in the situation where an unguarded next call raises StopIteration and causes the iteration controlled by the generator to terminate silently. This is particularly pernicious in combination with the yield from construct.
This is a backwards incompatible change, so to enable the new behavior, a __future__ import is necessary:
>>> from __future__ import generator_stop
>>> def gen():
... next(iter([]))
... yield
...
>>> next(gen())
Traceback (most recent call last):
File "<stdin>", line 2, in gen
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
Without a __future__ import, a PendingDeprecationWarning will be raised whenever a StopIteration exception is raised inside a generator.
479 -- Change StopIteration handling inside generators
PEP written by Chris Angelico and Guido van Rossum. Implemented by Chris Angelico, Yury Selivanov and Nick Coghlan.
PEP 485: A function for testing approximate equality
485 adds the math.isclose and cmath.isclose functions which tell whether two values are approximately equal or "close" to each other. Whether or not two values are considered close is determined according to given absolute and relative tolerances. Relative tolerance is the maximum allowed difference between isclose arguments, relative to the larger absolute value:
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False
It is also possible to compare two values using absolute tolerance, which must be a non-negative value:
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False
485 -- A function for testing approximate equality
PEP written by Christopher Barker; implemented by Chris Barker and Tal Einat.
PEP 486: Make the Python Launcher aware of virtual environments
486 makes the Windows launcher (see 397) aware of an active virtual environment. When the default interpreter would be used and the VIRTUAL_ENV environment variable is set, the interpreter in the virtual environment will be used.
486 -- Make the Python Launcher aware of virtual environments
PEP written and implemented by Paul Moore.
PEP 488: Elimination of PYO files
488 does away with the concept of .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode. To prevent the need to constantly regenerate bytecode files, .pyc files now have an optional opt- tag in their name when the bytecode is optimized. This has the side-effect of no more bytecode file name clashes when running under either -O or -OO. Consequently, bytecode files generated from -O, and -OO may now exist simultaneously. importlib.util.cache_from_source has an updated API to help with this change.
488 -- Elimination of PYO files
PEP written and implemented by Brett Cannon.
PEP 489: Multi-phase extension module initialization
489 updates extension module initialization to take advantage of the two step module loading mechanism introduced by 451 in Python 3.4.
This change brings the import semantics of extension modules that opt-in to using the new mechanism much closer to those of Python source and bytecode modules, including the ability to use any valid identifier as a module name, rather than being restricted to ASCII.
489 -- Multi-phase extension module initialization
PEP written by Petr Viktorin, Stefan Behnel, and Nick Coghlan; implemented by Petr Viktorin.
Other Language Changes
Some smaller changes made to the core Python language are:
- Added the
"namereplace"error handlers. The"backslashreplace"error handlers now work with decoding and translating. (Contributed by Serhiy Storchaka in19676and22286.) - The
-boption now affects comparisons ofbyteswithint. (Contributed by Serhiy Storchaka in23681.) - New Kazakh
kz1048and Tajikkoi8_tcodecs <standard-encodings>. (Contributed by Serhiy Storchaka in22682and22681.) - Property docstrings are now writable. This is especially useful for
collections.namedtupledocstrings. (Contributed by Berker Peksag in24064.) - Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in
17636.)
New Modules
typing
The new typing provisional <provisional API> module provides standard definitions and tools for function type annotations. See Type Hints <whatsnew-pep-484> for more information.
zipapp
The new zipapp module (specified in 441) provides an API and command line tool for creating executable Python Zip Applications, which were introduced in Python 2.6 in 1739468, but which were not well publicized, either at the time or since.
With the new module, bundling your application is as simple as putting all the files, including a __main__.py file, into a directory myapp and running:
$ python -m zipapp myapp
$ python myapp.pyz
The module implementation has been contributed by Paul Moore in 23491.
441 -- Improving Python ZIP Application Support
Improved Modules
argparse
The ~argparse.ArgumentParser class now allows disabling abbreviated usage <prefix-matching> of long options by setting allow_abbrev to False. (Contributed by Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson in 14910.)
asyncio
Since the asyncio module is provisional <provisional API>, all changes introduced in Python 3.5 have also been backported to Python 3.4.x.
Notable changes in the asyncio module since Python 3.4.0:
- New debugging APIs:
loop.set_debug() <asyncio.loop.set_debug>andloop.get_debug() <asyncio.loop.get_debug>methods. (Contributed by Victor Stinner.) - The proactor event loop now supports SSL. (Contributed by Antoine Pitrou and Victor Stinner in
22560.) - A new
loop.is_closed() <asyncio.loop.is_closed>method to check if the event loop is closed. (Contributed by Victor Stinner in21326.) - A new
loop.create_task() <asyncio.loop.create_task>to conveniently create and schedule a new~asyncio.Taskfor a coroutine. Thecreate_taskmethod is also used by all asyncio functions that wrap coroutines into tasks, such asasyncio.wait,asyncio.gather, etc. (Contributed by Victor Stinner.) - A new
transport.get_write_buffer_limits() <asyncio.WriteTransport.get_write_buffer_limits>method to inquire for high- and low- water limits of the flow control. (Contributed by Victor Stinner.) - The
!asyncfunction is deprecated in favor of~asyncio.ensure_future. (Contributed by Yury Selivanov.) - New
loop.set_task_factory() <asyncio.loop.set_task_factory>andloop.get_task_factory() <asyncio.loop.get_task_factory>methods to customize the task factory thatloop.create_task() <asyncio.loop.create_task>method uses. (Contributed by Yury Selivanov.) - New
Queue.join() <asyncio.Queue.join>andQueue.task_done() <asyncio.Queue.task_done>queue methods. (Contributed by Victor Stinner.) - The
JoinableQueueclass was removed, in favor of theasyncio.Queueclass. (Contributed by Victor Stinner.)
Updates in 3.5.1:
- The
~asyncio.ensure_futurefunction and all functions that use it, such asloop.run_until_complete() <asyncio.loop.run_until_complete>, now accept all kinds ofawaitable objects <awaitable>. (Contributed by Yury Selivanov.) - New
~asyncio.run_coroutine_threadsafefunction to submit coroutines to event loops from other threads. (Contributed by Vincent Michel.) - New
Transport.is_closing() <asyncio.BaseTransport.is_closing>method to check if the transport is closing or closed. (Contributed by Yury Selivanov.) - The
loop.create_server() <asyncio.loop.create_server>method can now accept a list of hosts. (Contributed by Yann Sionneau.)
Updates in 3.5.2:
- New
loop.create_future() <asyncio.loop.create_future>method to create Future objects. This allows alternative event loop implementations, such as uvloop, to provide a fasterasyncio.Futureimplementation. (Contributed by Yury Selivanov.) - New
loop.get_exception_handler() <asyncio.loop.get_exception_handler>method to get the current exception handler. (Contributed by Yury Selivanov.) - New
StreamReader.readuntil() <asyncio.StreamReader.readuntil>method to read data from the stream until a separator bytes sequence appears. (Contributed by Mark Korenberg.) - The
loop.create_connection() <asyncio.loop.create_connection>andloop.create_server() <asyncio.loop.create_server>methods are optimized to avoid calling the systemgetaddrinfofunction if the address is already resolved. (Contributed by A. Jesse Jiryu Davis.) - The
loop.sock_connect(sock, address) <asyncio.loop.sock_connect>no longer requires the address to be resolved prior to the call. (Contributed by A. Jesse Jiryu Davis.)
bz2
The BZ2Decompressor.decompress <bz2.BZ2Decompressor.decompress> method now accepts an optional max_length argument to limit the maximum size of decompressed data. (Contributed by Nikolaus Rath in 15955.)
cgi
The !FieldStorage class now supports the context manager protocol. (Contributed by Berker Peksag in 20289.)
cmath
A new function ~cmath.isclose provides a way to test for approximate equality. (Contributed by Chris Barker and Tal Einat in 24270.)
code
The InteractiveInterpreter.showtraceback() <code.InteractiveInterpreter.showtraceback> method now prints the full chained traceback, just like the interactive interpreter. (Contributed by Claudiu Popa in 17442.)
collections
The ~collections.OrderedDict class is now implemented in C, which makes it 4 to 100 times faster. (Contributed by Eric Snow in 16991.)
!OrderedDict.items, !OrderedDict.keys, and !OrderedDict.values views now support reversed iteration. (Contributed by Serhiy Storchaka in 19505.)
The ~collections.deque class now defines ~collections.deque.index, ~collections.deque.insert, and ~collections.deque.copy, and supports the + and * operators. This allows deques to be recognized as a ~collections.abc.MutableSequence and improves their substitutability for lists. (Contributed by Raymond Hettinger in 23704.)
Docstrings produced by ~collections.namedtuple can now be updated:
Point = namedtuple('Point', ['x', 'y'])
Point.__doc__ += ': Cartesian coordinate'
Point.x.__doc__ = 'abscissa'
Point.y.__doc__ = 'ordinate'
(Contributed by Berker Peksag in 24064.)
The ~collections.UserString class now implements the ~object.__getnewargs__, ~object.__rmod__, ~str.casefold, ~str.format_map, ~str.isprintable, and ~str.maketrans methods to match the corresponding methods of str. (Contributed by Joe Jevnik in 22189.)
collections.abc
The !Sequence.index method now accepts start and stop arguments to match the corresponding methods of tuple, list, etc. (Contributed by Devin Jeanpierre in 23086.)
A new ~collections.abc.Generator abstract base class. (Contributed by Stefan Behnel in 24018.)
New ~collections.abc.Awaitable, ~collections.abc.Coroutine, ~collections.abc.AsyncIterator, and ~collections.abc.AsyncIterable abstract base classes. (Contributed by Yury Selivanov in 24184.)
For earlier Python versions, a backport of the new ABCs is available in an external PyPI package <backports_abc>.
compileall
A new compileall option, -j {N}, allows running N workers simultaneously to perform parallel bytecode compilation. The ~compileall.compile_dir function has a corresponding workers parameter. (Contributed by Claudiu Popa in 16104.)
Another new option, -r, allows controlling the maximum recursion level for subdirectories. (Contributed by Claudiu Popa in 19628.)
The -q command line option can now be specified more than once, in which case all output, including errors, will be suppressed. The corresponding quiet parameter in ~compileall.compile_dir, ~compileall.compile_file, and ~compileall.compile_path can now accept an integer value indicating the level of output suppression. (Contributed by Thomas Kluyver in 21338.)
concurrent.futures
The Executor.map() <concurrent.futures.Executor.map> method now accepts a chunksize argument to allow batching of tasks to improve performance when ~concurrent.futures.ProcessPoolExecutor is used. (Contributed by Dan O'Reilly in 11271.)
The number of workers in the ~concurrent.futures.ThreadPoolExecutor constructor is optional now. The default value is 5 times the number of CPUs. (Contributed by Claudiu Popa in 21527.)
configparser
configparser now provides a way to customize the conversion of values by specifying a dictionary of converters in the ~configparser.ConfigParser constructor, or by defining them as methods in ConfigParser subclasses. Converters defined in a parser instance are inherited by its section proxies.
Example:
>>> import configparser
>>> conv = {}
>>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
>>> cfg = configparser.ConfigParser(converters=conv)
>>> cfg.read_string("""
... [s]
... list = a b c d e f g
... """)
>>> cfg.get('s', 'list')
'a b c d e f g'
>>> cfg.getlist('s', 'list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> section = cfg['s']
>>> section.getlist('list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
(Contributed by Łukasz Langa in 18159.)
contextlib
The new ~contextlib.redirect_stderr context manager (similar to ~contextlib.redirect_stdout) makes it easier for utility scripts to handle inflexible APIs that write their output to sys.stderr and don't provide any options to redirect it:
>>> import contextlib, io, logging
>>> f = io.StringIO()
>>> with contextlib.redirect_stderr(f):
... logging.warning('warning')
...
>>> f.getvalue()
'WARNING:root:warning\n'
(Contributed by Berker Peksag in 22389.)
csv
The ~csv.csvwriter.writerow method now supports arbitrary iterables, not just sequences. (Contributed by Serhiy Storchaka in 23171.)
curses
The new ~curses.update_lines_cols function updates the ~curses.LINES and ~curses.COLS module variables. This is useful for detecting manual screen resizing. (Contributed by Arnon Yaari in 4254.)
dbm
dumb.open <dbm.dumb.open> always creates a new database when the flag has the value "n". (Contributed by Claudiu Popa in 18039.)
difflib
The charset of HTML documents generated by HtmlDiff.make_file() <difflib.HtmlDiff.make_file> can now be customized by using a new charset keyword-only argument. The default charset of HTML document changed from "ISO-8859-1" to "utf-8". (Contributed by Berker Peksag in 2052.)
The ~difflib.diff_bytes function can now compare lists of byte strings. This fixes a regression from Python 2. (Contributed by Terry J. Reedy and Greg Ward in 17445.)
distutils
Both the build and build_ext commands now accept a -j option to enable parallel building of extension modules. (Contributed by Antoine Pitrou in 5309.)
The distutils module now supports xz compression, and can be enabled by passing xztar as an argument to bdist --format. (Contributed by Serhiy Storchaka in 16314.)
doctest
The ~doctest.DocTestSuite function returns an empty unittest.TestSuite if module contains no docstrings, instead of raising ValueError. (Contributed by Glenn Jones in 15916.)
A new policy option Policy.mangle_from_ <email.policy.Policy.mangle_from_> controls whether or not lines that start with "From " in email bodies are prefixed with a ">" character by generators. The default is True for ~email.policy.compat32 and False for all other policies. (Contributed by Milan Oberkirch in 20098.)
A new Message.get_content_disposition() <email.message.Message.get_content_disposition> method provides easy access to a canonical value for the Content-Disposition header. (Contributed by Abhilash Raj in 21083.)
A new policy option EmailPolicy.utf8 <email.policy.EmailPolicy.utf8> can be set to True to encode email headers using the UTF-8 charset instead of using encoded words. This allows Messages to be formatted according to 6532 and used with an SMTP server that supports the 6531 SMTPUTF8 extension. (Contributed by R. David Murray in 24211.)
The mime.text.MIMEText <email.mime.text.MIMEText> constructor now accepts a charset.Charset <email.charset.Charset> instance. (Contributed by Claude Paroz and Berker Peksag in 16324.)
enum
The ~enum.Enum callable has a new parameter start to specify the initial number of enum values if only names are provided:
>>> Animal = enum.Enum('Animal', 'cat dog', start=10)
>>> Animal.cat
<Animal.cat: 10>
>>> Animal.dog
<Animal.dog: 11>
(Contributed by Ethan Furman in 21706.)
faulthandler
The ~faulthandler.enable, ~faulthandler.register, ~faulthandler.dump_traceback and ~faulthandler.dump_traceback_later functions now accept file descriptors in addition to file-like objects. (Contributed by Wei Wu in 23566.)
functools
Most of the ~functools.lru_cache machinery is now implemented in C, making it significantly faster. (Contributed by Matt Joiner, Alexey Kachayev, and Serhiy Storchaka in 14373.)
glob
The ~glob.iglob and ~glob.glob functions now support recursive search in subdirectories, using the "**" pattern. (Contributed by Serhiy Storchaka in 13968.)
gzip
The mode argument of the ~gzip.GzipFile constructor now accepts "x" to request exclusive creation. (Contributed by Tim Heaney in 19222.)
heapq
Element comparison in ~heapq.merge can now be customized by passing a key function in a new optional key keyword argument, and a new optional reverse keyword argument can be used to reverse element comparison:
>>> import heapq
>>> a = ['9', '777', '55555']
>>> b = ['88', '6666']
>>> list(heapq.merge(a, b, key=len))
['9', '88', '777', '6666', '55555']
>>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
['55555', '6666', '777', '88', '9']
(Contributed by Raymond Hettinger in 13742.)
http
A new HTTPStatus <http.HTTPStatus> enum that defines a set of HTTP status codes, reason phrases and long descriptions written in English. (Contributed by Demian Brecht in 21793.)
http.client
HTTPConnection.getresponse() <http.client.HTTPConnection.getresponse> now raises a ~http.client.RemoteDisconnected exception when a remote server connection is closed unexpectedly. Additionally, if a ConnectionError (of which RemoteDisconnected is a subclass) is raised, the client socket is now closed automatically, and will reconnect on the next request:
import http.client
conn = http.client.HTTPConnection('www.python.org')
for retries in range(3):
try:
conn.request('GET', '/')
resp = conn.getresponse()
except http.client.RemoteDisconnected:
pass
(Contributed by Martin Panter in 3566.)
idlelib and IDLE
Since idlelib implements the IDLE shell and editor and is not intended for import by other programs, it gets improvements with every release. See Lib/idlelib/NEWS.txt for a cumulative list of changes since 3.4.0, as well as changes made in future 3.5.x releases. This file is also available from the IDLE Help --> About IDLE dialog.
imaplib
The ~imaplib.IMAP4 class now supports the context manager protocol. When used in a with statement, the IMAP4 LOGOUT command will be called automatically at the end of the block. (Contributed by Tarek Ziadé and Serhiy Storchaka in 4972.)
The imaplib module now supports 5161 (ENABLE Extension) and 6855 (UTF-8 Support) via the IMAP4.enable() <imaplib.IMAP4.enable> method. A new IMAP4.utf8_enabled <imaplib.IMAP4.utf8_enabled> attribute tracks whether or not 6855 support is enabled. (Contributed by Milan Oberkirch, R. David Murray, and Maciej Szulik in 21800.)
The imaplib module now automatically encodes non-ASCII string usernames and passwords using UTF-8, as recommended by the RFCs. (Contributed by Milan Oberkirch in 21800.)
imghdr
The !what function now recognizes the OpenEXR format (contributed by Martin Vignali and Claudiu Popa in 20295), and the WebP format (contributed by Fabrice Aneche and Claudiu Popa in 20197.)
importlib
The util.LazyLoader <importlib.util.LazyLoader> class allows for lazy loading of modules in applications where startup time is important. (Contributed by Brett Cannon in 17621.)
The abc.InspectLoader.source_to_code() <importlib.abc.InspectLoader.source_to_code> method is now a static method. This makes it easier to initialize a module object with code compiled from a string by running exec(code, module.__dict__). (Contributed by Brett Cannon in 21156.)
The new util.module_from_spec() <importlib.util.module_from_spec> function is now the preferred way to create a new module. As opposed to creating a types.ModuleType instance directly, this new function will set the various import-controlled attributes based on the passed-in spec object. (Contributed by Brett Cannon in 20383.)
inspect
Both the ~inspect.Signature and ~inspect.Parameter classes are now picklable and hashable. (Contributed by Yury Selivanov in 20726 and 20334.)
A new BoundArguments.apply_defaults() <inspect.BoundArguments.apply_defaults> method provides a way to set default values for missing arguments:
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
(Contributed by Yury Selivanov in 24190.)
A new class method Signature.from_callable() <inspect.Signature.from_callable> makes subclassing of ~inspect.Signature easier. (Contributed by Yury Selivanov and Eric Snow in 17373.)
The ~inspect.signature function now accepts a follow_wrapped optional keyword argument, which, when set to False, disables automatic following of __wrapped__ links. (Contributed by Yury Selivanov in 20691.)
A set of new functions to inspect coroutine functions <coroutine function> and coroutine objects <coroutine> has been added: ~inspect.iscoroutine, ~inspect.iscoroutinefunction, ~inspect.isawaitable, ~inspect.getcoroutinelocals, and ~inspect.getcoroutinestate. (Contributed by Yury Selivanov in 24017 and 24400.)
The ~inspect.stack, ~inspect.trace, ~inspect.getouterframes, and ~inspect.getinnerframes functions now return a list of named tuples. (Contributed by Daniel Shahaf in 16808.)
io
A new BufferedIOBase.readinto1() <io.BufferedIOBase.readinto1> method, that uses at most one call to the underlying raw stream's RawIOBase.read() <io.RawIOBase.read> or RawIOBase.readinto() <io.RawIOBase.readinto> methods. (Contributed by Nikolaus Rath in 20578.)
ipaddress
Both the ~ipaddress.IPv4Network and ~ipaddress.IPv6Network classes now accept an (address, netmask) tuple argument, so as to easily construct network objects from existing addresses:
>>> import ipaddress
>>> ipaddress.IPv4Network(('127.0.0.0', 8))
IPv4Network('127.0.0.0/8')
>>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
IPv4Network('127.0.0.0/8')
(Contributed by Peter Moody and Antoine Pitrou in 16531.)
A new ~ipaddress.IPv4Address.reverse_pointer attribute for the ~ipaddress.IPv4Address and ~ipaddress.IPv6Address classes returns the name of the reverse DNS PTR record:
>>> import ipaddress
>>> addr = ipaddress.IPv4Address('127.0.0.1')
>>> addr.reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> addr6 = ipaddress.IPv6Address('::1')
>>> addr6.reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'
(Contributed by Leon Weber in 20480.)
json
The json.tool command line interface now preserves the order of keys in JSON objects passed in input. The new --sort-keys option can be used to sort the keys alphabetically. (Contributed by Berker Peksag in 21650.)
JSON decoder now raises ~json.JSONDecodeError instead of ValueError to provide better context information about the error. (Contributed by Serhiy Storchaka in 19361.)
linecache
A new ~linecache.lazycache function can be used to capture information about a non-file-based module to permit getting its lines later via ~linecache.getline. This avoids doing I/O until a line is actually needed, without having to carry the module globals around indefinitely. (Contributed by Robert Collins in 17911.)
locale
A new ~locale.delocalize function can be used to convert a string into a normalized number string, taking the LC_NUMERIC settings into account:
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
'de_DE.UTF-8'
>>> locale.delocalize('1.234,56')
'1234.56'
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.delocalize('1,234.56')
'1234.56'
(Contributed by Cédric Krier in 13918.)
logging
All logging methods (~logging.Logger ~logging.Logger.log, ~logging.Logger.exception, ~logging.Logger.critical, ~logging.Logger.debug, etc.), now accept exception instances as an exc_info argument, in addition to boolean values and exception tuples:
>>> import logging
>>> try:
... 1/0
... except ZeroDivisionError as ex:
... logging.error('exception', exc_info=ex)
ERROR:root:exception
(Contributed by Yury Selivanov in 20537.)
The handlers.HTTPHandler <logging.handlers.HTTPHandler> class now accepts an optional ssl.SSLContext instance to configure SSL settings used in an HTTP connection. (Contributed by Alex Gaynor in 22788.)
The handlers.QueueListener <logging.handlers.QueueListener> class now takes a respect_handler_level keyword argument which, if set to True, will pass messages to handlers taking handler levels into account. (Contributed by Vinay Sajip.)
lzma
The LZMADecompressor.decompress() <lzma.LZMADecompressor.decompress> method now accepts an optional max_length argument to limit the maximum size of decompressed data. (Contributed by Martin Panter in 15955.)
math
Two new constants have been added to the math module: ~math.inf and ~math.nan. (Contributed by Mark Dickinson in 23185.)
A new function ~math.isclose provides a way to test for approximate equality. (Contributed by Chris Barker and Tal Einat in 24270.)
A new ~math.gcd function has been added. The !fractions.gcd function is now deprecated. (Contributed by Mark Dickinson and Serhiy Storchaka in 22486.)
multiprocessing
operator
~operator.attrgetter, ~operator.itemgetter, and ~operator.methodcaller objects now support pickling. (Contributed by Josh Rosenberg and Serhiy Storchaka in 22955.)
New ~operator.matmul and ~operator.imatmul functions to perform matrix multiplication. (Contributed by Benjamin Peterson in 21176.)
os
The new ~os.scandir function returning an iterator of ~os.DirEntry objects has been added. If possible, ~os.scandir extracts file attributes while scanning a directory, removing the need to perform subsequent system calls to determine file type or attributes, which may significantly improve performance. (Contributed by Ben Hoyt with the help of Victor Stinner in 22524.)
On Windows, a new stat_result.st_file_attributes <os.stat_result.st_file_attributes> attribute is now available. It corresponds to the dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). (Contributed by Ben Hoyt in 21719.)
The ~os.urandom function now uses the getrandom() syscall on Linux 3.17 or newer, and getentropy() on OpenBSD 5.6 and newer, removing the need to use /dev/urandom and avoiding failures due to potential file descriptor exhaustion. (Contributed by Victor Stinner in 22181.)
New ~os.get_blocking and ~os.set_blocking functions allow getting and setting a file descriptor's blocking mode (~os.O_NONBLOCK.) (Contributed by Victor Stinner in 22054.)
The ~os.truncate and ~os.ftruncate functions are now supported on Windows. (Contributed by Steve Dower in 23668.)
There is a new os.path.commonpath function returning the longest common sub-path of each passed pathname. Unlike the os.path.commonprefix function, it always returns a valid path:
>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'
>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
(Contributed by Rafik Draoui and Serhiy Storchaka in 10395.)
pathlib
The new Path.samefile() <pathlib.Path.samefile> method can be used to check whether the path points to the same file as another path, which can be either another ~pathlib.Path object, or a string:
>>> import pathlib
>>> p1 = pathlib.Path('/etc/hosts')
>>> p2 = pathlib.Path('/etc/../etc/hosts')
>>> p1.samefile(p2)
True
(Contributed by Vajrasky Kok and Antoine Pitrou in 19775.)
The Path.mkdir() <pathlib.Path.mkdir> method now accepts a new optional exist_ok argument to match mkdir -p and os.makedirs functionality. (Contributed by Berker Peksag in 21539.)
There is a new Path.expanduser() <pathlib.Path.expanduser> method to expand ~ and ~user prefixes. (Contributed by Serhiy Storchaka and Claudiu Popa in 19776.)
A new Path.home() <pathlib.Path.home> class method can be used to get a ~pathlib.Path instance representing the user’s home directory. (Contributed by Victor Salgado and Mayank Tripathi in 19777.)
New Path.write_text() <pathlib.Path.write_text>, Path.read_text() <pathlib.Path.read_text>, Path.write_bytes() <pathlib.Path.write_bytes>, Path.read_bytes() <pathlib.Path.read_bytes> methods to simplify read/write operations on files.
The following code snippet will create or rewrite existing file ~/spam42:
>>> import pathlib
>>> p = pathlib.Path('~/spam42')
>>> p.expanduser().write_text('ham')
3
(Contributed by Christopher Welborn in 20218.)
pickle
Nested objects, such as unbound methods or nested classes, can now be pickled using pickle protocols <pickle-protocols> older than protocol version 4. Protocol version 4 already supports these cases. (Contributed by Serhiy Storchaka in 23611.)
poplib
A new POP3.utf8() <poplib.POP3.utf8> command enables 6856 (Internationalized Email) support, if a POP server supports it. (Contributed by Milan OberKirch in 21804.)
re
References and conditional references to groups with fixed length are now allowed in lookbehind assertions:
>>> import re
>>> pat = re.compile(r'(a|b).(?<=\1)c')
>>> pat.match('aac')
<_sre.SRE_Match object; span=(0, 3), match='aac'>
>>> pat.match('bbc')
<_sre.SRE_Match object; span=(0, 3), match='bbc'>
(Contributed by Serhiy Storchaka in 9179.)
The number of capturing groups in regular expressions is no longer limited to 100. (Contributed by Serhiy Storchaka in 22437.)
The ~re.sub and ~re.subn functions now replace unmatched groups with empty strings instead of raising an exception. (Contributed by Serhiy Storchaka in 1519638.)
The re.error <re.PatternError> exceptions have new attributes, ~re.PatternError.msg, ~re.PatternError.pattern, ~re.PatternError.pos, ~re.PatternError.lineno, and ~re.PatternError.colno, that provide better context information about the error:
>>> re.compile("""
... (?x)
... .++
... """)
Traceback (most recent call last):
...
sre_constants.error: multiple repeat at position 16 (line 3, column 7)
(Contributed by Serhiy Storchaka in 22578.)
readline
A new ~readline.append_history_file function can be used to append the specified number of trailing elements in history to the given file. (Contributed by Bruno Cauet in 22940.)
selectors
The new ~selectors.DevpollSelector supports efficient /dev/poll polling on Solaris. (Contributed by Giampaolo Rodola' in 18931.)
shutil
The ~shutil.move function now accepts a copy_function argument, allowing, for example, the ~shutil.copy function to be used instead of the default ~shutil.copy2 if there is a need to ignore file metadata when moving. (Contributed by Claudiu Popa in 19840.)
The ~shutil.make_archive function now supports the xztar format. (Contributed by Serhiy Storchaka in 5411.)
signal
On Windows, the ~signal.set_wakeup_fd function now also supports socket handles. (Contributed by Victor Stinner in 22018.)
Various SIG* constants in the signal module have been converted into Enums <enum>. This allows meaningful names to be printed during debugging, instead of integer "magic numbers". (Contributed by Giampaolo Rodola' in 21076.)
smtpd
Both the !SMTPServer and !SMTPChannel classes now accept a decode_data keyword argument to determine if the DATA portion of the SMTP transaction is decoded using the "utf-8" codec or is instead provided to the !SMTPServer.process_message method as a byte string. The default is True for backward compatibility reasons, but will change to False in Python 3.6. If decode_data is set to False, the process_message method must be prepared to accept keyword arguments. (Contributed by Maciej Szulik in 19662.)
The !SMTPServer class now advertises the 8BITMIME extension (6152) if decode_data has been set True. If the client specifies BODY=8BITMIME on the MAIL command, it is passed to !SMTPServer.process_message via the mail_options keyword. (Contributed by Milan Oberkirch and R. David Murray in 21795.)
The !SMTPServer class now also supports the SMTPUTF8 extension (6531: Internationalized Email). If the client specified SMTPUTF8 BODY=8BITMIME on the MAIL command, they are passed to !SMTPServer.process_message via the mail_options keyword. It is the responsibility of the process_message method to correctly handle the SMTPUTF8 data. (Contributed by Milan Oberkirch in 21725.)
It is now possible to provide, directly or via name resolution, IPv6 addresses in the !SMTPServer constructor, and have it successfully connect. (Contributed by Milan Oberkirch in 14758.)
smtplib
A new SMTP.auth() <smtplib.SMTP.auth> method provides a convenient way to implement custom authentication mechanisms. (Contributed by Milan Oberkirch in 15014.)
The SMTP.set_debuglevel() <smtplib.SMTP.set_debuglevel> method now accepts an additional debuglevel (2), which enables timestamps in debug messages. (Contributed by Gavin Chappell and Maciej Szulik in 16914.)
Both the SMTP.sendmail() <smtplib.SMTP.sendmail> and SMTP.send_message() <smtplib.SMTP.send_message> methods now support 6531 (SMTPUTF8). (Contributed by Milan Oberkirch and R. David Murray in 22027.)
sndhdr
The !what and !whathdr functions now return a ~collections.namedtuple. (Contributed by Claudiu Popa in 18615.)
socket
Functions with timeouts now use a monotonic clock, instead of a system clock. (Contributed by Victor Stinner in 22043.)
A new socket.sendfile() <socket.socket.sendfile> method allows sending a file over a socket by using the high-performance os.sendfile function on UNIX, resulting in uploads being from 2 to 3 times faster than when using plain socket.send() <socket.socket.send>. (Contributed by Giampaolo Rodola' in 17552.)
The socket.sendall() <socket.socket.sendall> method no longer resets the socket timeout every time bytes are received or sent. The socket timeout is now the maximum total duration to send all data. (Contributed by Victor Stinner in 23853.)
The backlog argument of the socket.listen() <socket.socket.listen> method is now optional. By default it is set to SOMAXCONN <socket.SOMAXCONN> or to 128, whichever is less. (Contributed by Charles-François Natali in 21455.)
ssl
Memory BIO Support
(Contributed by Geert Jansen in 21965.)
The new ~ssl.SSLObject class has been added to provide SSL protocol support for cases when the network I/O capabilities of ~ssl.SSLSocket are not necessary or are suboptimal. SSLObject represents an SSL protocol instance, but does not implement any network I/O methods, and instead provides a memory buffer interface. The new ~ssl.MemoryBIO class can be used to pass data between Python and an SSL protocol instance.
The memory BIO SSL support is primarily intended to be used in frameworks implementing asynchronous I/O for which ~ssl.SSLSocket's readiness model ("select/poll") is inefficient.
A new SSLContext.wrap_bio() <ssl.SSLContext.wrap_bio> method can be used to create a new SSLObject instance.
Application-Layer Protocol Negotiation Support
(Contributed by Benjamin Peterson in 20188.)
Where OpenSSL support is present, the ssl module now implements the Application-Layer Protocol Negotiation TLS extension as described in 7301.
The new SSLContext.set_alpn_protocols() <ssl.SSLContext.set_alpn_protocols> can be used to specify which protocols a socket should advertise during the TLS handshake.
The new SSLSocket.selected_alpn_protocol() <ssl.SSLSocket.selected_alpn_protocol> returns the protocol that was selected during the TLS handshake. The ~ssl.HAS_ALPN flag indicates whether ALPN support is present.
Other Changes
There is a new SSLSocket.version() <ssl.SSLSocket.version> method to query the actual protocol version in use. (Contributed by Antoine Pitrou in 20421.)
The ~ssl.SSLSocket class now implements a !SSLSocket.sendfile method. (Contributed by Giampaolo Rodola' in 17552.)
The !SSLSocket.send method now raises either the ssl.SSLWantReadError or ssl.SSLWantWriteError exception on a non-blocking socket if the operation would block. Previously, it would return 0. (Contributed by Nikolaus Rath in 20951.)
The ~ssl.cert_time_to_seconds function now interprets the input time as UTC and not as local time, per 5280. Additionally, the return value is always an int. (Contributed by Akira Li in 19940.)
The SSLSocket.do_handshake() <ssl.SSLSocket.do_handshake>, SSLSocket.read() <ssl.SSLSocket.read>, !SSLSocket.shutdown, and SSLSocket.write() <ssl.SSLSocket.write> methods of the ~ssl.SSLSocket class no longer reset the socket timeout every time bytes are received or sent. The socket timeout is now the maximum total duration of the method. (Contributed by Victor Stinner in 23853.)
The !match_hostname function now supports matching of IP addresses. (Contributed by Antoine Pitrou in 23239.)
sqlite3
The ~sqlite3.Row class now fully supports the sequence protocol, in particular reversed iteration and slice indexing. (Contributed by Claudiu Popa in 10203; by Lucas Sinclair, Jessica McKellar, and Serhiy Storchaka in 13583.)
subprocess
The new ~subprocess.run function has been added. It runs the specified command and returns a ~subprocess.CompletedProcess object, which describes a finished process. The new API is more consistent and is the recommended approach to invoking subprocesses in Python code that does not need to maintain compatibility with earlier Python versions. (Contributed by Thomas Kluyver in 23342.)
Examples:
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
sys
A new !set_coroutine_wrapper function allows setting a global hook that will be called whenever a coroutine object <coroutine> is created by an async def function. A corresponding !get_coroutine_wrapper can be used to obtain a currently set wrapper. Both functions are provisional <provisional API>, and are intended for debugging purposes only. (Contributed by Yury Selivanov in 24017.)
A new ~sys.is_finalizing function can be used to check if the Python interpreter is shutting down <interpreter shutdown>. (Contributed by Antoine Pitrou in 22696.)
sysconfig
The name of the user scripts directory on Windows now includes the first two components of the Python version. (Contributed by Paul Moore in 23437.)
tarfile
The mode argument of the ~tarfile.open function now accepts "x" to request exclusive creation. (Contributed by Berker Peksag in 21717.)
The TarFile.extractall() <tarfile.TarFile.extractall> and TarFile.extract() <tarfile.TarFile.extract> methods now take a keyword argument numeric_owner. If set to True, the extracted files and directories will be owned by the numeric uid and gid from the tarfile. If set to False (the default, and the behavior in versions prior to 3.5), they will be owned by the named user and group in the tarfile. (Contributed by Michael Vogt and Eric Smith in 23193.)
The TarFile.list() <tarfile.TarFile.list> now accepts an optional members keyword argument that can be set to a subset of the list returned by TarFile.getmembers() <tarfile.TarFile.getmembers>. (Contributed by Serhiy Storchaka in 21549.)
threading
Both the Lock.acquire() <threading.Lock.acquire> and RLock.acquire() <threading.RLock.acquire> methods now use a monotonic clock for timeout management. (Contributed by Victor Stinner in 22043.)
time
The ~time.monotonic function is now always available. (Contributed by Victor Stinner in 22043.)
timeit
A new command line option -u or --unit={U} can be used to specify the time unit for the timer output. Supported options are usec, msec, or sec. (Contributed by Julian Gindi in 18983.)
The ~timeit.timeit function has a new globals parameter for specifying the namespace in which the code will be running. (Contributed by Ben Roberts in 2527.)
tkinter
The !tkinter._fix module used for setting up the Tcl/Tk environment on Windows has been replaced by a private function in the !_tkinter module which makes no permanent changes to environment variables. (Contributed by Zachary Ware in 20035.)
traceback
New ~traceback.walk_stack and ~traceback.walk_tb functions to conveniently traverse frame and traceback objects <traceback-objects>. (Contributed by Robert Collins in 17911.)
New lightweight classes: ~traceback.TracebackException, ~traceback.StackSummary, and ~traceback.FrameSummary. (Contributed by Robert Collins in 17911.)
Both the ~traceback.print_tb and ~traceback.print_stack functions now support negative values for the limit argument. (Contributed by Dmitry Kazakov in 22619.)
types
A new ~types.coroutine function to transform generator <generator iterator> and generator-like <collections.abc.Generator> objects into awaitables <awaitable>. (Contributed by Yury Selivanov in 24017.)
A new type called ~types.CoroutineType, which is used for coroutine objects created by async def functions. (Contributed by Yury Selivanov in 24400.)
unicodedata
The unicodedata module now uses data from Unicode 8.0.0.
unittest
The TestLoader.loadTestsFromModule() <unittest.TestLoader.loadTestsFromModule> method now accepts a keyword-only argument pattern which is passed to load_tests as the third argument. Found packages are now checked for load_tests regardless of whether their path matches pattern, because it is impossible for a package name to match the default pattern. (Contributed by Robert Collins and Barry A. Warsaw in 16662.)
Unittest discovery errors now are exposed in the TestLoader.errors <unittest.TestLoader.errors> attribute of the ~unittest.TestLoader instance. (Contributed by Robert Collins in 19746.)
A new command line option --locals to show local variables in tracebacks. (Contributed by Robert Collins in 22936.)
unittest.mock
The ~unittest.mock.Mock class has the following improvements:
- The class constructor has a new unsafe parameter, which causes mock objects to raise
AttributeErroron attribute names starting with"assert". (Contributed by Kushal Das in21238.) - A new
Mock.assert_not_called() <unittest.mock.Mock.assert_not_called>method to check if the mock object was called. (Contributed by Kushal Das in21262.)
The ~unittest.mock.MagicMock class now supports ~object.__truediv__, ~object.__divmod__ and ~object.__matmul__ operators. (Contributed by Johannes Baiter in 20968, and Håkan Lövdahl in 23581 and 23568.)
It is no longer necessary to explicitly pass create=True to the ~unittest.mock.patch function when patching builtin names. (Contributed by Kushal Das in 17660.)
urllib
A new request.HTTPPasswordMgrWithPriorAuth <urllib.request.HTTPPasswordMgrWithPriorAuth> class allows HTTP Basic Authentication credentials to be managed so as to eliminate unnecessary 401 response handling, or to unconditionally send credentials on the first request in order to communicate with servers that return a 404 response instead of a 401 if the Authorization header is not sent. (Contributed by Matej Cepl in 19494 and Akshit Khurana in 7159.)
A new quote_via argument for the parse.urlencode() <urllib.parse.urlencode> function provides a way to control the encoding of query parts if needed. (Contributed by Samwyse and Arnon Yaari in 13866.)
The request.urlopen() <urllib.request.urlopen> function accepts an ssl.SSLContext object as a context argument, which will be used for the HTTPS connection. (Contributed by Alex Gaynor in 22366.)
The parse.urljoin() <urllib.parse.urljoin> was updated to use the 3986 semantics for the resolution of relative URLs, rather than 1808 and 2396. (Contributed by Demian Brecht and Senthil Kumaran in 22118.)
wsgiref
The headers argument of the headers.Headers <wsgiref.headers.Headers> class constructor is now optional. (Contributed by Pablo Torres Navarrete and SilentGhost in 5800.)
xmlrpc
The client.ServerProxy <xmlrpc.client.ServerProxy> class now supports the context manager protocol. (Contributed by Claudiu Popa in 20627.)
The client.ServerProxy <xmlrpc.client.ServerProxy> constructor now accepts an optional ssl.SSLContext instance. (Contributed by Alex Gaynor in 22960.)
xml.sax
SAX parsers now support a character stream of the xmlreader.InputSource <xml.sax.xmlreader.InputSource> object. (Contributed by Serhiy Storchaka in 2175.)
~xml.sax.parseString now accepts a str instance. (Contributed by Serhiy Storchaka in 10590.)
zipfile
ZIP output can now be written to unseekable streams. (Contributed by Serhiy Storchaka in 23252.)
The mode argument of ZipFile.open() <zipfile.ZipFile.open> method now accepts "x" to request exclusive creation. (Contributed by Serhiy Storchaka in 21717.)
Other module-level changes
Many functions in the mmap, !ossaudiodev, socket, ssl, and codecs modules now accept writable bytes-like objects <bytes-like object>. (Contributed by Serhiy Storchaka in 23001.)
Optimizations
The os.walk function has been sped up by 3 to 5 times on POSIX systems, and by 7 to 20 times on Windows. This was done using the new os.scandir function, which exposes file information from the underlying readdir or FindFirstFile/FindNextFile system calls. (Contributed by Ben Hoyt with help from Victor Stinner in 23605.)
Construction of bytes(int) (filled by zero bytes) is faster and uses less memory for large objects. calloc() is used instead of malloc() to allocate memory for these objects. (Contributed by Victor Stinner in 21233.)
Some operations on ipaddress ~ipaddress.IPv4Network and ~ipaddress.IPv6Network have been massively sped up, such as ~ipaddress.IPv4Network.subnets, ~ipaddress.IPv4Network.supernet, ~ipaddress.summarize_address_range, ~ipaddress.collapse_addresses. The speed up can range from 3 to 15 times. (Contributed by Antoine Pitrou, Michel Albert, and Markus in 21486, 21487, 20826, 23266.)
Pickling of ipaddress objects was optimized to produce significantly smaller output. (Contributed by Serhiy Storchaka in 23133.)
Many operations on io.BytesIO are now 50% to 100% faster. (Contributed by Serhiy Storchaka in 15381 and David Wilson in 22003.)
The marshal.dumps function is now faster: 65--85% with versions 3 and 4, 20--25% with versions 0 to 2 on typical data, and up to 5 times in best cases. (Contributed by Serhiy Storchaka in 20416 and 23344.)
The UTF-32 encoder is now 3 to 7 times faster. (Contributed by Serhiy Storchaka in 15027.)
Regular expressions are now parsed up to 10% faster. (Contributed by Serhiy Storchaka in 19380.)
The json.dumps function was optimized to run with ensure_ascii=False as fast as with ensure_ascii=True. (Contributed by Naoki Inada in 23206.)
The PyObject_IsInstance and PyObject_IsSubclass functions have been sped up in the common case that the second argument has type as its metaclass. (Contributed Georg Brandl by in 22540.)
Method caching was slightly improved, yielding up to 5% performance improvement in some benchmarks. (Contributed by Antoine Pitrou in 22847.)
Objects from the random module now use 50% less memory on 64-bit builds. (Contributed by Serhiy Storchaka in 23488.)
The property getter calls are up to 25% faster. (Contributed by Joe Jevnik in 23910.)
Instantiation of fractions.Fraction is now up to 30% faster. (Contributed by Stefan Behnel in 22464.)
String methods ~str.find, ~str.rfind, ~str.split, ~str.partition and the in string operator are now significantly faster for searching 1-character substrings. (Contributed by Serhiy Storchaka in 23573.)
Build and C API Changes
New calloc functions were added:
PyMem_RawCalloc,PyMem_Calloc,PyObject_Calloc.
(Contributed by Victor Stinner in 21233.)
New encoding/decoding helper functions:
Py_DecodeLocale(replaced_Py_char2wchar()),Py_EncodeLocale(replaced_Py_wchar2char()).
(Contributed by Victor Stinner in 18395.)
A new PyCodec_NameReplaceErrors function to replace the unicode encode error with \N{...} escapes. (Contributed by Serhiy Storchaka in 19676.)
A new PyErr_FormatV function similar to PyErr_Format, but accepts a va_list argument. (Contributed by Antoine Pitrou in 18711.)
A new PyExc_RecursionError exception. (Contributed by Georg Brandl in 19235.)
New PyModule_FromDefAndSpec, PyModule_FromDefAndSpec2, and PyModule_ExecDef functions introduced by 489 -- multi-phase extension module initialization. (Contributed by Petr Viktorin in 24268.)
New PyNumber_MatrixMultiply and PyNumber_InPlaceMatrixMultiply functions to perform matrix multiplication. (Contributed by Benjamin Peterson in 21176. See also 465 for details.)
The PyTypeObject.tp_finalize slot is now part of the stable ABI.
Windows builds now require Microsoft Visual C++ 14.0, which is available as part of Visual Studio 2015.
Extension modules now include a platform information tag in their filename on some platforms (the tag is optional, and CPython will import extensions without it, although if the tag is present and mismatched, the extension won't be loaded):
- On Linux, extension module filenames end with
.cpython-<major><minor>m-<architecture>-<os>.pyd:<major>is the major number of the Python version; for Python 3.5 this is3.<minor>is the minor number of the Python version; for Python 3.5 this is5.<architecture>is the hardware architecture the extension module was built to run on. It's most commonly eitheri386for 32-bit Intel platforms orx86_64for 64-bit Intel (and AMD) platforms.<os>is alwayslinux-gnu, except for extensions built to talk to the 32-bit ABI on 64-bit platforms, in which case it islinux-gnu32(and<architecture>will bex86_64).
- On Windows, extension module filenames end with
<debug>.cp<major><minor>-<platform>.pyd:<major>is the major number of the Python version; for Python 3.5 this is3.<minor>is the minor number of the Python version; for Python 3.5 this is5.<platform>is the platform the extension module was built for, eitherwin32for Win32,win_amd64for Win64,win_ia64for Windows Itanium 64, andwin_armfor Windows on ARM.- If built in debug mode,
<debug>will be_d, otherwise it will be blank.
- On OS X platforms, extension module filenames now end with
-darwin.so. - On all other platforms, extension module filenames are the same as they were with Python 3.4.
Deprecated
New Keywords
async and await are not recommended to be used as variable, class, function or module names. Introduced by 492 in Python 3.5, they will become proper keywords in Python 3.7.
Deprecated Python Behavior
Raising the StopIteration exception inside a generator will now generate a silent PendingDeprecationWarning, which will become a non-silent deprecation warning in Python 3.6 and will trigger a RuntimeError in Python 3.7. See PEP 479: Change StopIteration handling inside generators <whatsnew-pep-479> for details.
Unsupported Operating Systems
Windows XP is no longer supported by Microsoft, thus, per PEP 11, CPython 3.5 is no longer officially supported on this OS.
Deprecated Python modules, functions and methods
The !formatter module has now graduated to full deprecation and is still slated for removal in Python 3.6.
The !asyncio.async function is deprecated in favor of ~asyncio.ensure_future.
The !smtpd module has in the past always decoded the DATA portion of email messages using the utf-8 codec. This can now be controlled by the new decode_data keyword to !SMTPServer. The default value is True, but this default is deprecated. Specify the decode_data keyword with an appropriate value to avoid the deprecation warning.
Directly assigning values to the ~http.cookies.Morsel.key, ~http.cookies.Morsel.value and ~http.cookies.Morsel.coded_value of http.cookies.Morsel objects is deprecated. Use the ~http.cookies.Morsel.set method instead. In addition, the undocumented LegalChars parameter of ~http.cookies.Morsel.set is deprecated, and is now ignored.
Passing a format string as keyword argument format_string to the ~string.Formatter.format method of the string.Formatter class has been deprecated. (Contributed by Serhiy Storchaka in 23671.)
The !platform.dist and !platform.linux_distribution functions are now deprecated. Linux distributions use too many different ways of describing themselves, so the functionality is left to a package. (Contributed by Vajrasky Kok and Berker Peksag in 1322.)
The previously undocumented from_function and from_builtin methods of inspect.Signature are deprecated. Use the new Signature.from_callable() <inspect.Signature.from_callable> method instead. (Contributed by Yury Selivanov in 24248.)
The !inspect.getargspec function is deprecated and scheduled to be removed in Python 3.6. (See 20438 for details.)
The inspect ~inspect.getfullargspec, ~inspect.getcallargs, and !formatargspec functions are deprecated in favor of the inspect.signature API. (Contributed by Yury Selivanov in 20438.)
~inspect.getargvalues and ~inspect.formatargvalues functions were inadvertently marked as deprecated with the release of Python 3.5.0.
Use of re.LOCALE flag with str patterns or re.ASCII is now deprecated. (Contributed by Serhiy Storchaka in 22407.)
Use of unrecognized special sequences consisting of '\' and an ASCII letter in regular expression patterns and replacement patterns now raises a deprecation warning and will be forbidden in Python 3.6. (Contributed by Serhiy Storchaka in 23622.)
The undocumented and unofficial use_load_tests default argument of the unittest.TestLoader.loadTestsFromModule method now is deprecated and ignored. (Contributed by Robert Collins and Barry A. Warsaw in 16662.)
Removed
API and Feature Removals
The following obsolete and previously deprecated APIs and features have been removed:
- The
__version__attribute has been dropped from the email package. The email code hasn't been shipped separately from the stdlib for a long time, and the__version__string was not updated in the last few releases. - The internal
Netrcclass in theftplibmodule was deprecated in 3.4, and has now been removed. (Contributed by Matt Chaput in6623.) - The concept of
.pyofiles has been removed. - The JoinableQueue class in the provisional
asynciomodule was deprecated in 3.4.4 and is now removed. (Contributed by A. Jesse Jiryu Davis in23464.)
Porting to Python 3.5
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in Python behavior
-
Due to an oversight, earlier Python versions erroneously accepted the following syntax:
f(1 for x in [1], *args) f(1 for x in [1], **kwargs)Python 3.5 now correctly raises a
SyntaxError, as generator expressions must be put in parentheses if not a sole argument to a function.
Changes in the Python API
475: System calls are now retried when interrupted by a signal instead of raisingInterruptedErrorif the Python signal handler does not raise an exception.- Before Python 3.5, a
datetime.timeobject was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See13936for full details. - The
!ssl.SSLSocket.sendmethod now raises eitherssl.SSLWantReadErrororssl.SSLWantWriteErroron a non-blocking socket if the operation would block. Previously, it would return0. (Contributed by Nikolaus Rath in20951.) - The
__name__attribute of generators is now set from the function name, instead of being set from the code name. Usegen.gi_code.co_nameto retrieve the code name. Generators also have a new__qualname__attribute, the qualified name, which is now used for the representation of a generator (repr(gen)). (Contributed by Victor Stinner in21205.) - The deprecated "strict" mode and argument of
~html.parser.HTMLParser,!HTMLParser.error, and the!HTMLParserErrorexception have been removed. (Contributed by Ezio Melotti in15114.) The convert_charrefs argument of~html.parser.HTMLParseris nowTrueby default. (Contributed by Berker Peksag in21047.) - Although it is not formally part of the API, it is worth noting for porting purposes (ie: fixing tests) that error messages that were previously of the form "'sometype' does not support the buffer protocol" are now of the form "a
bytes-like objectis required, not 'sometype'". (Contributed by Ezio Melotti in16518.) - If the current directory is set to a directory that no longer exists then
FileNotFoundErrorwill no longer be raised and instead~importlib.machinery.FileFinder.find_specwill returnNonewithout cachingNoneinsys.path_importer_cache, which is different than the typical case (22834). - HTTP status code and messages from
http.clientandhttp.serverwere refactored into a common~http.HTTPStatusenum. The values inhttp.clientandhttp.serverremain available for backwards compatibility. (Contributed by Demian Brecht in21793.) - When an import loader defines
~importlib.abc.Loader.exec_moduleit is now expected to also define~importlib.abc.Loader.create_module(raises aDeprecationWarningnow, will be an error in Python 3.6). If the loader inherits fromimportlib.abc.Loaderthen there is nothing to do, else simply define~importlib.abc.Loader.create_moduleto returnNone. (Contributed by Brett Cannon in23014.) - The
re.splitfunction always ignored empty pattern matches, so the"x*"pattern worked the same as"x+", and the"\b"pattern never worked. Nowre.splitraises a warning if the pattern could match an empty string. For compatibility, use patterns that never match an empty string (e.g."x+"instead of"x*"). Patterns that could only match an empty string (such as"\b") now raise an error. (Contributed by Serhiy Storchaka in22818.) - The
http.cookies.Morseldict-like interface has been made self consistent: morsel comparison now takes the~http.cookies.Morsel.keyand~http.cookies.Morsel.valueinto account,~http.cookies.Morsel.copynow results in a~http.cookies.Morselinstance rather than adict, and~http.cookies.Morsel.updatewill now raise an exception if any of the keys in the update dictionary are invalid. In addition, the undocumented LegalChars parameter of~http.cookies.Morsel.setis deprecated and is now ignored. (Contributed by Demian Brecht in2211.) 488has removed.pyofiles from Python and introduced the optionalopt-tag in.pycfile names. Theimportlib.util.cache_from_sourcehas gained an optimization parameter to help control theopt-tag. Because of this, the debug_override parameter of the function is now deprecated..pyofiles are also no longer supported as a file argument to the Python interpreter and thus serve no purpose when distributed on their own (i.e. sourceless code distribution). Due to the fact that the magic number for bytecode has changed in Python 3.5, all old.pyofiles from previous versions of Python are invalid regardless of this PEP.- The
socketmodule now exports the~socket.CAN_RAW_FD_FRAMESconstant on linux 3.6 and greater. - The
ssl.cert_time_to_secondsfunction now interprets the input time as UTC and not as local time, per5280. Additionally, the return value is always anint. (Contributed by Akira Li in19940.) - The
pygettext.pyTool now uses the standard +NNNN format for timezones in the POT-Creation-Date header. - The
smtplibmodule now usessys.stderrinstead of the previous module-level!stderrvariable for debug output. If your (test) program depends on patching the module-level variable to capture the debug output, you will need to update it to capture sys.stderr instead. - The
str.startswithandstr.endswithmethods no longer returnTruewhen finding the empty string and the indexes are completely out of range. (Contributed by Serhiy Storchaka in24284.) - The
inspect.getdocfunction now returns documentation strings inherited from base classes. Documentation strings no longer need to be duplicated if the inherited documentation is appropriate. To suppress an inherited string, an empty string must be specified (or the documentation may be filled in). This change affects the output of thepydocmodule and thehelpfunction. (Contributed by Serhiy Storchaka in15582.) - Nested
functools.partialcalls are now flattened. If you were relying on the previous behavior, you can now either add an attribute to afunctools.partialobject or you can create a subclass offunctools.partial. (Contributed by Alexander Belopolsky in7830.)
Changes in the C API
- The undocumented
!formatmember of the (non-public)!PyMemoryViewObjectstructure has been removed. All extensions relying on the relevant parts inmemoryobject.hmust be rebuilt. - The
!PyMemAllocatorstructure was renamed toPyMemAllocatorExand a newcallocfield was added. - Removed non-documented macro
!PyObject_REPR()which leaked references. Use format character%RinPyUnicode_FromFormat-like functions to format thereprof the object. (Contributed by Serhiy Storchaka in22453.) - Because the lack of the
~type.__module__attribute breaks pickling and introspection, a deprecation warning is now raised for builtin types without the~type.__module__attribute. This will be anAttributeErrorin the future. (Contributed by Serhiy Storchaka in20204.) - As part of the
492implementation, thetp_reservedslot ofPyTypeObjectwas replaced with a~PyTypeObject.tp_as_asyncslot. Refer tocoro-objectsfor new types, structures and functions.
Notable changes in Python 3.5.4
New make regen-all build target
To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.
Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).
More selective regeneration targets are also defined - see Makefile.pre.in for details.
(Contributed by Victor Stinner in 23404.)
3.5.4
Removal of make touch build target
The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.
It has been replaced by the new make regen-all target.
(Contributed by Victor Stinner in 23404.)
3.5.4
What's New In Python 3.6
Editors
Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Mercurial log when researching a change.
This article explains the new features in Python 3.6, compared to 3.5. Python 3.6 was released on December 23, 2016. See the changelog for a full list of changes.
494 - Python 3.6 Release Schedule
Summary -- Release highlights
New syntax features:
PEP 498 <whatsnew36-pep498>, formatted string literals.PEP 515 <whatsnew36-pep515>, underscores in numeric literals.PEP 526 <whatsnew36-pep526>, syntax for variable annotations.PEP 525 <whatsnew36-pep525>, asynchronous generators.PEP 530 <whatsnew36-pep530>: asynchronous comprehensions.
New library modules:
secrets:PEP 506 -- Adding A Secrets Module To The Standard Library <whatsnew36-pep506>.
CPython implementation improvements:
- The
dict <typesmapping>type has been reimplemented to use amore compact representation <whatsnew36-compactdict>based on a proposal by Raymond Hettinger and similar to the PyPy dict implementation. This resulted in dictionaries using 20% to 25% less memory when compared to Python 3.5. - Customization of class creation has been simplified with the
new protocol <whatsnew36-pep487>. - The class attribute definition order is
now preserved <whatsnew36-pep520>. - The order of elements in
**kwargsnowcorresponds to the order <whatsnew36-pep468>in which keyword arguments were passed to the function. - DTrace and SystemTap
probing support <whatsnew36-tracing>has been added. - The new
PYTHONMALLOC <whatsnew36-pythonmalloc>environment variable can now be used to debug the interpreter memory allocation and access errors.
Significant improvements in the standard library:
- The
asynciomodule has received new features, significant usability and performance improvements, and a fair amount of bug fixes. Starting with Python 3.6 theasynciomodule is no longer provisional and its API is considered stable. - A new
file system path protocol <whatsnew36-pep519>has been implemented to supportpath-like objects <path-like object>. All standard library functions operating on paths have been updated to work with the new protocol. - The
datetimemodule has gained support forLocal Time Disambiguation <whatsnew36-pep495>. - The
typingmodule received a number ofimprovements <whatsnew36-typing>. - The
tracemallocmodule has been significantly reworked and is now used to provide better output forResourceWarningas well as provide better diagnostics for memory allocation errors. See thePYTHONMALLOC section <whatsnew36-pythonmalloc>for more information.
Security improvements:
- The new
secretsmodule has been added to simplify the generation of cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar. - On Linux,
os.urandomnow blocks until the system urandom entropy pool is initialized to increase the security. See the524for the rationale. - The
hashlibandsslmodules now support OpenSSL 1.1.0. - The default settings and feature set of the
sslmodule have been improved. - The
hashlibmodule received support for the BLAKE2, SHA-3 and SHAKE hash algorithms and the~hashlib.scryptkey derivation function.
Windows improvements:
PEP 528 <whatsnew36-pep528>andPEP 529 <whatsnew36-pep529>, Windows filesystem and console encoding changed to UTF-8.- The
py.exelauncher, when used interactively, no longer prefers Python 2 over Python 3 when the user doesn't specify a version (via command line arguments or a config file). Handling of shebang lines remains unchanged - "python" refers to Python 2 in that case. python.exeandpythonw.exehave been marked as long-path aware, which means that the 260 character path limit may no longer apply. Seeremoving the MAX_PATH limitation <max-path>for details.- A
._pthfile can be added to force isolated mode and fully specify all search paths to avoid registry and environment lookup. Seethe documentation <windows_finding_modules>for more information. - A
python36.zipfile now works as a landmark to inferPYTHONHOME. Seethe documentation <windows_finding_modules>for more information.
New Features
PEP 498: Formatted string literals
498 introduces a new kind of string literals: f-strings, or formatted string literals <f-strings>.
Formatted string literals are prefixed with 'f' and are similar to the format strings accepted by str.format. They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format protocol:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
498 -- Literal String Interpolation.
PEP written and implemented by Eric V. Smith.
Feature documentation <f-strings>.
PEP 526: Syntax for variable annotations
484 introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:
primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: Dict[str, int] = {}
Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the __annotations__ attribute of a class or module.
In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the __annotations__ attribute.
526 -- Syntax for variable annotations.
PEP written by Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, and Guido van Rossum. Implemented by Ivan Levkivskyi.
Tools that use or will use the new syntax: mypy, pytype, PyCharm, etc.
PEP 515: Underscores in Numeric Literals
515 adds the ability to use underscores in numeric literals for improved readability. For example:
>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295
Single underscores are allowed between digits and after any base specifier. Leading, trailing, or multiple underscores in a row are not allowed.
The string formatting <formatspec> language also now has support for the '_' option to signal the use of an underscore for a thousands separator for floating-point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits:
>>> '{:_}'.format(1000000)
'1_000_000'
>>> '{:_x}'.format(0xFFFFFFFF)
'ffff_ffff'
515 -- Underscores in Numeric Literals
PEP written by Georg Brandl and Serhiy Storchaka.
PEP 525: Asynchronous Generators
492 introduced support for native coroutines and async / await syntax to Python 3.5. A notable limitation of the Python 3.5 implementation is that it was not possible to use await and yield in the same function body. In Python 3.6 this restriction has been lifted, making it possible to define asynchronous generators:
async def ticker(delay, to):
"""Yield numbers from 0 to *to* every *delay* seconds."""
for i in range(to):
yield i
await asyncio.sleep(delay)
The new syntax allows for faster and more concise code.
525 -- Asynchronous Generators
PEP written and implemented by Yury Selivanov.
PEP 530: Asynchronous Comprehensions
530 adds support for using async for in list, set, dict comprehensions and generator expressions:
result = [i async for i in aiter() if i % 2]
Additionally, await expressions are supported in all kinds of comprehensions:
result = [await fun() for fun in funcs if await condition()]
530 -- Asynchronous Comprehensions
PEP written and implemented by Yury Selivanov.
PEP 487: Simpler customization of class creation
It is now possible to customize subclass creation without using a metaclass. The new __init_subclass__ classmethod will be called on the base class whenever a new subclass is created:
class PluginBase:
subclasses = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.subclasses.append(cls)
class Plugin1(PluginBase):
pass
class Plugin2(PluginBase):
pass
In order to allow zero-argument super calls to work correctly from ~object.__init_subclass__ implementations, custom metaclasses must ensure that the new __classcell__ namespace entry is propagated to type.__new__ (as described in class-object-creation).
487 -- Simpler customization of class creation
PEP written and implemented by Martin Teichmann.
Feature documentation <class-customization>
PEP 487: Descriptor Protocol Enhancements
487 extends the descriptor protocol to include the new optional ~object.__set_name__ method. Whenever a new class is defined, the new method will be called on all descriptors included in the definition, providing them with a reference to the class being defined and the name given to the descriptor within the class namespace. In other words, instances of descriptors can now know the attribute name of the descriptor in the owner class:
class IntField:
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError(f'expecting integer in {self.name}')
instance.__dict__[self.name] = value
# this is the new initializer:
def __set_name__(self, owner, name):
self.name = name
class Model:
int_field = IntField()
487 -- Simpler customization of class creation
PEP written and implemented by Martin Teichmann.
Feature documentation <descriptors>
PEP 519: Adding a file system path protocol
File system paths have historically been represented as str or bytes objects. This has led to people who write code which operate on file system paths to assume that such objects are only one of those two types (an int representing a file descriptor does not count as that is not a file path). Unfortunately that assumption prevents alternative object representations of file system paths like pathlib from working with pre-existing code, including Python's standard library.
To fix this situation, a new interface represented by os.PathLike has been defined. By implementing the ~os.PathLike.__fspath__ method, an object signals that it represents a path. An object can then provide a low-level representation of a file system path as a str or bytes object. This means an object is considered path-like <path-like object> if it implements os.PathLike or is a str or bytes object which represents a file system path. Code can use os.fspath, os.fsdecode, or os.fsencode to explicitly get a str and/or bytes representation of a path-like object.
The built-in open function has been updated to accept os.PathLike objects, as have all relevant functions in the os and os.path modules, and most other functions and classes in the standard library. The os.DirEntry class and relevant classes in pathlib have also been updated to implement os.PathLike.
The hope is that updating the fundamental functions for operating on file system paths will lead to third-party code to implicitly support all path-like objects <path-like object> without any code changes, or at least very minimal ones (e.g. calling os.fspath at the beginning of code before operating on a path-like object).
Here are some examples of how the new interface allows for pathlib.Path to be used more easily and transparently with pre-existing code:
>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
... contents = f.read()
...
>>> import os.path
>>> os.path.splitext(pathlib.Path("some_file.txt"))
('some_file', '.txt')
>>> os.path.join("/a/b", pathlib.Path("c"))
'/a/b/c'
>>> import os
>>> os.fspath(pathlib.Path("some_file.txt"))
'some_file.txt'
(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra.)
519 -- Adding a file system path protocol
PEP written by Brett Cannon and Koos Zevenhoven.
PEP 495: Local Time Disambiguation
In most world locations, there have been and will be times when local clocks are moved back. In those times, intervals are introduced in which local clocks show the same time twice in the same day. In these situations, the information displayed on a local clock (or stored in a Python datetime instance) is insufficient to identify a particular moment in time.
495 adds the new fold attribute to instances of datetime.datetime and datetime.time classes to differentiate between two moments in time for which local times are the same:
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
... u = u0 + i*HOUR
... t = u.astimezone(Eastern)
... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
The values of the fold <datetime.datetime.fold> attribute have the value 0 for all instances except those that represent the second (chronologically) moment in time in an ambiguous case.
495 -- Local Time Disambiguation
PEP written by Alexander Belopolsky and Tim Peters, implementation by Alexander Belopolsky.
PEP 529: Change Windows filesystem encoding to UTF-8
Representing filesystem paths is best performed with str (Unicode) rather than bytes. However, there are some situations where using bytes is sufficient and correct.
Prior to Python 3.6, data loss could result when using bytes paths on Windows. With this change, using bytes to represent paths is now supported on Windows, provided those bytes are encoded with the encoding returned by sys.getfilesystemencoding, which now defaults to 'utf-8'.
Applications that do not use str to represent paths should use os.fsencode and os.fsdecode to ensure their bytes are correctly encoded. To revert to the previous behaviour, set PYTHONLEGACYWINDOWSFSENCODING or call !sys._enablelegacywindowsfsencoding.
See 529 for more information and discussion of code modifications that may be required.
PEP 528: Change Windows console encoding to UTF-8
The default console on Windows will now accept all Unicode characters and provide correctly read str objects to Python code. sys.stdin, sys.stdout and sys.stderr now default to utf-8 encoding.
This change only applies when using an interactive console, and not when redirecting files or pipes. To revert to the previous behaviour for interactive console use, set PYTHONLEGACYWINDOWSSTDIO.
528 -- Change Windows console encoding to UTF-8
PEP written and implemented by Steve Dower.
PEP 520: Preserving Class Attribute Definition Order
Attributes in a class definition body have a natural ordering: the same order in which the names appear in the source. This order is now preserved in the new class's ~type.__dict__ attribute.
Also, the effective default class execution namespace (returned from type.__prepare__() <prepare>) is now an insertion-order-preserving mapping.
520 -- Preserving Class Attribute Definition Order
PEP written and implemented by Eric Snow.
PEP 468: Preserving Keyword Argument Order
**kwargs in a function signature is now guaranteed to be an insertion-order-preserving mapping.
468 -- Preserving Keyword Argument Order
PEP written and implemented by Eric Snow.
New dict <typesmapping> implementation
The dict <typesmapping> type now uses a "compact" representation based on a proposal by Raymond Hettinger which was first implemented by PyPy. The memory usage of the new dict is between 20% and 25% smaller compared to Python 3.5.
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).
(Contributed by INADA Naoki in 27350. Idea originally suggested by Raymond Hettinger.)
PEP 523: Adding a frame evaluation API to CPython
While Python provides extensive support to customize how code executes, one place it has not done so is in the evaluation of frame objects. If you wanted some way to intercept frame evaluation in Python there really wasn't any way without directly manipulating function pointers for defined functions.
523 changes this by providing an API to make frame evaluation pluggable at the C level. This will allow for tools such as debuggers and JITs to intercept frame evaluation before the execution of Python code begins. This enables the use of alternative evaluation implementations for Python code, tracking frame evaluation, etc.
This API is not part of the limited C API and is marked as private to signal that usage of this API is expected to be limited and only applicable to very select, low-level use-cases. Semantics of the API will change with Python as necessary.
523 -- Adding a frame evaluation API to CPython
PEP written by Brett Cannon and Dino Viehland.
PYTHONMALLOC environment variable
The new PYTHONMALLOC environment variable allows setting the Python memory allocators and installing debug hooks.
It is now possible to install debug hooks on Python memory allocators on Python compiled in release mode using PYTHONMALLOC=debug. Effects of debug hooks:
- Newly allocated memory is filled with the byte
0xCB - Freed memory is filled with the byte
0xDB - Detect violations of the Python memory allocator API. For example,
PyObject_Freecalled on a memory block allocated byPyMem_Malloc. - Detect writes before the start of a buffer (buffer underflows)
- Detect writes after the end of a buffer (buffer overflows)
- Check that the
GIL <global interpreter lock>is held when allocator functions ofPYMEM_DOMAIN_OBJ(ex:PyObject_Malloc) andPYMEM_DOMAIN_MEM(ex:PyMem_Malloc) domains are called.
Checking if the GIL is held is also a new feature of Python 3.6.
See the PyMem_SetupDebugHooks function for debug hooks on Python memory allocators.
It is now also possible to force the usage of the malloc allocator of the C library for all Python memory allocations using PYTHONMALLOC=malloc. This is helpful when using external memory debuggers like Valgrind on a Python compiled in release mode.
On error, the debug hooks on Python memory allocators now use the tracemalloc module to get the traceback where a memory block was allocated.
Example of fatal error on buffer overflow using python3.6 -X tracemalloc=5 (store 5 frames in traces):
Debug memory block at address p=0x7fbcd41666f8: API 'o'
4 bytes originally requested
The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
at tail+0: 0x02 *** OUCH
at tail+1: 0xfb
at tail+2: 0xfb
at tail+3: 0xfb
at tail+4: 0xfb
at tail+5: 0xfb
at tail+6: 0xfb
at tail+7: 0xfb
The block was made by call #1233329 to debug malloc/realloc.
Data at p: 1a 2b 30 00
Memory block allocated at (most recent call first):
File "test/test_bytes.py", line 323
File "unittest/case.py", line 600
File "unittest/case.py", line 648
File "unittest/suite.py", line 122
File "unittest/suite.py", line 84
Fatal Python error: bad trailing pad byte
Current thread 0x00007fbcdbd32700 (most recent call first):
File "test/test_bytes.py", line 323 in test_hex
File "unittest/case.py", line 600 in run
File "unittest/case.py", line 648 in __call__
File "unittest/suite.py", line 122 in run
File "unittest/suite.py", line 84 in __call__
File "unittest/suite.py", line 122 in run
File "unittest/suite.py", line 84 in __call__
...
(Contributed by Victor Stinner in 26516 and 26564.)
DTrace and SystemTap probing support
Python can now be built --with-dtrace which enables static markers for the following events in the interpreter:
- function call/return
- garbage collection started/finished
- line of code executed.
This can be used to instrument running interpreters in production, without the need to recompile specific debug builds <debug-build> or providing application-specific profiling/debugging code.
More details in instrumentation.
The current implementation is tested on Linux and macOS. Additional markers may be added in the future.
(Contributed by Łukasz Langa in 21590, based on patches by Jesús Cea Avión, David Malcolm, and Nikhil Benesch.)
Other Language Changes
Some smaller changes made to the core Python language are:
- A
globalornonlocalstatement must now textually appear before the first use of the affected name in the same scope. Previously this was aSyntaxWarning. - It is now possible to set a
special method <specialnames>toNoneto indicate that the corresponding operation is not available. For example, if a class sets~object.__iter__toNone, the class is not iterable. (Contributed by Andrew Barnert and Ivan Levkivskyi in25958.) - Long sequences of repeated traceback lines are now abbreviated as
"[Previous line repeated {count} more times]"(seewhatsnew36-tracebackfor an example). (Contributed by Emanuel Barry in26823.) - Import now raises the new exception
ModuleNotFoundError(subclass ofImportError) when it cannot find a module. Code that currently checks for ImportError (in try-except) will still work. (Contributed by Eric Snow in15767.) - Class methods relying on zero-argument
super()will now work correctly when called from metaclass methods during class creation. (Contributed by Martin Teichmann in23722.)
New Modules
secrets
The main purpose of the new secrets module is to provide an obvious way to reliably generate cryptographically strong pseudo-random values suitable for managing secrets, such as account authentication, tokens, and similar.
[!WARNING] Note that the pseudo-random generators in the
randommodule should NOT be used for security purposes. Usesecretson Python 3.6+ andos.urandomon Python 3.5 and earlier.
506 -- Adding A Secrets Module To The Standard Library
PEP written and implemented by Steven D'Aprano.
Improved Modules
array
Exhausted iterators of array.array will now stay exhausted even if the iterated array is extended. This is consistent with the behavior of other mutable sequences.
Contributed by Serhiy Storchaka in 26492.
ast
The new ast.Constant AST node has been added. It can be used by external AST optimizers for the purposes of constant folding.
Contributed by Victor Stinner in 26146.
asyncio
Starting with Python 3.6 the asyncio module is no longer provisional and its API is considered stable.
Notable changes in the asyncio module since Python 3.5.0 (all backported to 3.5.x due to the provisional status):
- The
~asyncio.get_event_loopfunction has been changed to always return the currently running loop when called from coroutines and callbacks. (Contributed by Yury Selivanov in28613.) - The
~asyncio.ensure_futurefunction and all functions that use it, such asloop.run_until_complete() <asyncio.loop.run_until_complete>, now accept all kinds ofawaitable objects <awaitable>. (Contributed by Yury Selivanov.) - New
~asyncio.run_coroutine_threadsafefunction to submit coroutines to event loops from other threads. (Contributed by Vincent Michel.) - New
Transport.is_closing() <asyncio.BaseTransport.is_closing>method to check if the transport is closing or closed. (Contributed by Yury Selivanov.) - The
loop.create_server() <asyncio.loop.create_server>method can now accept a list of hosts. (Contributed by Yann Sionneau.) - New
loop.create_future() <asyncio.loop.create_future>method to create Future objects. This allows alternative event loop implementations, such as uvloop, to provide a fasterasyncio.Futureimplementation. (Contributed by Yury Selivanov in27041.) - New
loop.get_exception_handler() <asyncio.loop.get_exception_handler>method to get the current exception handler. (Contributed by Yury Selivanov in27040.) - New
StreamReader.readuntil() <asyncio.StreamReader.readuntil>method to read data from the stream until a separator bytes sequence appears. (Contributed by Mark Korenberg.) - The performance of
StreamReader.readexactly() <asyncio.StreamReader.readexactly>has been improved. (Contributed by Mark Korenberg in28370.) - The
loop.getaddrinfo() <asyncio.loop.getaddrinfo>method is optimized to avoid calling the systemgetaddrinfofunction if the address is already resolved. (Contributed by A. Jesse Jiryu Davis.) - The
loop.stop() <asyncio.loop.stop>method has been changed to stop the loop immediately after the current iteration. Any new callbacks scheduled as a result of the last iteration will be discarded. (Contributed by Guido van Rossum in25593.) Future.set_exception <asyncio.Future.set_exception>will now raiseTypeErrorwhen passed an instance of theStopIterationexception. (Contributed by Chris Angelico in26221.)- New
loop.connect_accepted_socket() <asyncio.loop.connect_accepted_socket>method to be used by servers that accept connections outside of asyncio, but that use asyncio to handle them. (Contributed by Jim Fulton in27392.) TCP_NODELAYflag is now set for all TCP transports by default. (Contributed by Yury Selivanov in27456.)- New
loop.shutdown_asyncgens() <asyncio.loop.shutdown_asyncgens>to properly close pending asynchronous generators before closing the loop. (Contributed by Yury Selivanov in28003.) Future <asyncio.Future>andTask <asyncio.Task>classes now have an optimized C implementation which makes asyncio code up to 30% faster. (Contributed by Yury Selivanov and INADA Naoki in26081and28544.)
binascii
The ~binascii.b2a_base64 function now accepts an optional newline keyword argument to control whether the newline character is appended to the return value. (Contributed by Victor Stinner in 25357.)
cmath
The new cmath.tau (τ) constant has been added. (Contributed by Lisa Roach in 12345, see 628 for details.)
New constants: cmath.inf and cmath.nan to match math.inf and math.nan, and also cmath.infj and cmath.nanj to match the format used by complex repr. (Contributed by Mark Dickinson in 23229.)
collections
The new ~collections.abc.Collection abstract base class has been added to represent sized iterable container classes. (Contributed by Ivan Levkivskyi, docs by Neil Girdhar in 27598.)
The new ~collections.abc.Reversible abstract base class represents iterable classes that also provide the ~object.__reversed__ method. (Contributed by Ivan Levkivskyi in 25987.)
The new ~collections.abc.AsyncGenerator abstract base class represents asynchronous generators. (Contributed by Yury Selivanov in 28720.)
The ~collections.namedtuple function now accepts an optional keyword argument module, which, when specified, is used for the ~type.__module__ attribute of the returned named tuple class. (Contributed by Raymond Hettinger in 17941.)
The verbose and rename arguments for ~collections.namedtuple are now keyword-only. (Contributed by Raymond Hettinger in 25628.)
Recursive collections.deque instances can now be pickled. (Contributed by Serhiy Storchaka in 26482.)
concurrent.futures
The ThreadPoolExecutor <concurrent.futures.ThreadPoolExecutor> class constructor now accepts an optional thread_name_prefix argument to make it possible to customize the names of the threads created by the pool. (Contributed by Gregory P. Smith in 27664.)
contextlib
The contextlib.AbstractContextManager class has been added to provide an abstract base class for context managers. It provides a sensible default implementation for __enter__() which returns self and leaves __exit__() an abstract method. A matching class has been added to the typing module as typing.ContextManager. (Contributed by Brett Cannon in 25609.)
datetime
The ~datetime.datetime and ~datetime.time classes have the new ~datetime.time.fold attribute used to disambiguate local time when necessary. Many functions in the datetime have been updated to support local time disambiguation. See Local Time Disambiguation <whatsnew36-pep495> section for more information. (Contributed by Alexander Belopolsky in 24773.)
The datetime.strftime() <datetime.datetime.strftime> and date.strftime() <datetime.date.strftime> methods now support ISO 8601 date directives %G, %u and %V. (Contributed by Ashley Anderson in 12006.)
The datetime.isoformat() <datetime.datetime.isoformat> function now accepts an optional timespec argument that specifies the number of additional components of the time value to include. (Contributed by Alessandro Cucci and Alexander Belopolsky in 19475.)
The datetime.combine() <datetime.datetime.combine> now accepts an optional tzinfo argument. (Contributed by Alexander Belopolsky in 27661.)
decimal
New Decimal.as_integer_ratio() <decimal.Decimal.as_integer_ratio> method that returns a pair (n, d) of integers that represent the given ~decimal.Decimal instance as a fraction, in lowest terms and with a positive denominator:
>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)
(Contributed by Stefan Krah amd Mark Dickinson in 25928.)
distutils
The default_format attribute has been removed from distutils.command.sdist.sdist and the formats attribute defaults to ['gztar']. Although not anticipated, any code relying on the presence of default_format may need to be adapted. See 27819 for more details.
The new email API, enabled via the policy keyword to various constructors, is no longer provisional. The email documentation has been reorganized and rewritten to focus on the new API, while retaining the old documentation for the legacy API. (Contributed by R. David Murray in 24277.)
The email.mime classes now all accept an optional policy keyword. (Contributed by Berker Peksag in 27331.)
The ~email.generator.DecodedGenerator now supports the policy keyword.
There is a new ~email.policy attribute, ~email.policy.Policy.message_factory, that controls what class is used by default when the parser creates new message objects. For the email.policy.compat32 policy this is ~email.message.Message, for the new policies it is ~email.message.EmailMessage. (Contributed by R. David Murray in 20476.)
encodings
On Windows, added the 'oem' encoding to use CP_OEMCP, and the 'ansi' alias for the existing 'mbcs' encoding, which uses the CP_ACP code page. (Contributed by Steve Dower in 27959.)
enum
Two new enumeration base classes have been added to the enum module: ~enum.Flag and ~enum.IntFlag. Both are used to define constants that can be combined using the bitwise operators. (Contributed by Ethan Furman in 23591.)
Many standard library modules have been updated to use the ~enum.IntFlag class for their constants.
The new enum.auto value can be used to assign values to enum members automatically:
>>> from enum import Enum, auto
>>> class Color(Enum):
... red = auto()
... blue = auto()
... green = auto()
...
>>> list(Color)
[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]
faulthandler
On Windows, the faulthandler module now installs a handler for Windows exceptions: see faulthandler.enable. (Contributed by Victor Stinner in 23848.)
fileinput
~fileinput.hook_encoded now supports the errors argument. (Contributed by Joseph Hackman in 25788.)
hashlib
hashlib supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2. (Contributed by Christian Heimes in 26470.)
BLAKE2 hash functions were added to the module. ~hashlib.blake2b and ~hashlib.blake2s are always available and support the full feature set of BLAKE2. (Contributed by Christian Heimes in 26798 based on code by Dmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)
The SHA-3 hash functions ~hashlib.sha3_224, ~hashlib.sha3_256, ~hashlib.sha3_384, ~hashlib.sha3_512, and SHAKE hash functions ~hashlib.shake_128 and ~hashlib.shake_256 were added. (Contributed by Christian Heimes in 16113. Keccak Code Package by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, and Ronny Van Keer.)
The password-based key derivation function ~hashlib.scrypt is now available with OpenSSL 1.1.0 and newer. (Contributed by Christian Heimes in 27928.)
http.client
HTTPConnection.request() <http.client.HTTPConnection.request> and ~http.client.HTTPConnection.endheaders both now support chunked encoding request bodies. (Contributed by Demian Brecht and Rolf Krahl in 12319.)
idlelib and IDLE
The idlelib package is being modernized and refactored to make IDLE look and work better and to make the code easier to understand, test, and improve. Part of making IDLE look better, especially on Linux and Mac, is using ttk widgets, mostly in the dialogs. As a result, IDLE no longer runs with tcl/tk 8.4. It now requires tcl/tk 8.5 or 8.6. We recommend running the latest release of either.
'Modernizing' includes renaming and consolidation of idlelib modules. The renaming of files with partial uppercase names is similar to the renaming of, for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0. As a result, imports of idlelib files that worked in 3.5 will usually not work in 3.6. At least a module name change will be needed (see idlelib/README.txt), sometimes more. (Name changes contributed by Al Swiegart and Terry Reedy in 24225. Most idlelib patches since have been and will be part of the process.)
In compensation, the eventual result with be that some idlelib classes will be easier to use, with better APIs and docstrings explaining them. Additional useful information will be added to idlelib when available.
New in 3.6.2:
Multiple fixes for autocompletion. (Contributed by Louie Lu in 15786.)
New in 3.6.3:
Module Browser (on the File menu, formerly called Class Browser), now displays nested functions and classes in addition to top-level functions and classes. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy in 1612262.)
The IDLE features formerly implemented as extensions have been reimplemented as normal features. Their settings have been moved from the Extensions tab to other dialog tabs. (Contributed by Charles Wohlganger and Terry Jan Reedy in 27099.)
The Settings dialog (Options, Configure IDLE) has been partly rewritten to improve both appearance and function. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)
New in 3.6.4:
The font sample now includes a selection of non-Latin characters so that users can better see the effect of selecting a particular font. (Contributed by Terry Jan Reedy in 13802.) The sample can be edited to include other characters. (Contributed by Serhiy Storchaka in 31860.)
New in 3.6.6:
Editor code context option revised. Box displays all context lines up to maxlines. Clicking on a context line jumps the editor to that line. Context colors for custom themes is added to Highlights tab of Settings dialog. (Contributed by Cheryl Sabella and Terry Jan Reedy in 33642, 33768, and 33679.)
On Windows, a new API call tells Windows that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect. (Contributed by Terry Jan Reedy in 33656.)
New in 3.6.7:
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 1529353.)
importlib
Import now raises the new exception ModuleNotFoundError (subclass of ImportError) when it cannot find a module. Code that current checks for ImportError (in try-except) will still work. (Contributed by Eric Snow in 15767.)
importlib.util.LazyLoader now calls ~importlib.abc.Loader.create_module on the wrapped loader, removing the restriction that importlib.machinery.BuiltinImporter and importlib.machinery.ExtensionFileLoader couldn't be used with importlib.util.LazyLoader.
importlib.util.cache_from_source, importlib.util.source_from_cache, and importlib.util.spec_from_file_location now accept a path-like object.
inspect
The inspect.signature() <inspect.signature> function now reports the implicit .0 parameters generated by the compiler for comprehension and generator expression scopes as if they were positional-only parameters called implicit0. (Contributed by Jelle Zijlstra in 19611.)
To reduce code churn when upgrading from Python 2.7 and the legacy !inspect.getargspec API, the previously documented deprecation of inspect.getfullargspec has been reversed. While this function is convenient for single/source Python 2/3 code bases, the richer inspect.signature interface remains the recommended approach for new code. (Contributed by Nick Coghlan in 27172)
json
json.load and json.loads now support binary input. Encoded JSON should be represented using either UTF-8, UTF-16, or UTF-32. (Contributed by Serhiy Storchaka in 17909.)
logging
The new WatchedFileHandler.reopenIfNeeded() <logging.handlers.WatchedFileHandler.reopenIfNeeded> method has been added to add the ability to check if the log file needs to be reopened. (Contributed by Marian Horban in 24884.)
math
The tau (τ) constant has been added to the math and cmath modules. (Contributed by Lisa Roach in 12345, see 628 for details.)
multiprocessing
Proxy Objects <multiprocessing-proxy_objects> returned by multiprocessing.Manager can now be nested. (Contributed by Davin Potts in 6766.)
os
See the summary of PEP 519 <whatsnew36-pep519> for details on how the os and os.path modules now support path-like objects <path-like object>.
~os.scandir now supports bytes paths on Windows.
A new ~os.scandir.close method allows explicitly closing a ~os.scandir iterator. The ~os.scandir iterator now supports the context manager protocol. If a !scandir iterator is neither exhausted nor explicitly closed a ResourceWarning will be emitted in its destructor. (Contributed by Serhiy Storchaka in 25994.)
On Linux, os.urandom now blocks until the system urandom entropy pool is initialized to increase the security. See the 524 for the rationale.
The Linux getrandom() syscall (get random bytes) is now exposed as the new os.getrandom function. (Contributed by Victor Stinner, part of the 524)
pathlib
pathlib now supports path-like objects <path-like object>. (Contributed by Brett Cannon in 27186.)
See the summary of PEP 519 <whatsnew36-pep519> for details.
pdb
The ~pdb.Pdb class constructor has a new optional readrc argument to control whether .pdbrc files should be read.
pickle
Objects that need __new__ called with keyword arguments can now be pickled using pickle protocols <pickle-protocols> older than protocol version 4. Protocol version 4 already supports this case. (Contributed by Serhiy Storchaka in 24164.)
pickletools
pickletools.dis now outputs the implicit memo index for the MEMOIZE opcode. (Contributed by Serhiy Storchaka in 25382.)
pydoc
The pydoc module has learned to respect the MANPAGER environment variable. (Contributed by Matthias Klose in 8637.)
help and pydoc can now list named tuple fields in the order they were defined rather than alphabetically. (Contributed by Raymond Hettinger in 24879.)
random
The new ~random.choices function returns a list of elements of specified size from the given population with optional weights. (Contributed by Raymond Hettinger in 18844.)
re
Added support of modifier spans in regular expressions. Examples: '(?i:p)ython' matches 'python' and 'Python', but not 'PYTHON'; '(?i)g(?-i:v)r' matches 'GvR' and 'gvr', but not 'GVR'. (Contributed by Serhiy Storchaka in 433028.)
Match object groups can be accessed by __getitem__, which is equivalent to group(). So mo['name'] is now equivalent to mo.group('name'). (Contributed by Eric Smith in 24454.)
~re.Match objects now support index-like objects <object.__index__> as group indices. (Contributed by Jeroen Demeyer and Xiang Zhang in 27177.)
readline
Added ~readline.set_auto_history to enable or disable automatic addition of input to the history list. (Contributed by Tyler Crompton in 26870.)
rlcompleter
Private and special attribute names now are omitted unless the prefix starts with underscores. A space or a colon is added after some completed keywords. (Contributed by Serhiy Storchaka in 25011 and 25209.)
shlex
The ~shlex.shlex has much improved shell compatibility <improved-shell-compatibility> through the new punctuation_chars argument to control which characters are treated as punctuation. (Contributed by Vinay Sajip in 1521950.)
site
When specifying paths to add to sys.path in a .pth file, you may now specify file paths on top of directories (e.g. zip files). (Contributed by Wolfgang Langner in 26587).
sqlite3
sqlite3.Cursor.lastrowid now supports the REPLACE statement. (Contributed by Alex LordThorsen in 16864.)
socket
The ~socket.socket.ioctl function now supports the ~socket.SIO_LOOPBACK_FAST_PATH control code. (Contributed by Daniel Stokes in 26536.)
The ~socket.socket.getsockopt constants SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, and SO_PASSSEC are now supported. (Contributed by Christian Heimes in 26907.)
The ~socket.socket.setsockopt now supports the setsockopt(level, optname, None, optlen: int) form. (Contributed by Christian Heimes in 27744.)
The socket module now supports the address family ~socket.AF_ALG to interface with Linux Kernel crypto API. ALG_*, SOL_ALG and ~socket.socket.sendmsg_afalg were added. (Contributed by Christian Heimes in 27744 with support from Victor Stinner.)
New Linux constants TCP_USER_TIMEOUT and TCP_CONGESTION were added. (Contributed by Omar Sandoval, 26273).
socketserver
Servers based on the socketserver module, including those defined in http.server, xmlrpc.server and wsgiref.simple_server, now support the context manager protocol. (Contributed by Aviv Palivoda in 26404.)
The wfile <socketserver.DatagramRequestHandler.wfile> attribute of ~socketserver.StreamRequestHandler classes now implements the io.BufferedIOBase writable interface. In particular, calling ~io.BufferedIOBase.write is now guaranteed to send the data in full. (Contributed by Martin Panter in 26721.)
ssl
ssl supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2. (Contributed by Christian Heimes in 26470.)
3DES has been removed from the default cipher suites and ChaCha20 Poly1305 cipher suites have been added. (Contributed by Christian Heimes in 27850 and 27766.)
~ssl.SSLContext has better default configuration for options and ciphers. (Contributed by Christian Heimes in 28043.)
SSL session can be copied from one client-side connection to another with the new ~ssl.SSLSession class. TLS session resumption can speed up the initial handshake, reduce latency and improve performance (Contributed by Christian Heimes in 19500 based on a draft by Alex Warhawk.)
The new ~ssl.SSLContext.get_ciphers method can be used to get a list of enabled ciphers in order of cipher priority.
All constants and flags have been converted to ~enum.IntEnum and ~enum.IntFlag. (Contributed by Christian Heimes in 28025.)
Server and client-side specific TLS protocols for ~ssl.SSLContext were added. (Contributed by Christian Heimes in 28085.)
Added 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 78851.)
statistics
A new ~statistics.harmonic_mean function has been added. (Contributed by Steven D'Aprano in 27181.)
struct
struct now supports IEEE 754 half-precision floats via the 'e' format specifier. (Contributed by Eli Stevens, Mark Dickinson in 11734.)
subprocess
subprocess.Popen destructor now emits a ResourceWarning warning if the child process is still running. Use the context manager protocol (with proc: ...) or explicitly call the ~subprocess.Popen.wait method to read the exit status of the child process. (Contributed by Victor Stinner in 26741.)
The subprocess.Popen constructor and all functions that pass arguments through to it now accept encoding and errors arguments. Specifying either of these will enable text mode for the stdin, stdout and stderr streams. (Contributed by Steve Dower in 6135.)
sys
The new ~sys.getfilesystemencodeerrors function returns the name of the error mode used to convert between Unicode filenames and bytes filenames. (Contributed by Steve Dower in 27781.)
On Windows the return value of the ~sys.getwindowsversion function now includes the platform_version field which contains the accurate major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process (Contributed by Steve Dower in 27932.)
telnetlib
!telnetlib.Telnet is now a context manager (contributed by Stéphane Wirtel in 25485).
time
The ~time.struct_time attributes !tm_gmtoff and !tm_zone are now available on all platforms.
timeit
The new Timer.autorange() <timeit.Timer.autorange> convenience method has been added to call Timer.timeit() <timeit.Timer.timeit> repeatedly so that the total run time is greater or equal to 200 milliseconds. (Contributed by Steven D'Aprano in 6422.)
timeit now warns when there is substantial (4x) variance between best and worst times. (Contributed by Serhiy Storchaka in 23552.)
tkinter
Added methods !Variable.trace_add, !Variable.trace_remove and !trace_info in the !tkinter.Variable class. They replace old methods !trace_variable, !trace, !trace_vdelete and !trace_vinfo that use obsolete Tcl commands and might not work in future versions of Tcl. (Contributed by Serhiy Storchaka in 22115).
traceback
Both the traceback module and the interpreter's builtin exception display now abbreviate long sequences of repeated lines in tracebacks as shown in the following example:
>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in f
File "<stdin>", line 1, in f
File "<stdin>", line 1, in f
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
(Contributed by Emanuel Barry in 26823.)
tracemalloc
The tracemalloc module now supports tracing memory allocations in multiple different address spaces.
The new ~tracemalloc.DomainFilter filter class has been added to filter block traces by their address space (domain).
(Contributed by Victor Stinner in 26588.)
typing
Since the typing module is provisional <provisional API>, all changes introduced in Python 3.6 have also been backported to Python 3.5.x.
The typing module has a much improved support for generic type aliases. For example Dict[str, Tuple[S, T]] is now a valid type annotation. (Contributed by Guido van Rossum in Github #195.)
The typing.ContextManager class has been added for representing contextlib.AbstractContextManager. (Contributed by Brett Cannon in 25609.)
The typing.Collection class has been added for representing collections.abc.Collection. (Contributed by Ivan Levkivskyi in 27598.)
The typing.ClassVar type construct has been added to mark class variables. As introduced in 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. (Contributed by Ivan Levkivskyi in Github #280.)
A new ~typing.TYPE_CHECKING constant that is assumed to be True by the static type checkers, but is False at runtime. (Contributed by Guido van Rossum in Github #230.)
A new ~typing.NewType helper function has been added to create lightweight distinct types for annotations:
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
The static type checker will treat the new type as if it were a subclass of the original type. (Contributed by Ivan Levkivskyi in Github #189.)
unicodedata
The unicodedata module now uses data from Unicode 9.0.0. (Contributed by Benjamin Peterson.)
unittest.mock
The ~unittest.mock.Mock class has the following improvements:
- Two new methods,
Mock.assert_called() <unittest.mock.Mock.assert_called>andMock.assert_called_once() <unittest.mock.Mock.assert_called_once>to check if the mock object was called. (Contributed by Amit Saha in26323.) - The
Mock.reset_mock() <unittest.mock.Mock.reset_mock>method now has two optional keyword only arguments: return_value and side_effect. (Contributed by Kushal Das in21271.)
urllib.request
If a HTTP request has a file or iterable body (other than a bytes object) but no Content-Length header, rather than throwing an error, AbstractHTTPHandler <urllib.request.HTTPHandler> now falls back to use chunked transfer encoding. (Contributed by Demian Brecht and Rolf Krahl in 12319.)
urllib.robotparser
~urllib.robotparser.RobotFileParser now supports the Crawl-delay and Request-rate extensions. (Contributed by Nikolay Bogoychev in 16099.)
venv
venv accepts a new parameter --prompt. This parameter provides an alternative prefix for the virtual environment. (Proposed by Łukasz Balcerzak and ported to 3.6 by Stéphane Wirtel in 22829.)
warnings
A new optional source parameter has been added to the warnings.warn_explicit function: the destroyed object which emitted a ResourceWarning. A source attribute has also been added to !warnings.WarningMessage (contributed by Victor Stinner in 26568 and 26567).
When a ResourceWarning warning is logged, the tracemalloc module is now used to try to retrieve the traceback where the destroyed object was allocated.
Example with the script example.py:
import warnings
def func():
return open(__file__)
f = func()
f = None
Output of the command python3.6 -Wd -X tracemalloc=5 example.py:
example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
f = None
Object allocated at (most recent call first):
File "example.py", lineno 4
return open(__file__)
File "example.py", lineno 6
f = func()
The "Object allocated at" traceback is new and is only displayed if tracemalloc is tracing Python memory allocations and if the warnings module was already imported.
winreg
Added the 64-bit integer type REG_QWORD <winreg.REG_QWORD>. (Contributed by Clement Rouault in 23026.)
winsound
Allowed keyword arguments to be passed to Beep <winsound.Beep>, MessageBeep <winsound.MessageBeep>, and PlaySound <winsound.PlaySound> (27982).
xmlrpc.client
The xmlrpc.client module now supports unmarshalling additional data types used by the Apache XML-RPC implementation for numerics and None. (Contributed by Serhiy Storchaka in 26885.)
zipfile
A new ZipInfo.from_file() <zipfile.ZipInfo.from_file> class method allows making a ~zipfile.ZipInfo instance from a filesystem file. A new ZipInfo.is_dir() <zipfile.ZipInfo.is_dir> method can be used to check if the ~zipfile.ZipInfo instance represents a directory. (Contributed by Thomas Kluyver in 26039.)
The ZipFile.open() <zipfile.ZipFile.open> method can now be used to write data into a ZIP file, as well as for extracting data. (Contributed by Thomas Kluyver in 26039.)
zlib
The ~zlib.compress and ~zlib.decompress functions now accept keyword arguments. (Contributed by Aviv Palivoda in 26243 and Xiang Zhang in 16764 respectively.)
Optimizations
- The Python interpreter now uses a 16-bit wordcode instead of bytecode which made a number of opcode optimizations possible. (Contributed by Demur Rumed with input and reviews from Serhiy Storchaka and Victor Stinner in
26647and28050.) - The
asyncio.Futureclass now has an optimized C implementation. (Contributed by Yury Selivanov and INADA Naoki in26081.) - The
asyncio.Taskclass now has an optimized C implementation. (Contributed by Yury Selivanov in28544.) - Various implementation improvements in the
typingmodule (such as caching of generic types) allow up to 30 times performance improvements and reduced memory footprint. - The ASCII decoder is now up to 60 times as fast for error handlers
surrogateescape,ignoreandreplace(Contributed by Victor Stinner in24870). - The ASCII and the Latin1 encoders are now up to 3 times as fast for the error handler
surrogateescape(Contributed by Victor Stinner in25227). - The UTF-8 encoder is now up to 75 times as fast for error handlers
ignore,replace,surrogateescape,surrogatepass(Contributed by Victor Stinner in25267). - The UTF-8 decoder is now up to 15 times as fast for error handlers
ignore,replaceandsurrogateescape(Contributed by Victor Stinner in25301). bytes % argsis now up to 2 times faster. (Contributed by Victor Stinner in25349).bytearray % argsis now between 2.5 and 5 times faster. (Contributed by Victor Stinner in25399).- Optimize
bytes.fromhexandbytearray.fromhex: they are now between 2x and 3.5x faster. (Contributed by Victor Stinner in25401). - Optimize
bytes.replace(b'', b'.')andbytearray.replace(b'', b'.'): up to 80% faster. (Contributed by Josh Snider in26574). - Allocator functions of the
PyMem_Mallocdomain (PYMEM_DOMAIN_MEM) now use thepymalloc memory allocator <pymalloc>instead ofmallocfunction of the C library. The pymalloc allocator is optimized for objects smaller or equal to 512 bytes with a short lifetime, and usemallocfor larger memory blocks. (Contributed by Victor Stinner in26249). pickle.loadandpickle.loadsare now up to 10% faster when deserializing many small objects (Contributed by Victor Stinner in27056).- Passing
keyword arguments <keyword argument>to a function has an overhead in comparison with passingpositional arguments <positional argument>. Now in extension functions implemented with using Argument Clinic this overhead is significantly decreased. (Contributed by Serhiy Storchaka in27574). - Optimized
~glob.globand~glob.iglobfunctions in theglobmodule; they are now about 3--6 times faster. (Contributed by Serhiy Storchaka in25596). - Optimized globbing in
pathlibby usingos.scandir; it is now about 1.5--4 times faster. (Contributed by Serhiy Storchaka in26032). xml.etree.ElementTreeparsing, iteration and deepcopy performance has been significantly improved. (Contributed by Serhiy Storchaka in25638,25873, and25869.)- Creation of
fractions.Fractioninstances from floats and decimals is now 2 to 3 times faster. (Contributed by Serhiy Storchaka in25971.)
Build and C API Changes
- Python now requires some C99 support in the toolchain to build. Most notably, Python now uses standard integer types and macros in place of custom macros like
PY_LONG_LONG. For more information, see7and17884. - Cross-compiling CPython with the Android NDK and the Android API level set to 21 (Android 5.0 Lollipop) or greater runs successfully. While Android is not yet a supported platform, the Python test suite runs on the Android emulator with only about 16 tests failures. See the Android meta-issue
26865. - The
--enable-optimizationsconfigure flag has been added. Turning it on will activate expensive optimizations like PGO. (Original patch by Alecsandru Patrascu of Intel in26359.) - The
GIL <global interpreter lock>must now be held when allocator functions ofPYMEM_DOMAIN_OBJ(ex:PyObject_Malloc) andPYMEM_DOMAIN_MEM(ex:PyMem_Malloc) domains are called. - New
Py_FinalizeExAPI which indicates if flushing buffered data failed. (Contributed by Martin Panter in5319.) PyArg_ParseTupleAndKeywordsnow supportspositional-only parameters <positional-only_parameter>. Positional-only parameters are defined by empty names. (Contributed by Serhiy Storchaka in26282).PyTraceback_Printmethod now abbreviates long sequences of repeated lines as"[Previous line repeated {count} more times]". (Contributed by Emanuel Barry in26823.)- The new
PyErr_SetImportErrorSubclassfunction allows for specifying a subclass ofImportErrorto raise. (Contributed by Eric Snow in15767.) - The new
PyErr_ResourceWarningfunction can be used to generate aResourceWarningproviding the source of the resource allocation. (Contributed by Victor Stinner in26567.) - The new
PyOS_FSPathfunction returns the file system representation of apath-like object. (Contributed by Brett Cannon in27186.) - The
PyUnicode_FSConverterandPyUnicode_FSDecoderfunctions will now acceptpath-like objects <path-like object>.
Other Improvements
-
When
--version(short form:-V) is supplied twice, Python printssys.versionfor detailed information.$ ./python -VV Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
Deprecated
New Keywords
async and await are not recommended to be used as variable, class, function or module names. Introduced by 492 in Python 3.5, they will become proper keywords in Python 3.7. Starting in Python 3.6, the use of async or await as names will generate a DeprecationWarning.
Deprecated Python behavior
Raising the StopIteration exception inside a generator will now generate a DeprecationWarning, and will trigger a RuntimeError in Python 3.7. See whatsnew-pep-479 for details.
The ~object.__aiter__ method is now expected to return an asynchronous iterator directly instead of returning an awaitable as previously. Doing the former will trigger a DeprecationWarning. Backward compatibility will be removed in Python 3.7. (Contributed by Yury Selivanov in 27243.)
A backslash-character pair that is not a valid escape sequence now generates a DeprecationWarning. Although this will eventually become a SyntaxError, that will not be for several Python releases. (Contributed by Emanuel Barry in 27364.)
When performing a relative import, falling back on __name__ and __path__ from the calling module when __spec__ or __package__ are not defined now raises an ImportWarning. (Contributed by Rose Ames in 25791.)
Deprecated Python modules, functions and methods
asynchat
The !asynchat has been deprecated in favor of asyncio. (Contributed by Mariatta in 25002.)
asyncore
The !asyncore has been deprecated in favor of asyncio. (Contributed by Mariatta in 25002.)
dbm
Unlike other dbm implementations, the dbm.dumb module creates databases with the 'rw' mode and allows modifying the database opened with the 'r' mode. This behavior is now deprecated and will be removed in 3.8. (Contributed by Serhiy Storchaka in 21708.)
distutils
The undocumented extra_path argument to the distutils.Distribution constructor is now considered deprecated and will raise a warning if set. Support for this parameter will be removed in a future Python release. See 27919 for details.
grp
The support of non-integer arguments in ~grp.getgrgid has been deprecated. (Contributed by Serhiy Storchaka in 26129.)
importlib
The importlib.machinery.SourceFileLoader.load_module and importlib.machinery.SourcelessFileLoader.load_module methods are now deprecated. They were the only remaining implementations of importlib.abc.Loader.load_module in importlib that had not been deprecated in previous versions of Python in favour of importlib.abc.Loader.exec_module.
The importlib.machinery.WindowsRegistryFinder class is now deprecated. As of 3.6.0, it is still added to sys.meta_path by default (on Windows), but this may change in future releases.
os
Undocumented support of general bytes-like objects <bytes-like object> as paths in os functions, compile and similar functions is now deprecated. (Contributed by Serhiy Storchaka in 25791 and 26754.)
re
Support for inline flags (?letters) in the middle of the regular expression has been deprecated and will be removed in a future Python version. Flags at the start of a regular expression are still allowed. (Contributed by Serhiy Storchaka in 22493.)
ssl
OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.
A couple of protocols and functions of the ssl module are now deprecated. Some features will no longer be available in future versions of OpenSSL. Other features are deprecated in favor of a different API. (Contributed by Christian Heimes in 28022 and 26470.)
tkinter
The !tkinter.tix module is now deprecated. tkinter users should use tkinter.ttk instead.
venv
The pyvenv script has been deprecated in favour of python3 -m venv. This prevents confusion as to what Python interpreter pyvenv is connected to and thus what Python interpreter will be used by the virtual environment. (Contributed by Brett Cannon in 25154.)
xml
- As mitigation against DTD and external entity retrieval, the
xml.dom.minidomandxml.saxmodules no longer process external entities by default. (Contributed by Christian Heimes in61441.)
Deprecated functions and types of the C API
Undocumented functions !PyUnicode_AsEncodedObject, !PyUnicode_AsDecodedObject, !PyUnicode_AsEncodedUnicode and !PyUnicode_AsDecodedUnicode are deprecated now. Use the generic codec based API <codec-registry> instead.
Deprecated Build Options
The --with-system-ffi configure flag is now on by default on non-macOS UNIX platforms. It may be disabled by using --without-system-ffi, but using the flag is deprecated and will not be accepted in Python 3.7. macOS is unaffected by this change. Note that many OS distributors already use the --with-system-ffi flag when building their system Python.
Removed
API and Feature Removals
- Unknown escapes consisting of
'\'and an ASCII letter in regular expressions will now cause an error. In replacement templates forre.subthey are still allowed, but deprecated. There.LOCALEflag can now only be used with binary patterns. inspect.getmoduleinfo()was removed (was deprecated since CPython 3.3).inspect.getmodulenameshould be used for obtaining the module name for a given path. (Contributed by Yury Selivanov in13248.)traceback.Ignoreclass andtraceback.usage,traceback.modname,traceback.fullmodname,traceback.find_lines_from_code,traceback.find_lines,traceback.find_strings,traceback.find_executable_linesmethods were removed from thetracebackmodule. They were undocumented methods deprecated since Python 3.2 and equivalent functionality is available from private methods.- The
tk_menuBar()andtk_bindForTraversal()dummy methods intkinterwidget classes were removed (corresponding Tk commands were obsolete since Tk 4.0). - The
~zipfile.ZipFile.openmethod of thezipfile.ZipFileclass no longer supports the'U'mode (was deprecated since Python 3.4). Useio.TextIOWrapperfor reading compressed text files inuniversal newlinesmode. - The undocumented
IN,CDROM,DLFCN,TYPES,CDIO, andSTROPTSmodules have been removed. They had been available in the platform specificLib/plat-*/directories, but were chronically out of date, inconsistently available across platforms, and unmaintained. The script that created these modules is still available in the source distribution at Tools/scripts/h2py.py. - The deprecated
asynchat.fifoclass has been removed.
Porting to Python 3.6
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in 'python' Command Behavior
- The output of a special Python build with defined
COUNT_ALLOCS,SHOW_ALLOC_COUNTorSHOW_TRACK_COUNTmacros is now off by default. It can be re-enabled using the-X showalloccountoption. It now outputs tostderrinstead ofstdout. (Contributed by Serhiy Storchaka in23034.)
Changes in the Python API
-
open() <open>will no longer allow combining the'U'mode flag with'+'. (Contributed by Jeff Balogh and John O'Connor in2091.) -
sqlite3no longer implicitly commits an open transaction before DDL statements. -
On Linux,
os.urandomnow blocks until the system urandom entropy pool is initialized to increase the security. -
When
importlib.abc.Loader.exec_moduleis defined,importlib.abc.Loader.create_modulemust also be defined. -
PyErr_SetImportErrornow setsTypeErrorwhen its msg argument is not set. Previously onlyNULLwas returned. -
The format of the
!codeobject.co_lnotabattribute of code objects changed to support a negative line number delta. By default, Python does not emit bytecode with a negative line number delta. Functions usingframe.f_lineno,PyFrame_GetLineNumber()orPyCode_Addr2Line()are not affected. Functions directly decoding!co_lnotabshould be updated to use a signed 8-bit integer type for the line number delta, but this is only required to support applications using a negative line number delta. SeeObjects/lnotab_notes.txtfor the!co_lnotabformat and how to decode it, and see the511for the rationale. -
The functions in the
compileallmodule now return booleans instead of1or0to represent success or failure, respectively. Thanks to booleans being a subclass of integers, this should only be an issue if you were doing identity checks for1or0. See25768. -
Reading the
!portattribute ofurllib.parse.urlsplitand~urllib.parse.urlparseresults now raisesValueErrorfor out-of-range values, rather than returningNone. See20059. -
The
!impmodule now raises aDeprecationWarninginstead ofPendingDeprecationWarning. -
The following modules have had missing APIs added to their
~module.__all__attributes to match the documented APIs:calendar,!cgi,csv,~xml.etree.ElementTree,enum,fileinput,ftplib,logging,mailbox,mimetypes,optparse,plistlib,!smtpd,subprocess,tarfile,threadingandwave. This means they will export new symbols whenimport *is used. (Contributed by Joel Taddei and Jacek Kołodziej in23883.) -
When performing a relative import, if
__package__does not compare equal to__spec__.parentthenImportWarningis raised. (Contributed by Brett Cannon in25791.) -
When a relative import is performed and no parent package is known, then
ImportErrorwill be raised. Previously,SystemErrorcould be raised. (Contributed by Brett Cannon in18018.) -
Servers based on the
socketservermodule, including those defined inhttp.server,xmlrpc.serverandwsgiref.simple_server, now only catch exceptions derived fromException. Therefore if a request handler raises an exception likeSystemExitorKeyboardInterrupt,~socketserver.BaseServer.handle_erroris no longer called, and the exception will stop a single-threaded server. (Contributed by Martin Panter in23430.) -
!spwd.getspnamnow raises aPermissionErrorinstead ofKeyErrorif the user doesn't have privileges. -
The
socket.socket.closemethod now raises an exception if an error (e.g.EBADF) was reported by the underlying system call. (Contributed by Martin Panter in26685.) -
The decode_data argument for the
!smtpd.SMTPChanneland!smtpd.SMTPServerconstructors is nowFalseby default. This means that the argument passed to!process_messageis now a bytes object by default, and!process_messagewill be passed keyword arguments. Code that has already been updated in accordance with the deprecation warning generated by 3.5 will not be affected. -
All optional arguments of the
~json.dump,~json.dumps,~json.loadand~json.loadsfunctions and~json.JSONEncoderand~json.JSONDecoderclass constructors in thejsonmodule are nowkeyword-only <keyword-only_parameter>. (Contributed by Serhiy Storchaka in18726.) -
Subclasses of
typewhich don't overridetype.__new__may no longer use the one-argument form to get the type of an object. -
As part of
487, the handling of keyword arguments passed totype(other than the metaclass hint,metaclass) is now consistently delegated toobject.__init_subclass__. This means thattype.__new__ <object.__new__>andtype.__init__ <object.__init__>both now accept arbitrary keyword arguments, butobject.__init_subclass__(which is called fromtype.__new__ <object.__new__>) will reject them by default. Custom metaclasses accepting additional keyword arguments will need to adjust their calls totype.__new__ <object.__new__>(whether direct or viasuper) accordingly. -
In
distutils.command.sdist.sdist, thedefault_formatattribute has been removed and is no longer honored. Instead, the gzipped tarfile format is the default on all platforms and no platform-specific selection is made. In environments where distributions are built on Windows and zip distributions are required, configure the project with asetup.cfgfile containing the following:[sdist] formats=zipThis behavior has also been backported to earlier Python versions by Setuptools 26.0.0.
-
In the
urllib.requestmodule and thehttp.client.HTTPConnection.requestmethod, if no Content-Length header field has been specified and the request body is a file object, it is now sent with HTTP 1.1 chunked encoding. If a file object has to be sent to a HTTP 1.0 server, the Content-Length value now has to be specified by the caller. (Contributed by Demian Brecht and Rolf Krahl with tweaks from Martin Panter in12319.) -
The
~csv.DictReadernow returns rows of type~collections.OrderedDict. (Contributed by Steve Holden in27842.) -
The
!crypt.METHOD_CRYPTwill no longer be added tocrypt.methodsif unsupported by the platform. (Contributed by Victor Stinner in25287.) -
The verbose and rename arguments for
~collections.namedtupleare now keyword-only. (Contributed by Raymond Hettinger in25628.) -
On Linux,
ctypes.util.find_librarynow looks inLD_LIBRARY_PATHfor shared libraries. (Contributed by Vinay Sajip in9998.) -
The
imaplib.IMAP4class now handles flags containing the']'character in messages sent from the server to improve real-world compatibility. (Contributed by Lita Cho in21815.) -
The
mmap.mmap.writefunction now returns the number of bytes written like other write methods. (Contributed by Jakub Stasiak in26335.) -
The
pkgutil.iter_modulesandpkgutil.walk_packagesfunctions now return~pkgutil.ModuleInfonamed tuples. (Contributed by Ramchandra Apte in17211.) -
re.subnow raises an error for invalid numerical group references in replacement templates even if the pattern is not found in the string. The error message for invalid group references now includes the group index and the position of the reference. (Contributed by SilentGhost, Serhiy Storchaka in25953.) -
zipfile.ZipFilewill now raiseNotImplementedErrorfor unrecognized compression values. Previously a plainRuntimeErrorwas raised. Additionally, calling~zipfile.ZipFilemethods on a closed ZipFile or calling the~zipfile.ZipFile.writemethod on a ZipFile created with mode'r'will raise aValueError. Previously, aRuntimeErrorwas raised in those scenarios. -
when custom metaclasses are combined with zero-argument
superor direct references from methods to the implicit__class__closure variable, the implicit__classcell__namespace entry must now be passed up totype.__new__for initialisation. Failing to do so will result in aDeprecationWarningin Python 3.6 and aRuntimeErrorin Python 3.8. -
With the introduction of
ModuleNotFoundError, import system consumers may start expecting import system replacements to raise that more specific exception when appropriate, rather than the less-specificImportError. To provide future compatibility with such consumers, implementers of alternative import systems that completely replace__import__will need to update their implementations to raise the new subclass when a module can't be found at all. Implementers of compliant plugins to the default import system shouldn't need to make any changes, as the default import system will raise the new subclass when appropriate.
Changes in the C API
- The
PyMem_Mallocallocator family now uses thepymalloc allocator <pymalloc>rather than the systemmalloc. Applications callingPyMem_Mallocwithout holding the GIL can now crash. Set thePYTHONMALLOCenvironment variable todebugto validate the usage of memory allocators in your application. See26249. Py_Exit(and the main interpreter) now override the exit status with 120 if flushing buffered data failed. See5319.
CPython bytecode changes
There have been several major changes to the bytecode in Python 3.6.
- The Python interpreter now uses a 16-bit wordcode instead of bytecode. (Contributed by Demur Rumed with input and reviews from Serhiy Storchaka and Victor Stinner in
26647and28050.) - The new
!FORMAT_VALUEandBUILD_STRINGopcodes as part of theformatted string literal <whatsnew36-pep498>implementation. (Contributed by Eric Smith in25483and Serhiy Storchaka in27078.) - The new
!BUILD_CONST_KEY_MAPopcode to optimize the creation of dictionaries with constant keys. (Contributed by Serhiy Storchaka in27140.) - The function call opcodes have been heavily reworked for better performance and simpler implementation. The
MAKE_FUNCTION,!CALL_FUNCTION,!CALL_FUNCTION_KWand!BUILD_MAP_UNPACK_WITH_CALLopcodes have been modified, the newCALL_FUNCTION_EXand!BUILD_TUPLE_UNPACK_WITH_CALLhave been added, andCALL_FUNCTION_VAR,CALL_FUNCTION_VAR_KWandMAKE_CLOSUREopcodes have been removed. (Contributed by Demur Rumed in27095, and Serhiy Storchaka in27213,28257.) - The new
SETUP_ANNOTATIONSand!STORE_ANNOTATIONopcodes have been added to support the newvariable annotationsyntax. (Contributed by Ivan Levkivskyi in27985.)
Notable changes in Python 3.6.2
New make regen-all build target
To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.
Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).
More selective regeneration targets are also defined - see Makefile.pre.in for details.
(Contributed by Victor Stinner in 23404.)
3.6.2
Removal of make touch build target
The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.
It has been replaced by the new make regen-all target.
(Contributed by Victor Stinner in 23404.)
3.6.2
Notable changes in Python 3.6.4
The PyExc_RecursionErrorInst singleton that was part of the public API has been removed as its members being never cleared may cause a segfault during finalization of the interpreter. (Contributed by Xavier de Gaye in 22898 and 30697.)
Notable changes in Python 3.6.5
The locale.localeconv function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases. (Contributed by Victor Stinner in 31900.)
Notable changes in Python 3.6.7
xml.dom.minidom and xml.sax modules no longer process external entities by default. See also 61441.
In 3.6.7 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 33899.)
Notable changes in Python 3.6.10
Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in 37228.)
Notable changes in Python 3.6.13
Earlier Python versions allowed using both ; and & as query parameter separators in urllib.parse.parse_qs and urllib.parse.parse_qsl. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects !cgi.parse and !cgi.parse_multipart as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in 42967.)
Notable changes in Python 3.6.14
A security fix alters the ftplib.FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel. We reuse the ftp server IP address instead. For unusual code requiring the old behavior, set a trust_server_pasv_ipv4_address attribute on your FTP instance to True. (See 87451)
The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates RFC 3986, ASCII newline \n, \r and tab \t characters are stripped from the URL by the parser urllib.parse preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (See 88048)
What's New In Python 3.7
Editor
Elvis Pranskevichus <elvis@magic.io>
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Git log when researching a change.
This article explains the new features in Python 3.7, compared to 3.6. Python 3.7 was released on June 27, 2018. For full details, see the changelog <changelog>.
Summary -- Release Highlights
New syntax features:
PEP 563 <whatsnew37-pep563>, postponed evaluation of type annotations.
Backwards incompatible syntax changes:
asyncandawaitare now reserved keywords.
New library modules:
contextvars:PEP 567 -- Context Variables <whatsnew37-pep567>dataclasses:PEP 557 -- Data Classes <whatsnew37-pep557>whatsnew37_importlib_resources
New built-in features:
PEP 553 <whatsnew37-pep553>, the newbreakpointfunction.
Python data model improvements:
PEP 562 <whatsnew37-pep562>, customization of access to module attributes.PEP 560 <whatsnew37-pep560>, core support for typing module and generic types.- the insertion-order preservation nature of
dict <typesmapping>objects has been declared to be an official part of the Python language spec.
Significant improvements in the standard library:
- The
asynciomodule has received new features, significantusability and performance improvements <whatsnew37_asyncio>. - The
timemodule gained support forfunctions with nanosecond resolution <whatsnew37-pep564>.
CPython implementation improvements:
- Avoiding the use of ASCII as a default text encoding:
PEP 538 <whatsnew37-pep538>, legacy C locale coercionPEP 540 <whatsnew37-pep540>, forced UTF-8 runtime mode
PEP 552 <whatsnew37-pep552>, deterministic .pycsNew Python Development Mode <whatsnew37-devmode>PEP 565 <whatsnew37-pep565>, improvedDeprecationWarninghandling
C API improvements:
PEP 539 <whatsnew37-pep539>, new C API for thread-local storage
Documentation improvements:
PEP 545 <whatsnew37-pep545>, Python documentation translations- New documentation translations: Japanese, French, and Korean.
This release features notable performance improvements in many areas. The whatsnew37-perf section lists them in detail.
For a list of changes that may affect compatibility with previous Python releases please refer to the porting-to-python-37 section.
New Features
PEP 563: Postponed Evaluation of Annotations
The advent of type hints in Python uncovered two glaring usability issues with the functionality of annotations added in 3107 and refined further in 526:
- annotations could only use names which were already available in the current scope, in other words they didn't support forward references of any kind; and
- annotating source code had adverse effects on startup time of Python programs.
Both of these issues are fixed by postponing the evaluation of annotations. Instead of compiling code which executes expressions in annotations at their definition time, the compiler stores the annotation in a string form equivalent to the AST of the expression in question. If needed, annotations can be resolved at runtime using typing.get_type_hints. In the common case where this is not required, the annotations are cheaper to store (since short strings are interned by the interpreter) and make startup time faster.
Usability-wise, annotations now support forward references, making the following syntax valid:
class C:
@classmethod
def from_string(cls, source: str) -> C:
...
def validate_b(self, obj: B) -> bool:
...
class B:
...
Since this change breaks compatibility, the new behavior needs to be enabled on a per-module basis in Python 3.7 using a __future__ import:
from __future__ import annotations
It will become the default in Python 3.10.
563 -- Postponed evaluation of annotations
PEP written and implemented by Łukasz Langa.
PEP 538: Legacy C Locale Coercion
An ongoing challenge within the Python 3 series has been determining a sensible default strategy for handling the "7-bit ASCII" text encoding assumption currently implied by the use of the default C or POSIX locale on non-Windows platforms.
538 updates the default interpreter command line interface to automatically coerce that locale to an available UTF-8 based locale as described in the documentation of the new PYTHONCOERCECLOCALE environment variable. Automatically setting LC_CTYPE this way means that both the core interpreter and locale-aware C extensions (such as readline) will assume the use of UTF-8 as the default text encoding, rather than ASCII.
The platform support definition in 11 has also been updated to limit full text handling support to suitably configured non-ASCII based locales.
As part of this change, the default error handler for ~sys.stdin and ~sys.stdout is now surrogateescape (rather than strict) when using any of the defined coercion target locales (currently C.UTF-8, C.utf8, and UTF-8). The default error handler for ~sys.stderr continues to be backslashreplace, regardless of locale.
Locale coercion is silent by default, but to assist in debugging potentially locale related integration problems, explicit warnings (emitted directly on ~sys.stderr) can be requested by setting PYTHONCOERCECLOCALE=warn. This setting will also cause the Python runtime to emit a warning if the legacy C locale remains active when the core interpreter is initialized.
While 538's locale coercion has the benefit of also affecting extension modules (such as GNU readline), as well as child processes (including those running non-Python applications and older versions of Python), it has the downside of requiring that a suitable target locale be present on the running system. To better handle the case where no suitable target locale is available (as occurs on RHEL/CentOS 7, for example), Python 3.7 also implements whatsnew37-pep540.
538 -- Coercing the legacy C locale to a UTF-8 based locale
PEP written and implemented by Nick Coghlan.
PEP 540: Forced UTF-8 Runtime Mode
The new -X utf8 command line option and PYTHONUTF8 environment variable can be used to enable the Python UTF-8 Mode <utf8-mode>.
When in UTF-8 mode, CPython ignores the locale settings, and uses the UTF-8 encoding by default. The error handlers for sys.stdin and sys.stdout streams are set to surrogateescape.
The forced UTF-8 mode can be used to change the text handling behavior in an embedded Python interpreter without changing the locale settings of an embedding application.
While 540's UTF-8 mode has the benefit of working regardless of which locales are available on the running system, it has the downside of having no effect on extension modules (such as GNU readline), child processes running non-Python applications, and child processes running older versions of Python. To reduce the risk of corrupting text data when communicating with such components, Python 3.7 also implements whatsnew37-pep540).
The UTF-8 mode is enabled by default when the locale is C or POSIX, and the 538 locale coercion feature fails to change it to a UTF-8 based alternative (whether that failure is due to PYTHONCOERCECLOCALE=0 being set, LC_ALL being set, or the lack of a suitable target locale).
540 -- Add a new UTF-8 mode
PEP written and implemented by Victor Stinner
PEP 553: Built-in breakpoint()
Python 3.7 includes the new built-in breakpoint function as an easy and consistent way to enter the Python debugger.
Built-in breakpoint() calls sys.breakpointhook. By default, the latter imports pdb and then calls pdb.set_trace(), but by binding sys.breakpointhook() to the function of your choosing, breakpoint() can enter any debugger. Additionally, the environment variable PYTHONBREAKPOINT can be set to the callable of your debugger of choice. Set PYTHONBREAKPOINT=0 to completely disable built-in breakpoint().
553 -- Built-in breakpoint()
PEP written and implemented by Barry Warsaw
PEP 539: New C API for Thread-Local Storage
While Python provides a C API for thread-local storage support; the existing Thread Local Storage (TLS) API <thread-local-storage-api> has used int to represent TLS keys across all platforms. This has not generally been a problem for officially support platforms, but that is neither POSIX-compliant, nor portable in any practical sense.
539 changes this by providing a new Thread Specific Storage (TSS) API <thread-specific-storage-api> to CPython which supersedes use of the existing TLS API within the CPython interpreter, while deprecating the existing API. The TSS API uses a new type Py_tss_t instead of int to represent TSS keys--an opaque type the definition of which may depend on the underlying TLS implementation. Therefore, this will allow to build CPython on platforms where the native TLS key is defined in a way that cannot be safely cast to int.
Note that on platforms where the native TLS key is defined in a way that cannot be safely cast to int, all functions of the existing TLS API will be no-op and immediately return failure. This indicates clearly that the old API is not supported on platforms where it cannot be used reliably, and that no effort will be made to add such support.
539 -- A New C-API for Thread-Local Storage in CPython
PEP written by Erik M. Bray; implementation by Masayuki Yamamoto.
PEP 562: Customization of Access to Module Attributes
Python 3.7 allows defining ~module.__getattr__ on modules and will call it whenever a module attribute is otherwise not found. Defining ~module.__dir__ on modules is now also allowed.
A typical example of where this may be useful is module attribute deprecation and lazy loading.
562 -- Module __getattr__ and __dir__
PEP written and implemented by Ivan Levkivskyi
PEP 564: New Time Functions With Nanosecond Resolution
The resolution of clocks in modern systems can exceed the limited precision of a floating-point number returned by the time.time function and its variants. To avoid loss of precision, 564 adds six new "nanosecond" variants of the existing timer functions to the time module:
time.clock_gettime_nstime.clock_settime_nstime.monotonic_nstime.perf_counter_nstime.process_time_nstime.time_ns
The new functions return the number of nanoseconds as an integer value.
Measurements <0564#annex-clocks-resolution-in-python> show that on Linux and Windows the resolution of time.time_ns is approximately 3 times better than that of time.time.
564 -- Add new time functions with nanosecond resolution
PEP written and implemented by Victor Stinner
PEP 565: Show DeprecationWarning in __main__
The default handling of DeprecationWarning has been changed such that these warnings are once more shown by default, but only when the code triggering them is running directly in the __main__ module. As a result, developers of single file scripts and those using Python interactively should once again start seeing deprecation warnings for the APIs they use, but deprecation warnings triggered by imported application, library and framework modules will continue to be hidden by default.
As a result of this change, the standard library now allows developers to choose between three different deprecation warning behaviours:
FutureWarning: always displayed by default, recommended for warnings intended to be seen by application end users (e.g. for deprecated application configuration settings).DeprecationWarning: displayed by default only in__main__and when running tests, recommended for warnings intended to be seen by other Python developers where a version upgrade may result in changed behaviour or an error.PendingDeprecationWarning: displayed by default only when running tests, intended for cases where a future version upgrade will change the warning category toDeprecationWarningorFutureWarning.
Previously both DeprecationWarning and PendingDeprecationWarning were only visible when running tests, which meant that developers primarily writing single file scripts or using Python interactively could be surprised by breaking changes in the APIs they used.
565 -- Show DeprecationWarning in __main__
PEP written and implemented by Nick Coghlan
PEP 560: Core Support for typing module and Generic Types
Initially 484 was designed in such way that it would not introduce any changes to the core CPython interpreter. Now type hints and the typing module are extensively used by the community, so this restriction is removed. The PEP introduces two special methods ~object.__class_getitem__ and ~object.__mro_entries__, these methods are now used by most classes and special constructs in typing. As a result, the speed of various operations with types increased up to 7 times, the generic types can be used without metaclass conflicts, and several long standing bugs in typing module are fixed.
560 -- Core support for typing module and generic types
PEP written and implemented by Ivan Levkivskyi
PEP 552: Hash-based .pyc Files
Python has traditionally checked the up-to-dateness of bytecode cache files (i.e., .pyc files) by comparing the source metadata (last-modified timestamp and size) with source metadata saved in the cache file header when it was generated. While effective, this invalidation method has its drawbacks. When filesystem timestamps are too coarse, Python can miss source updates, leading to user confusion. Additionally, having a timestamp in the cache file is problematic for build reproducibility and content-based build systems.
552 extends the pyc format to allow the hash of the source file to be used for invalidation instead of the source timestamp. Such .pyc files are called "hash-based". By default, Python still uses timestamp-based invalidation and does not generate hash-based .pyc files at runtime. Hash-based .pyc files may be generated with py_compile or compileall.
Hash-based .pyc files come in two variants: checked and unchecked. Python validates checked hash-based .pyc files against the corresponding source files at runtime but doesn't do so for unchecked hash-based pycs. Unchecked hash-based .pyc files are a useful performance optimization for environments where a system external to Python (e.g., the build system) is responsible for keeping .pyc files up-to-date.
See pyc-invalidation for more information.
552 -- Deterministic pycs
PEP written and implemented by Benjamin Peterson
PEP 545: Python Documentation Translations
545 describes the process of creating and maintaining Python documentation translations.
Three new translations have been added:
- Japanese: https://docs.python.org/ja/
- French: https://docs.python.org/fr/
- Korean: https://docs.python.org/ko/
545 -- Python Documentation Translations
PEP written and implemented by Julien Palard, Inada Naoki, and Victor Stinner.
Python Development Mode (-X dev)
The new -X dev command line option or the new PYTHONDEVMODE environment variable can be used to enable Python Development Mode <devmode>. When in development mode, Python performs additional runtime checks that are too expensive to be enabled by default. See Python Development Mode <devmode> documentation for the full description.
Other Language Changes
- An
awaitexpression and comprehensions containing anasync forclause were illegal in the expressions informatted string literals <f-strings>due to a problem with the implementation. In Python 3.7 this restriction was lifted. - More than 255 arguments can now be passed to a function, and a function can now have more than 255 parameters. (Contributed by Serhiy Storchaka in
12844and18896.) bytes.fromhexandbytearray.fromhexnow ignore all ASCII whitespace, not only spaces. (Contributed by Robert Xiao in28927.)str,bytes, andbytearraygained support for the newisascii() <str.isascii>method, which can be used to test if a string or bytes contain only the ASCII characters. (Contributed by INADA Naoki in32677.)ImportErrornow displays module name and module__file__path whenfrom ... import ...fails. (Contributed by Matthias Bussonnier in29546.)- Circular imports involving absolute imports with binding a submodule to a name are now supported. (Contributed by Serhiy Storchaka in
30024.) object.__format__(x, '')is now equivalent tostr(x)rather thanformat(str(self), ''). (Contributed by Serhiy Storchaka in28974.)- In order to better support dynamic creation of stack traces,
types.TracebackTypecan now be instantiated from Python code, and the~traceback.tb_nextattribute ontracebacks <traceback-objects>is now writable. (Contributed by Nathaniel J. Smith in30579.) - When using the
-mswitch,sys.path[0]is now eagerly expanded to the full starting directory path, rather than being left as the empty directory (which allows imports from the current working directory at the time when an import occurs) (Contributed by Nick Coghlan in33053.) - The new
-Ximporttimeoption or thePYTHONPROFILEIMPORTTIMEenvironment variable can be used to show the timing of each module import. (Contributed by Inada Naoki in31415.)
New Modules
contextvars
The new contextvars module and a set of new C APIs <contextvarsobjects> introduce support for context variables. Context variables are conceptually similar to thread-local variables. Unlike TLS, context variables support asynchronous code correctly.
The asyncio and decimal modules have been updated to use and support context variables out of the box. Particularly the active decimal context is now stored in a context variable, which allows decimal operations to work with the correct context in asynchronous code.
567 -- Context Variables
PEP written and implemented by Yury Selivanov
dataclasses
The new ~dataclasses.dataclass decorator provides a way to declare data classes. A data class describes its attributes using class variable annotations. Its constructor and other magic methods, such as ~object.__repr__, ~object.__eq__, and ~object.__hash__ are generated automatically.
Example:
@dataclass
class Point:
x: float
y: float
z: float = 0.0
p = Point(1.5, 2.5)
print(p) # produces "Point(x=1.5, y=2.5, z=0.0)"
557 -- Data Classes
PEP written and implemented by Eric V. Smith
importlib.resources
The new importlib.resources module provides several new APIs and one new ABC for access to, opening, and reading resources inside packages. Resources are roughly similar to files inside packages, but they needn't be actual files on the physical file system. Module loaders can provide a !get_resource_reader function which returns a !importlib.abc.ResourceReader instance to support this new API. Built-in file path loaders and zip file loaders both support this.
Contributed by Barry Warsaw and Brett Cannon in 32248.
importlib_resources -- a PyPI backport for earlier Python versions.
Improved Modules
argparse
The new ArgumentParser.parse_intermixed_args() <argparse.ArgumentParser.parse_intermixed_args> method allows intermixing options and positional arguments. (Contributed by paul.j3 in 14191.)
asyncio
The asyncio module has received many new features, usability and performance improvements <whatsnew37-asyncio-perf>. Notable changes include:
-
The new
provisional <provisional API>asyncio.runfunction can be used to run a coroutine from synchronous code by automatically creating and destroying the event loop. (Contributed by Yury Selivanov in32314.) -
asyncio gained support for
contextvars.loop.call_soon() <asyncio.loop.call_soon>,loop.call_soon_threadsafe() <asyncio.loop.call_soon_threadsafe>,loop.call_later() <asyncio.loop.call_later>,loop.call_at() <asyncio.loop.call_at>, andFuture.add_done_callback() <asyncio.Future.add_done_callback>have a new optional keyword-only context parameter.Tasks <asyncio.Task>now track their context automatically. See567for more details. (Contributed by Yury Selivanov in32436.) -
The new
asyncio.create_taskfunction has been added as a shortcut toasyncio.get_event_loop().create_task(). (Contributed by Andrew Svetlov in32311.) -
The new
loop.start_tls() <asyncio.loop.start_tls>method can be used to upgrade an existing connection to TLS. (Contributed by Yury Selivanov in23749.) -
The new
loop.sock_recv_into() <asyncio.loop.sock_recv_into>method allows reading data from a socket directly into a provided buffer making it possible to reduce data copies. (Contributed by Antoine Pitrou in31819.) -
The new
asyncio.current_taskfunction returns the currently running~asyncio.Taskinstance, and the newasyncio.all_tasksfunction returns a set of all existingTaskinstances in a given loop. The!Task.current_taskand!Task.all_tasksmethods have been deprecated. (Contributed by Andrew Svetlov in32250.) -
The new provisional
~asyncio.BufferedProtocolclass allows implementing streaming protocols with manual control over the receive buffer. (Contributed by Yury Selivanov in32251.) -
The new
asyncio.get_running_loopfunction returns the currently running loop, and raises aRuntimeErrorif no loop is running. This is in contrast withasyncio.get_event_loop, which will create a new event loop if none is running. (Contributed by Yury Selivanov in32269.) -
The new
StreamWriter.wait_closed() <asyncio.StreamWriter.wait_closed>coroutine method allows waiting until the stream writer is closed. The newStreamWriter.is_closing() <asyncio.StreamWriter.is_closing>method can be used to determine if the writer is closing. (Contributed by Andrew Svetlov in32391.) -
The new
loop.sock_sendfile() <asyncio.loop.sock_sendfile>coroutine method allows sending files usingos.sendfilewhen possible. (Contributed by Andrew Svetlov in32410.) -
The new
Future.get_loop() <asyncio.Future.get_loop>andTask.get_loop()methods return the instance of the loop on which a task or a future were created.Server.get_loop() <asyncio.Server.get_loop>allows doing the same forasyncio.Serverobjects. (Contributed by Yury Selivanov in32415and Srinivas Reddy Thatiparthy in32418.) -
It is now possible to control how instances of
asyncio.Serverbegin serving. Previously, the server would start serving immediately when created. The new start_serving keyword argument toloop.create_server() <asyncio.loop.create_server>andloop.create_unix_server() <asyncio.loop.create_unix_server>, as well asServer.start_serving() <asyncio.Server.start_serving>, andServer.serve_forever() <asyncio.Server.serve_forever>can be used to decouple server instantiation and serving. The newServer.is_serving() <asyncio.Server.is_serving>method returnsTrueif the server is serving.~asyncio.Serverobjects are now asynchronous context managers:srv = await loop.create_server(...) async with srv: # some code # At this point, srv is closed and no longer accepts new connections.(Contributed by Yury Selivanov in
32662.) -
Callback objects returned by
loop.call_later() <asyncio.loop.call_later>gained the newwhen() <asyncio.TimerHandle.when>method which returns an absolute scheduled callback timestamp. (Contributed by Andrew Svetlov in32741.) -
The :meth:`loop.create_datagram_endpoint() <asyncio.loop.create_datagram_endpoint>` method gained support for Unix sockets. (Contributed by Quentin Dawans in
31245.) -
The
asyncio.open_connection,asyncio.start_serverfunctions,loop.create_connection() <asyncio.loop.create_connection>,loop.create_server() <asyncio.loop.create_server>,loop.create_accepted_socket() <asyncio.loop.connect_accepted_socket>methods and their corresponding UNIX socket variants now accept the ssl_handshake_timeout keyword argument. (Contributed by Neil Aspinall in29970.) -
The new
Handle.cancelled() <asyncio.Handle.cancelled>method returnsTrueif the callback was cancelled. (Contributed by Marat Sharafutdinov in31943.) -
The asyncio source has been converted to use the
async/awaitsyntax. (Contributed by Andrew Svetlov in32193.) -
The new
ReadTransport.is_reading() <asyncio.ReadTransport.is_reading>method can be used to determine the reading state of the transport. Additionally, calls toReadTransport.resume_reading() <asyncio.ReadTransport.resume_reading>andReadTransport.pause_reading() <asyncio.ReadTransport.pause_reading>are now idempotent. (Contributed by Yury Selivanov in32356.) -
Loop methods which accept socket paths now support passing
path-like objects <path-like object>. (Contributed by Yury Selivanov in32066.) -
In
asyncioTCP sockets on Linux are now created withTCP_NODELAYflag set by default. (Contributed by Yury Selivanov and Victor Stinner in27456.) -
Exceptions occurring in cancelled tasks are no longer logged. (Contributed by Yury Selivanov in
30508.) -
New
WindowsSelectorEventLoopPolicyandWindowsProactorEventLoopPolicyclasses. (Contributed by Yury Selivanov in33792.)
Several asyncio APIs have been deprecated <whatsnew37-asyncio-deprecated>.
binascii
The ~binascii.b2a_uu function now accepts an optional backtick keyword argument. When it's true, zeros are represented by '`' instead of spaces. (Contributed by Xiang Zhang in 30103.)
calendar
The ~calendar.HTMLCalendar class has new class attributes which ease the customization of CSS classes in the produced HTML calendar. (Contributed by Oz Tiram in 30095.)
collections
collections.namedtuple() now supports default values. (Contributed by Raymond Hettinger in 32320.)
compileall
compileall.compile_dir learned the new invalidation_mode parameter, which can be used to enable hash-based .pyc invalidation <whatsnew37-pep552>. The invalidation mode can also be specified on the command line using the new --invalidation-mode argument. (Contributed by Benjamin Peterson in 31650.)
concurrent.futures
ProcessPoolExecutor <concurrent.futures.ProcessPoolExecutor> and ThreadPoolExecutor <concurrent.futures.ThreadPoolExecutor> now support the new initializer and initargs constructor arguments. (Contributed by Antoine Pitrou in 21423.)
The ProcessPoolExecutor <concurrent.futures.ProcessPoolExecutor> can now take the multiprocessing context via the new mp_context argument. (Contributed by Thomas Moreau in 31540.)
contextlib
The new ~contextlib.nullcontext is a simpler and faster no-op context manager than ~contextlib.ExitStack. (Contributed by Jesse-Bakker in 10049.)
The new ~contextlib.asynccontextmanager, ~contextlib.AbstractAsyncContextManager, and ~contextlib.AsyncExitStack have been added to complement their synchronous counterparts. (Contributed by Jelle Zijlstra in 29679 and 30241, and by Alexander Mohr and Ilya Kulakov in 29302.)
cProfile
The !cProfile command line now accepts -m module_name as an alternative to script path. (Contributed by Sanyam Khurana in 21862.)
crypt
The !crypt module now supports the Blowfish hashing method. (Contributed by Serhiy Storchaka in 31664.)
The !mksalt function now allows specifying the number of rounds for hashing. (Contributed by Serhiy Storchaka in 31702.)
datetime
The new datetime.fromisoformat() <datetime.datetime.fromisoformat> method constructs a ~datetime.datetime object from a string in one of the formats output by datetime.isoformat() <datetime.datetime.isoformat>. (Contributed by Paul Ganssle in 15873.)
The tzinfo <datetime.tzinfo> class now supports sub-minute offsets. (Contributed by Alexander Belopolsky in 5288.)
dbm
dbm.dumb now supports reading read-only files and no longer writes the index file when it is not changed.
decimal
The decimal module now uses context variables <whatsnew37-pep567> to store the decimal context. (Contributed by Yury Selivanov in 32630.)
dis
The ~dis.dis function is now able to disassemble nested code objects (the code of comprehensions, generator expressions and nested functions, and the code used for building nested classes). The maximum depth of disassembly recursion is controlled by the new depth parameter. (Contributed by Serhiy Storchaka in 11822.)
distutils
README.rst is now included in the list of distutils standard READMEs and therefore included in source distributions. (Contributed by Ryan Gonzalez in 11913.)
enum
The Enum <enum.Enum> learned the new _ignore_ class property, which allows listing the names of properties which should not become enum members. (Contributed by Ethan Furman in 31801.)
In Python 3.8, attempting to check for non-Enum objects in ~enum.Enum classes will raise a TypeError (e.g. 1 in Color); similarly, attempting to check for non-Flag objects in a ~enum.Flag member will raise TypeError (e.g. 1 in Perm.RW); currently, both operations return False instead and are deprecated. (Contributed by Ethan Furman in 33217.)
functools
functools.singledispatch now supports registering implementations using type annotations. (Contributed by Łukasz Langa in 32227.)
gc
The new gc.freeze function allows freezing all objects tracked by the garbage collector and excluding them from future collections. This can be used before a POSIX fork() call to make the GC copy-on-write friendly or to speed up collection. The new gc.unfreeze functions reverses this operation. Additionally, gc.get_freeze_count can be used to obtain the number of frozen objects. (Contributed by Li Zekun in 31558.)
hmac
The hmac module now has an optimized one-shot ~hmac.digest function, which is up to three times faster than ~hmac.HMAC. (Contributed by Christian Heimes in 32433.)
http.client
~http.client.HTTPConnection and ~http.client.HTTPSConnection now support the new blocksize argument for improved upload throughput. (Contributed by Nir Soffer in 31945.)
http.server
~http.server.SimpleHTTPRequestHandler now supports the HTTP If-Modified-Since header. The server returns the 304 response status if the target file was not modified after the time specified in the header. (Contributed by Pierre Quentel in 29654.)
~http.server.SimpleHTTPRequestHandler accepts the new directory argument, in addition to the new --directory command line argument. With this parameter, the server serves the specified directory, by default it uses the current working directory. (Contributed by Stéphane Wirtel and Julien Palard in 28707.)
The new ThreadingHTTPServer <http.server.ThreadingHTTPServer> class uses threads to handle requests using ~socketserver.ThreadingMixIn. It is used when http.server is run with -m. (Contributed by Julien Palard in 31639.)
idlelib and IDLE
Multiple fixes for autocompletion. (Contributed by Louie Lu in 15786.)
Module Browser (on the File menu, formerly called Class Browser), now displays nested functions and classes in addition to top-level functions and classes. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy in 1612262.)
The Settings dialog (Options, Configure IDLE) has been partly rewritten to improve both appearance and function. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)
The font sample now includes a selection of non-Latin characters so that users can better see the effect of selecting a particular font. (Contributed by Terry Jan Reedy in 13802.) The sample can be edited to include other characters. (Contributed by Serhiy Storchaka in 31860.)
The IDLE features formerly implemented as extensions have been reimplemented as normal features. Their settings have been moved from the Extensions tab to other dialog tabs. (Contributed by Charles Wohlganger and Terry Jan Reedy in 27099.)
Editor code context option revised. Box displays all context lines up to maxlines. Clicking on a context line jumps the editor to that line. Context colors for custom themes is added to Highlights tab of Settings dialog. (Contributed by Cheryl Sabella and Terry Jan Reedy in 33642, 33768, and 33679.)
On Windows, a new API call tells Windows that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect. (Contributed by Terry Jan Reedy in 33656.)
New in 3.7.1:
Output over N lines (50 by default) is squeezed down to a button. N can be changed in the PyShell section of the General page of the Settings dialog. Fewer, but possibly extra long, lines can be squeezed by right clicking on the output. Squeezed output can be expanded in place by double-clicking the button or into the clipboard or a separate window by right-clicking the button. (Contributed by Tal Einat in 1529353.)
The changes above have been backported to 3.6 maintenance releases.
NEW in 3.7.4:
Add "Run Customized" to the Run menu to run a module with customized settings. Any command line arguments entered are added to sys.argv. They re-appear in the box for the next customized run. One can also suppress the normal Shell main module restart. (Contributed by Cheryl Sabella, Terry Jan Reedy, and others in 5680 and 37627.)
New in 3.7.5:
Add optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog. Line numbers for an existing window are shown and hidden in the Options menu. (Contributed by Tal Einat and Saimadhav Heblikar in 17535.)
importlib
The !importlib.abc.ResourceReader ABC was introduced to support the loading of resources from packages. See also whatsnew37_importlib_resources. (Contributed by Barry Warsaw, Brett Cannon in 32248.)
importlib.reload now raises ModuleNotFoundError if the module lacks a spec. (Contributed by Garvit Khatri in 29851.)
importlib.util.find_spec now raises ModuleNotFoundError instead of AttributeError if the specified parent module is not a package (i.e. lacks a __path__ attribute). (Contributed by Milan Oberkirch in 30436.)
The new importlib.util.source_hash can be used to compute the hash of the passed source. A hash-based .pyc file <whatsnew37-pep552> embeds the value returned by this function.
io
The new TextIOWrapper.reconfigure() <io.TextIOWrapper.reconfigure> method can be used to reconfigure the text stream with the new settings. (Contributed by Antoine Pitrou in 30526 and INADA Naoki in 15216.)
ipaddress
The new subnet_of() and supernet_of() methods of ipaddress.IPv6Network and ipaddress.IPv4Network can be used for network containment tests. (Contributed by Michel Albert and Cheryl Sabella in 20825.)
itertools
itertools.islice now accepts integer-like objects <object.__index__> as start, stop, and slice arguments. (Contributed by Will Roberts in 30537.)
locale
The new monetary argument to locale.format_string can be used to make the conversion use monetary thousands separators and grouping strings. (Contributed by Garvit in 10379.)
The locale.getpreferredencoding function now always returns 'UTF-8' on Android or when in the forced UTF-8 mode <whatsnew37-pep540>.
logging
~logging.Logger instances can now be pickled. (Contributed by Vinay Sajip in 30520.)
The new StreamHandler.setStream() <logging.StreamHandler.setStream> method can be used to replace the logger stream after handler creation. (Contributed by Vinay Sajip in 30522.)
It is now possible to specify keyword arguments to handler constructors in configuration passed to logging.config.fileConfig. (Contributed by Preston Landers in 31080.)
math
The new math.remainder function implements the IEEE 754-style remainder operation. (Contributed by Mark Dickinson in 29962.)
mimetypes
The MIME type of .bmp has been changed from 'image/x-ms-bmp' to 'image/bmp'. (Contributed by Nitish Chandra in 22589.)
msilib
The new !Database.Close method can be used to close the MSI database. (Contributed by Berker Peksag in 20486.)
multiprocessing
The new Process.close() <multiprocessing.Process.close> method explicitly closes the process object and releases all resources associated with it. ValueError is raised if the underlying process is still running. (Contributed by Antoine Pitrou in 30596.)
The new Process.kill() <multiprocessing.Process.kill> method can be used to terminate the process using the ~signal.SIGKILL signal on Unix. (Contributed by Vitor Pereira in 30794.)
Non-daemonic threads created by ~multiprocessing.Process are now joined on process exit. (Contributed by Antoine Pitrou in 18966.)
os
os.fwalk now accepts the path argument as bytes. (Contributed by Serhiy Storchaka in 28682.)
os.scandir gained support for file descriptors <path_fd>. (Contributed by Serhiy Storchaka in 25996.)
The new ~os.register_at_fork function allows registering Python callbacks to be executed at process fork. (Contributed by Antoine Pitrou in 16500.)
Added os.preadv (combine the functionality of os.readv and os.pread) and os.pwritev functions (combine the functionality of os.writev and os.pwrite). (Contributed by Pablo Galindo in 31368.)
The mode argument of os.makedirs no longer affects the file permission bits of newly created intermediate-level directories. (Contributed by Serhiy Storchaka in 19930.)
os.dup2 now returns the new file descriptor. Previously, None was always returned. (Contributed by Benjamin Peterson in 32441.)
The structure returned by os.stat now contains the ~os.stat_result.st_fstype attribute on Solaris and its derivatives. (Contributed by Jesús Cea Avión in 32659.)
pathlib
The new Path.is_mount() <pathlib.Path.is_mount> method is now available on POSIX systems and can be used to determine whether a path is a mount point. (Contributed by Cooper Ry Lees in 30897.)
pdb
pdb.set_trace now takes an optional header keyword-only argument. If given, it is printed to the console just before debugging begins. (Contributed by Barry Warsaw in 31389.)
pdb command line now accepts -m module_name as an alternative to script file. (Contributed by Mario Corchero in 32206.)
py_compile
py_compile.compile -- and by extension, compileall -- now respects the SOURCE_DATE_EPOCH environment variable by unconditionally creating .pyc files for hash-based validation. This allows for guaranteeing reproducible builds of .pyc files when they are created eagerly. (Contributed by Bernhard M. Wiedemann in 29708.)
pydoc
The pydoc server can now bind to an arbitrary hostname specified by the new -n command-line argument. (Contributed by Feanil Patel in 31128.)
queue
The new ~queue.SimpleQueue class is an unbounded FIFO queue. (Contributed by Antoine Pitrou in 14976.)
re
The flags re.ASCII, re.LOCALE and re.UNICODE can be set within the scope of a group. (Contributed by Serhiy Storchaka in 31690.)
re.split now supports splitting on a pattern like r'\b', '^$' or (?=-) that matches an empty string. (Contributed by Serhiy Storchaka in 25054.)
Regular expressions compiled with the re.LOCALE flag no longer depend on the locale at compile time. Locale settings are applied only when the compiled regular expression is used. (Contributed by Serhiy Storchaka in 30215.)
FutureWarning is now emitted if a regular expression contains character set constructs that will change semantically in the future, such as nested sets and set operations. (Contributed by Serhiy Storchaka in 30349.)
Compiled regular expression and match objects can now be copied using copy.copy and copy.deepcopy. (Contributed by Serhiy Storchaka in 10076.)
signal
The new warn_on_full_buffer argument to the signal.set_wakeup_fd function makes it possible to specify whether Python prints a warning on stderr when the wakeup buffer overflows. (Contributed by Nathaniel J. Smith in 30050.)
socket
The new socket.getblocking() <socket.socket.getblocking> method returns True if the socket is in blocking mode and False otherwise. (Contributed by Yury Selivanov in 32373.)
The new socket.close function closes the passed socket file descriptor. This function should be used instead of os.close for better compatibility across platforms. (Contributed by Christian Heimes in 32454.)
The socket module now exposes the socket.TCP_CONGESTION <socket-unix-constants> (Linux 2.6.13), socket.TCP_USER_TIMEOUT <socket-unix-constants> (Linux 2.6.37), and socket.TCP_NOTSENT_LOWAT <socket-unix-constants> (Linux 3.12) constants. (Contributed by Omar Sandoval in 26273 and Nathaniel J. Smith in 29728.)
Support for socket.AF_VSOCK sockets has been added to allow communication between virtual machines and their hosts. (Contributed by Cathy Avery in 27584.)
Sockets now auto-detect family, type and protocol from file descriptor by default. (Contributed by Christian Heimes in 28134.)
socketserver
socketserver.ThreadingMixIn.server_close <socketserver.BaseServer.server_close> now waits until all non-daemon threads complete. socketserver.ForkingMixIn.server_close <socketserver.BaseServer.server_close> now waits until all child processes complete.
Add a new socketserver.ForkingMixIn.block_on_close <socketserver.ThreadingMixIn.block_on_close> class attribute to socketserver.ForkingMixIn and socketserver.ThreadingMixIn classes. Set the class attribute to False to get the pre-3.7 behaviour.
sqlite3
sqlite3.Connection now exposes the ~sqlite3.Connection.backup method when the underlying SQLite library is at version 3.6.11 or higher. (Contributed by Lele Gaifax in 27645.)
The database argument of sqlite3.connect now accepts any path-like object, instead of just a string. (Contributed by Anders Lorentsen in 31843.)
ssl
The ssl module now uses OpenSSL's builtin API instead of !match_hostname to check a host name or an IP address. Values are validated during TLS handshake. Any certificate validation error including failing the host name check now raises ~ssl.SSLCertVerificationError and aborts the handshake with a proper TLS Alert message. The new exception contains additional information. Host name validation can be customized with SSLContext.hostname_checks_common_name <ssl.SSLContext.hostname_checks_common_name>. (Contributed by Christian Heimes in 31399.)
[!NOTE] 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
37-platform-support-removalsfor 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 32185.)
!match_hostname no longer supports partial wildcards like www*.example.org. (Contributed by Mandeep Singh in 23033 and Christian Heimes in 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 31429.)
Validation of server certificates containing internationalized domain names (IDNs) is now supported. As part of this change, the SSLSocket.server_hostname <ssl.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 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 ssl-tlsv1_3. (Contributed by Christian Heimes in 32947, 20995, 29136, 30622 and 33618)
~ssl.SSLSocket and ~ssl.SSLObject no longer have a public constructor. Direct instantiation was never a documented and supported feature. Instances must be created with ~ssl.SSLContext methods ~ssl.SSLContext.wrap_socket and ~ssl.SSLContext.wrap_bio. (Contributed by Christian Heimes in 32951)
OpenSSL 1.1 APIs for setting the minimum and maximum TLS protocol version are available as SSLContext.minimum_version <ssl.SSLContext.minimum_version> and SSLContext.maximum_version <ssl.SSLContext.maximum_version>. Supported protocols are indicated by several new flags, such as ~ssl.HAS_TLSv1_1. (Contributed by Christian Heimes in 32609.)
Added 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 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 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 32102.)
The subprocess.run function and the subprocess.Popen constructor now accept the text keyword argument as an alias to universal_newlines. (Contributed by Andrew Clegg in 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. This means that close_fds now defaults to True on all supported platforms. (Contributed by Segev Finer in 19764.)
The subprocess module is now more graceful when handling KeyboardInterrupt during subprocess.call, subprocess.run, or in a ~subprocess.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 25942.)
sys
The new sys.breakpointhook hook function is called by the built-in breakpoint. (Contributed by Barry Warsaw in 31353.)
On Android, the new sys.getandroidapilevel returns the build-time Android API version. (Contributed by Victor Stinner in 28740.)
The new sys.get_coroutine_origin_tracking_depth function returns the current coroutine origin tracking depth, as set by the new sys.set_coroutine_origin_tracking_depth. asyncio has been converted to use this new API instead of the deprecated !sys.set_coroutine_wrapper. (Contributed by Nathaniel J. Smith in 32591.)
time
564 adds six new functions with nanosecond resolution to the time module:
time.clock_gettime_nstime.clock_settime_nstime.monotonic_nstime.perf_counter_nstime.process_time_nstime.time_ns
New clock identifiers have been added:
time.CLOCK_BOOTTIME(Linux): Identical totime.CLOCK_MONOTONIC, except it also includes any time that the system is suspended.time.CLOCK_PROF(FreeBSD, NetBSD and OpenBSD): High-resolution per-process CPU timer.time.CLOCK_UPTIME(FreeBSD, OpenBSD): Time whose absolute value is the time the system has been running and not suspended, providing accurate uptime measurement.
The new time.thread_time and time.thread_time_ns functions can be used to get per-thread CPU time measurements. (Contributed by Antoine Pitrou in 32025.)
The new time.pthread_getcpuclockid function returns the clock ID of the thread-specific CPU-time clock.
tkinter
The new tkinter.ttk.Spinbox class is now available. (Contributed by Alan Moore in 32585.)
tracemalloc
tracemalloc.Traceback behaves more like regular tracebacks, sorting the frames from oldest to most recent. Traceback.format() <tracemalloc.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 argument to Traceback.format(). (Contributed by Jesse Bakker in 32121.)
types
The new ~types.WrapperDescriptorType, ~types.MethodWrapperType, ~types.MethodDescriptorType, and ~types.ClassMethodDescriptorType classes are now available. (Contributed by Manuel Krebber and Guido van Rossum in 29377, and Serhiy Storchaka in 32265.)
The new types.resolve_bases function resolves MRO entries dynamically as specified by 560. (Contributed by Ivan Levkivskyi in 32717.)
unicodedata
The internal unicodedata database has been upgraded to use Unicode 11. (Contributed by Benjamin Peterson.)
unittest
The new -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 32071.)
unittest.mock
The ~unittest.mock.sentinel attributes now preserve their identity when they are copied <copy> or pickled <pickle>. (Contributed by Serhiy Storchaka in 20804.)
The new ~unittest.mock.seal function allows sealing ~unittest.mock.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 30541.)
urllib.parse
urllib.parse.quote has been updated from 2396 to 3986, adding ~ to the set of characters that are never quoted by default. (Contributed by Christian Theune and Ratnadeep Debnath in 16285.)
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 30103.)
uuid
The new UUID.is_safe <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 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 32107.)
warnings
The initialization of the default warnings filters has changed as follows:
- warnings enabled via command line options (including those for
-band the new CPython-specific-Xdevoption) are always passed to the warnings machinery via thesys.warnoptionsattribute. - warnings filters enabled via the command line or the environment now have the following order of precedence:
- the
BytesWarningfilter for-b(or-bb) - any filters specified with the
-Woption - any filters specified with the
PYTHONWARNINGSenvironment variable - any other CPython specific filters (e.g. the
defaultfilter added for the new-X devmode) - any implicit filters defined directly by the warnings machinery
- the
- in
CPython debug builds <debug-build>, all warnings are now displayed by default (the implicit filter list is empty)
(Contributed by Nick Coghlan and Victor Stinner in 20361, 32043, and 32230.)
Deprecation warnings are once again shown by default in single-file scripts and at the interactive prompt. See whatsnew37-pep565 for details. (Contributed by Nick Coghlan in 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 61441.)
xml.etree
ElementPath <elementtree-xpath> 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 31648.)
xmlrpc.server
!SimpleXMLRPCDispatcher.register_function can now be used as a decorator. (Contributed by Xiang Zhang in 7769.)
zipapp
Function ~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 31072.)
Function ~zipapp.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 31638.)
zipfile
~zipfile.ZipFile now accepts the new compresslevel parameter to control the compression level. (Contributed by Bo Bayles in 21417.)
Subdirectories in archives created by ZipFile are now stored in alphabetical order. (Contributed by Bernhard M. Wiedemann in 30693.)
C API Changes
A new API for thread-local storage has been implemented. See whatsnew37-pep539 for an overview and thread-specific-storage-api for a complete reference. (Contributed by Masayuki Yamamoto in 25658.)
The new context variables <whatsnew37-pep567> functionality exposes a number of new C APIs <contextvarsobjects>.
The new PyImport_GetModule function returns the previously imported module with the given name. (Contributed by Eric Snow in 28411.)
The new Py_RETURN_RICHCOMPARE macro eases writing rich comparison functions. (Contributed by Petr Victorin in 23699.)
The new Py_UNREACHABLE macro can be used to mark unreachable code paths. (Contributed by Barry Warsaw in 31338.)
The tracemalloc now exposes a C API through the new PyTraceMalloc_Track and PyTraceMalloc_Untrack functions. (Contributed by Victor Stinner in 30054.)
The new import__find__load__start <static-markers> and import__find__load__done <static-markers> static markers can be used to trace module imports. (Contributed by Christian Heimes in 31574.)
The fields !name and !doc of structures PyMemberDef, PyGetSetDef, PyStructSequence_Field, PyStructSequence_Desc, and !wrapperbase are now of type const char * rather of char *. (Contributed by Serhiy Storchaka in 28761.)
The result of PyUnicode_AsUTF8AndSize and PyUnicode_AsUTF8 is now of type const char * rather of char *. (Contributed by Serhiy Storchaka in 28769.)
The result of PyMapping_Keys, PyMapping_Values and PyMapping_Items is now always a list, rather than a list or a tuple. (Contributed by Oren Milman in 28280.)
Added functions PySlice_Unpack and PySlice_AdjustIndices. (Contributed by Serhiy Storchaka in 27867.)
PyOS_AfterFork is deprecated in favour of the new functions PyOS_BeforeFork, PyOS_AfterFork_Parent and PyOS_AfterFork_Child. (Contributed by Antoine Pitrou in 16500.)
The PyExc_RecursionErrorInst singleton that was part of the public API has been removed as its members being never cleared may cause a segfault during finalization of the interpreter. Contributed by Xavier de Gaye in 22898 and 30697.
Added C API support for timezones with timezone constructors PyTimeZone_FromOffset and PyTimeZone_FromOffsetAndName, and access to the UTC singleton with PyDateTime_TimeZone_UTC. Contributed by Paul Ganssle in 10381.
The type of results of !PyThread_start_new_thread and !PyThread_get_thread_ident, and the id parameter of PyThreadState_SetAsyncExc changed from long to unsigned long. (Contributed by Serhiy Storchaka in 6532.)
PyUnicode_AsWideCharString now raises a ValueError if the second argument is NULL and the wchar_t* string contains null characters. (Contributed by Serhiy Storchaka in 30708.)
Changes to the startup sequence and the management of dynamic memory allocators mean that the long documented requirement to call Py_Initialize before calling most C API functions is now relied on more heavily, and failing to abide by it may lead to segfaults in embedding applications. See the porting-to-python-37 section in this document and the pre-init-safe section in the C API documentation for more details.
The new PyInterpreterState_GetID returns the unique ID for a given interpreter. (Contributed by Eric Snow in 29102.)
Py_DecodeLocale, Py_EncodeLocale now use the UTF-8 encoding when the UTF-8 mode <whatsnew37-pep540> is enabled. (Contributed by Victor Stinner in 29240.)
PyUnicode_DecodeLocaleAndSize and PyUnicode_EncodeLocale now use the current locale encoding for surrogateescape error handler. (Contributed by Victor Stinner in 29240.)
The start and end parameters of PyUnicode_FindChar are now adjusted to behave like string slices. (Contributed by Xiang Zhang in 28822.)
Build Changes
Support for building --without-threads has been removed. The threading module is now always available. (Contributed by Antoine Pitrou in 31370.).
A full copy of libffi is no longer bundled for use when building the _ctypes <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 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 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.
Optimizations
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 29300, 29507, 29452, and 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 29585, and Ivan Levkivskyi in 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 26110.)
The asyncio module received a number of notable optimizations for commonly used functions:
- The
asyncio.get_event_loopfunction has been reimplemented in C to make it up to 15 times faster. (Contributed by Yury Selivanov in32296.) asyncio.Futurecallback management has been optimized. (Contributed by Yury Selivanov in32348.)asyncio.gatheris now up to 15% faster. (Contributed by Yury Selivanov in32355.)asyncio.sleepis now up to 2 times faster when the delay argument is zero or negative. (Contributed by Andrew Svetlov in32351.)- The performance overhead of asyncio debug mode has been reduced. (Contributed by Antoine Pitrou in
31970.)
As a result of PEP 560 work <whatsnew37-pep560>, 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 32226.)
sorted and list.sort have been optimized for common cases to be up to 40-75% faster. (Contributed by Elliot Gorokhovsky in 28685.)
dict.copy is now up to 5.5 times faster. (Contributed by Yury Selivanov in 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 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 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 28638.)
datetime.date.fromordinal and datetime.date.fromtimestamp are now up to 30% faster in the common case. (Contributed by Paul Ganssle in 32403.)
The os.fwalk function is now up to 2 times faster thanks to the use of os.scandir. (Contributed by Serhiy Storchaka in 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 28564.)
Optimized case-insensitive matching and searching of regular expressions <re>. Searching some patterns can now be up to 20 times faster. (Contributed by Serhiy Storchaka in 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 31671.)
The ~selectors.BaseSelector.modify methods of classes selectors.EpollSelector, selectors.PollSelector and selectors.DevpollSelector may be around 10% faster under heavy loads. (Contributed by Giampaolo Rodola' in 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 29469 and 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 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 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 24700.)
The math.erf and math.erfc functions now use the (faster) C library implementation on most platforms. (Contributed by Serhiy Storchaka in 26121.)
Other CPython Implementation Changes
- Trace hooks may now opt out of receiving the
lineand opt into receiving theopcodeevents from the interpreter by setting the corresponding new~frame.f_trace_linesand~frame.f_trace_opcodesattributes on the frame being traced. (Contributed by Nick Coghlan in31344.) - Fixed some consistency problems with namespace package module attributes. Namespace module objects now have an
__file__that is set toNone(previously unset), and their__spec__.originis also set toNone(previously the string"namespace"). See32305. Also, the namespace module object's__spec__.loaderis set to the same value as__loader__(previously, the former was set toNone). See32303. - The
localsdictionary now displays in the lexical order that variables were defined. Previously, the order was undefined. (Contributed by Raymond Hettinger in32690.) - The
distutilsuploadcommand 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 in32304.)
Deprecated Python Behavior
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 generator iterator object), while generator expressions won't attempt to interleave their implicit output with the output from any explicit yield expressions. In Python 3.7, such expressions emit DeprecationWarning when compiled, in Python 3.8 this will be a SyntaxError. (Contributed by Serhiy Storchaka in 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 28894.)
Deprecated Python modules, functions and methods
aifc
!aifc.openfp has been deprecated and will be removed in Python 3.9. Use !aifc.open instead. (Contributed by Brian Curtin in 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 32253.)
The !asyncio.Task.current_task and !asyncio.Task.all_tasks methods have been deprecated. (Contributed by Andrew Svetlov in 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 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 28847.)
enum
In Python 3.8, attempting to check for non-Enum objects in ~enum.Enum classes will raise a TypeError (e.g. 1 in Color); similarly, attempting to check for non-Flag objects in a ~enum.Flag member will raise TypeError (e.g. 1 in Perm.RW); currently, both operations return False instead. (Contributed by Ethan Furman in 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 28692.)
importlib
Methods !MetaPathFinder.find_module (replaced by MetaPathFinder.find_spec() <importlib.abc.MetaPathFinder.find_spec>) and !PathEntryFinder.find_loader (replaced by PathEntryFinder.find_spec() <importlib.abc.PathEntryFinder.find_spec>) both deprecated in Python 3.4 now emit DeprecationWarning. (Contributed by Matthias Bussonnier in 29576.)
The importlib.abc.ResourceLoader ABC has been deprecated in favour of !importlib.abc.ResourceReader.
locale
!locale.format has been deprecated, use locale.format_string instead. (Contributed by Garvit in 10379.)
macpath
The !macpath is now deprecated and will be removed in Python 3.8. (Contributed by Chi Hsuan Yen in 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 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 28332.)
ssl
!ssl.wrap_socket is deprecated. Use ssl.SSLContext.wrap_socket instead. (Contributed by Christian Heimes in 28124.)
sunau
!sunau.openfp has been deprecated and will be removed in Python 3.9. Use !sunau.open instead. (Contributed by Brian Curtin in 31985.)
sys
Deprecated !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 28799.)
wave
!wave.openfp has been deprecated and will be removed in Python 3.9. Use wave.open instead. (Contributed by Brian Curtin in 31985.)
Deprecated functions and types of the C API
Function PySlice_GetIndicesEx is deprecated and replaced with a macro if Py_LIMITED_API is not set or set to a value in the range between 0x03050400 and 0x03060000 (not inclusive), or is 0x03060100 or higher. (Contributed by Serhiy Storchaka in 27867.)
PyOS_AfterFork has been deprecated. Use PyOS_BeforeFork, PyOS_AfterFork_Parent or PyOS_AfterFork_Child() instead. (Contributed by Antoine Pitrou in 16500.)
Platform Support Removals
-
FreeBSD 9 and older are no longer officially supported.
-
For full Unicode support, including within extension modules, *nix platforms are now expected to provide at least one of
C.UTF-8(full locale),C.utf8(full locale) orUTF-8(LC_CTYPE-only locale) as an alternative to the legacyASCII-basedClocale. -
OpenSSL 0.9.8 and 1.0.1 are no longer supported, which means building CPython 3.7 with SSL/TLS support on older platforms still using these versions requires custom build options that link to a more recent version of OpenSSL.
Notably, this issue affects the Debian 8 (aka "jessie") and Ubuntu 14.04 (aka "Trusty") LTS Linux distributions, as they still use OpenSSL 1.0.1 by default.
Debian 9 ("stretch") and Ubuntu 16.04 ("xenial"), as well as recent releases of other LTS Linux releases (e.g. RHEL/CentOS 7.5, SLES 12-SP3), use OpenSSL 1.0.2 or later, and remain supported in the default build configuration.
CPython's own CI configuration file provides an example of using the SSL
compatibility testing infrastructure <Tools/ssl/multissltests.py>in CPython's test suite to build and link against OpenSSL 1.1.0 rather than an outdated system provided OpenSSL.
API and Feature Removals
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. - Unknown escapes consisting of
'\'and an ASCII letter in replacement templates forre.subwere deprecated in Python 3.5, and will now cause an error. - Removed support of the exclude argument in
tarfile.TarFile.add. It was deprecated in Python 2.7 and 3.2. Use the filter argument instead. - The
!ntpath.splituncfunction was deprecated in Python 3.1, and has now been removed. Use~os.path.splitdriveinstead. collections.namedtupleno longer supports the verbose parameter or_sourceattribute which showed the generated source code for the named tuple class. This was part of an optimization designed to speed-up class creation. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger in28638.)- Functions
bool,float,listandtupleno longer take keyword arguments. The first argument ofintcan now be passed only as positional argument. - Removed previously deprecated in Python 2.4 classes
Plist,Dictand_InternalDictin theplistlibmodule. Dict values in the result of functions!readPlistand!readPlistFromBytesare 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 thesocket.socketpairfunction instead, it is available on all platforms since Python 3.5.asyncio.windows_utils.socketpairwas just an alias tosocket.socketpairon Python 3.5 and newer. asynciono longer exports theselectorsand!_overlappedmodules asasyncio.selectorsandasyncio._overlapped. Replacefrom asyncio import selectorswithimport selectors.- Direct instantiation of
ssl.SSLSocketandssl.SSLObjectobjects is now prohibited. The constructors were never documented, tested, or designed as public constructors. Users were supposed to use!ssl.wrap_socketorssl.SSLContext. (Contributed by Christian Heimes in32951.) - The unused
distutilsinstall_misccommand has been removed. (Contributed by Eric N. Vander Weele in29218.)
Module Removals
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 29137.)
Windows-only Changes
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 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 30362.)
Porting to Python 3.7
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in Python Behavior
-
asyncandawaitnames are now reserved keywords. Code using these names as identifiers will now raise aSyntaxError. (Contributed by Jelle Zijlstra in30406.) -
479is enabled for all code in Python 3.7, meaning thatStopIterationexceptions raised directly or indirectly in coroutines and generators are transformed intoRuntimeErrorexceptions. (Contributed by Yury Selivanov in32670.) -
object.__aiter__methods can no longer be declared as asynchronous. (Contributed by Yury Selivanov in31709.) -
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]): passPython 3.7 now correctly raises a
SyntaxError, as a generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side, and the duplication of the parentheses can be omitted only on calls. (Contributed by Serhiy Storchaka in32012and32023.) -
When using the
-mswitch, the initial working directory is now added tosys.path, rather than an empty string (which dynamically denoted the current working directory at the time of each import). Any programs that are checking for the empty string, or otherwise relying on the previous behaviour, will need to be updated accordingly (e.g. by also checking foros.getcwd()oros.path.dirname(__main__.__file__), depending on why the code was checking for the empty string in the first place).
Changes in the Python API
-
socketserver.ThreadingMixIn.server_close <socketserver.BaseServer.server_close>now waits until all non-daemon threads complete. Set the newsocketserver.ThreadingMixIn.block_on_closeclass attribute toFalseto get the pre-3.7 behaviour. (Contributed by Victor Stinner in31233and33540.) -
socketserver.ForkingMixIn.server_close <socketserver.BaseServer.server_close>now waits until all child processes complete. Set the newsocketserver.ForkingMixIn.block_on_close <socketserver.ThreadingMixIn.block_on_close>class attribute toFalseto get the pre-3.7 behaviour. (Contributed by Victor Stinner in31151and33540.) -
The
locale.localeconvfunction now temporarily sets theLC_CTYPElocale to the value ofLC_NUMERICin some cases. (Contributed by Victor Stinner in31900.) -
pkgutil.walk_packagesnow raises aValueErrorif path is a string. Previously an empty list was returned. (Contributed by Sanyam Khurana in24744.) -
A format string argument for
string.Formatter.formatis nowpositional-only <positional-only_parameter>. Passing it as a keyword argument was deprecated in Python 3.5. (Contributed by Serhiy Storchaka in29193.) -
Attributes
~http.cookies.Morsel.key,~http.cookies.Morsel.valueand~http.cookies.Morsel.coded_valueof classhttp.cookies.Morselare now read-only. Assigning to them was deprecated in Python 3.5. Use the~http.cookies.Morsel.setmethod for setting them. (Contributed by Serhiy Storchaka in29192.) -
The mode argument of
os.makedirsno longer affects the file permission bits of newly created intermediate-level directories. To set their file permission bits you can set the umask before invokingmakedirs(). (Contributed by Serhiy Storchaka in19930.) -
The
struct.Struct.formattype is nowstrinstead ofbytes. (Contributed by Victor Stinner in21071.) -
!cgi.parse_multipartnow accepts the encoding and errors arguments and returns the same results as!FieldStorage: for non-file fields, the value associated to a key is a list of strings, not bytes. (Contributed by Pierre Quentel in29979.) -
Due to internal changes in
socket, callingsocket.fromshareon a socket created bysocket.share <socket.socket.share>in older Python versions is not supported. -
reprforBaseExceptionhas changed to not include the trailing comma. Most exceptions are affected by this change. (Contributed by Serhiy Storchaka in30399.) -
reprfordatetime.timedeltahas changed to include the keyword arguments in the output. (Contributed by Utkarsh Upadhyay in30302.) -
Because
shutil.rmtreeis now implemented using theos.scandirfunction, the user specified handler onerror is now called with the first argumentos.scandirinstead ofos.listdirwhen listing the directory is failed. -
Support for nested sets and set operations in regular expressions as in Unicode Technical Standard #18 might be added in the future. This would change the syntax. To facilitate this future change a
FutureWarningwill be raised in ambiguous cases for the time being. That include sets starting with a literal'['or containing literal character sequences'--','&&','~~', and'||'. To avoid a warning, escape them with a backslash. (Contributed by Serhiy Storchaka in30349.) -
The result of splitting a string on a
regular expression <re>that could match an empty string has been changed. For example splitting onr'\s*'will now split not only on whitespaces as it did previously, but also on empty strings before all non-whitespace characters and just before the end of the string. The previous behavior can be restored by changing the pattern tor'\s+'. AFutureWarningwas emitted for such patterns since Python 3.5.For patterns that match both empty and non-empty strings, the result of searching for all matches may also be changed in other cases. For example in the string
'a\n\n', the patternr'(?m)^\s*?$'will not only match empty strings at positions 2 and 3, but also the string'\n'at positions 2--3. To match only blank lines, the pattern should be rewritten asr'(?m)^[^\S\n]*$'.re.subnow replaces empty matches adjacent to a previous non-empty match. For examplere.sub('x*', '-', 'abxd')returns now'-a-b--d-'instead of'-a-b-d-'(the first minus between 'b' and 'd' replaces 'x', and the second minus replaces an empty string between 'x' and 'd').(Contributed by Serhiy Storchaka in
25054and32308.) -
Change
re.escapeto only escape regex special characters instead of escaping all characters other than ASCII letters, numbers, and'_'. (Contributed by Serhiy Storchaka in29995.) -
tracemalloc.Tracebackframes are now sorted from oldest to most recent to be more consistent withtraceback. (Contributed by Jesse Bakker in32121.) -
On OSes that support
socket.SOCK_NONBLOCKorsocket.SOCK_CLOEXECbit flags, thesocket.type <socket.socket.type>no longer has them applied. Therefore, checks likeif sock.type == socket.SOCK_STREAMwork as expected on all platforms. (Contributed by Yury Selivanov in32331.) -
On Windows the default for the close_fds argument of
subprocess.Popenwas changed fromFalsetoTruewhen redirecting the standard handles. If you previously depended on handles being inherited when usingsubprocess.Popenwith standard io redirection, you will have to passclose_fds=Falseto preserve the previous behaviour, or useSTARTUPINFO.lpAttributeList <subprocess.STARTUPINFO.lpAttributeList>. -
importlib.machinery.PathFinder.invalidate_caches-- which implicitly affectsimportlib.invalidate_caches-- now deletes entries insys.path_importer_cachewhich are set toNone. (Contributed by Brett Cannon in33169.) -
In
asyncio,loop.sock_recv() <asyncio.loop.sock_recv>,loop.sock_sendall() <asyncio.loop.sock_sendall>,loop.sock_accept() <asyncio.loop.sock_accept>,loop.getaddrinfo() <asyncio.loop.getaddrinfo>,loop.getnameinfo() <asyncio.loop.getnameinfo>have been changed to be proper coroutine methods to match their documentation. Previously, these methods returnedasyncio.Futureinstances. (Contributed by Yury Selivanov in32327.) -
asyncio.Server.socketsnow returns a copy of the internal list of server sockets, instead of returning it directly. (Contributed by Yury Selivanov in32662.) -
Struct.format <struct.Struct.format>is now astrinstance instead of abytesinstance. (Contributed by Victor Stinner in21071.) -
argparsesubparsers can now be made mandatory by passingrequired=TruetoArgumentParser.add_subparsers() <argparse.ArgumentParser.add_subparsers>. (Contributed by Anthony Sottile in26510.) -
ast.literal_evalis now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. (Contributed by Serhiy Storchaka in31778.) -
Calendar.itermonthdates <calendar.Calendar.itermonthdates>will now consistently raise an exception when a date falls outside of the0001-01-01through9999-12-31range. To support applications that cannot tolerate such exceptions, the newCalendar.itermonthdays3 <calendar.Calendar.itermonthdays3>andCalendar.itermonthdays4 <calendar.Calendar.itermonthdays4>can be used. The new methods return tuples and are not restricted by the range supported bydatetime.date. (Contributed by Alexander Belopolsky in28292.) -
collections.ChainMapnow preserves the order of the underlying mappings. (Contributed by Raymond Hettinger in32792.) -
The
submit()method ofconcurrent.futures.ThreadPoolExecutorandconcurrent.futures.ProcessPoolExecutornow raises aRuntimeErrorif called during interpreter shutdown. (Contributed by Mark Nemec in33097.) -
The
configparser.ConfigParserconstructor now usesread_dict()to process the default values, making its behavior consistent with the rest of the parser. Non-string keys and values in the defaults dictionary are now being implicitly converted to strings. (Contributed by James Tocknell in23835.) -
Several undocumented internal imports were removed. One example is that
os.errnois no longer available; useimport errnodirectly instead. Note that such undocumented internal imports may be removed any time without notice, even in micro version releases.
Changes in the C API
The function PySlice_GetIndicesEx is considered unsafe for resizable sequences. If the slice indices are not instances of int, but objects that implement the !__index__ method, the sequence can be resized after passing its length to !PySlice_GetIndicesEx. This can lead to returning indices out of the length of the sequence. For avoiding possible problems use new functions PySlice_Unpack and PySlice_AdjustIndices. (Contributed by Serhiy Storchaka in 27867.)
CPython bytecode changes
There are two new opcodes: !LOAD_METHOD and !CALL_METHOD. (Contributed by Yury Selivanov and INADA Naoki in 26110.)
The !STORE_ANNOTATION opcode has been removed. (Contributed by Mark Shannon in 32550.)
Windows-only Changes
The file used to override sys.path is now called <python-executable>._pth instead of 'sys.path'. See windows_finding_modules for more information. (Contributed by Steve Dower in 28137.)
Other CPython implementation changes
In preparation for potential future changes to the public CPython runtime initialization API (see 432 for an initial, but somewhat outdated, draft), CPython's internal startup and configuration management logic has been significantly refactored. While these updates are intended to be entirely transparent to both embedding applications and users of the regular CPython CLI, they're being mentioned here as the refactoring changes the internal order of various operations during interpreter startup, and hence may uncover previously latent defects, either in embedding applications, or in CPython itself. (Initially contributed by Nick Coghlan and Eric Snow as part of 22257, and further updated by Nick, Eric, and Victor Stinner in a number of other issues). Some known details affected:
!PySys_AddWarnOptionUnicodeis not currently usable by embedding applications due to the requirement to create a Unicode object prior to callingPy_Initialize. Use!PySys_AddWarnOptioninstead.- warnings filters added by an embedding application with
!PySys_AddWarnOptionshould now more consistently take precedence over the default filters set by the interpreter
Due to changes in the way the default warnings filters are configured, setting !Py_BytesWarningFlag to a value greater than one is no longer sufficient to both emit BytesWarning messages and have them converted to exceptions. Instead, the flag must be set (to cause the warnings to be emitted in the first place), and an explicit error::BytesWarning warnings filter added to convert them to exceptions.
Due to a change in the way docstrings are handled by the compiler, the implicit return None in a function body consisting solely of a docstring is now marked as occurring on the same line as the docstring, not on the function's header line.
The current exception state has been moved from the frame object to the co-routine. This simplified the interpreter and fixed a couple of obscure bugs caused by having swap exception state when entering or exiting a generator. (Contributed by Mark Shannon in 25612.)
Notable changes in Python 3.7.1
Starting in 3.7.1, Py_Initialize now consistently reads and respects all of the same environment settings as Py_Main (in earlier Python versions, it respected an ill-defined subset of those environment variables, while in Python 3.7.0 it didn't read any of them due to 34247). If this behavior is unwanted, set !Py_IgnoreEnvironmentFlag to 1 before calling Py_Initialize.
In 3.7.1 the C API for Context Variables was updated <contextvarsobjects_pointertype_change> to use PyObject pointers. See also 34762.
In 3.7.1 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 33899.)
Notable changes in Python 3.7.2
In 3.7.2, venv on Windows no longer copies the original binaries, but creates redirector scripts named python.exe and pythonw.exe instead. This resolves a long standing issue where all virtual environments would have to be upgraded or recreated with each Python update. However, note that this release will still require recreation of virtual environments in order to get the new scripts.
Notable changes in Python 3.7.6
Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in 37228.)
Notable changes in Python 3.7.10
Earlier Python versions allowed using both ; and & as query parameter separators in urllib.parse.parse_qs and urllib.parse.parse_qsl. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects !cgi.parse and !cgi.parse_multipart as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in 42967.)
Notable changes in Python 3.7.11
A security fix alters the ftplib.FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel. We reuse the ftp server IP address instead. For unusual code requiring the old behavior, set a trust_server_pasv_ipv4_address attribute on your FTP instance to True. (See 87451)
The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates RFC 3986, ASCII newline \n, \r and tab \t characters are stripped from the URL by the parser urllib.parse preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (See 88048)
Notable security feature in 3.7.14
Converting between int and str in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for 2020-10735. This limit can be configured or disabled by environment variable, command line flag, or sys APIs. See the integer string conversion length limitation <int_max_str_digits> documentation. The default limit is 4300 digits in string form.
What's New In Python 3.8
* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Git log when researching a change.
Editor
Raymond Hettinger
This article explains the new features in Python 3.8, compared to 3.7. Python 3.8 was released on October 14, 2019. For full details, see the changelog <changelog>.
from math import cos, radians from unicodedata import normalize import re import math
Summary -- Release highlights
New Features
Assignment expressions
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as "the walrus operator" due to its resemblance to the eyes and tusks of a walrus.
In this example, the assignment expression helps avoid calling len twice:
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
A similar benefit arises during regular expression matching where match objects are needed twice, once to test whether a match occurred and another to extract a subgroup:
discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
discount = float(mo.group(1)) / 100.0
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:
# Loop over fixed length blocks
while (block := f.read(256)) != '':
process(block)
Another motivating use case arises in list comprehensions where a value computed in a filtering condition is also needed in the expression body:
[clean_name.title() for name in names
if (clean_name := normalize('NFC', name)) in allowed_names]
Try to limit use of the walrus operator to clean cases that reduce complexity and improve readability.
See 572 for a full description.
(Contributed by Emily Morehouse in 35224.)
Positional-only parameters
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 tool.
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 module:
class Counter(dict):
def __init__(self, iterable=None, /, **kwds):
# Note "iterable" is a possible keyword argument
See 570 for a full description.
(Contributed by Pablo Galindo in 36540.)
Parallel filesystem cache for compiled bytecode files
The new PYTHONPYCACHEPREFIX setting (also available as -X pycache_prefix) configures the implicit bytecode cache to use a separate parallel filesystem tree, rather than the default __pycache__ subdirectories within each source directory.
The location of the cache is reported in sys.pycache_prefix (None indicates the default location in __pycache__ subdirectories).
(Contributed by Carl Meyer in 33499.)
Debug build uses the same ABI as release build
The ABI of Python debug builds <debug-build> is now compatible with Python release builds. On Unix, when Python is built in debug mode, it is now possible to load C extensions built in release mode and C extensions built using the stable ABI. The inverse is not true, as debug builds expose additional symbols not available in release builds.
Defining the Py_DEBUG macro no longer implies the Py_TRACE_REFS macro, which introduces the only ABI incompatibility. The Py_TRACE_REFS macro, which adds the sys.getobjects function and the PYTHONDUMPREFS environment variable, can be set using the new ./configure --with-trace-refs <--with-trace-refs> build option. (Contributed by Victor Stinner in 36465.)
On Unix, C extensions are no longer linked to libpython except on Android and Cygwin. It is now possible for a statically linked Python to load a C extension built using a shared library Python. (Contributed by Victor Stinner in 21536.)
On Unix, when Python is built in debug mode, import now also looks for C extensions compiled in release mode and for C extensions compiled with the stable ABI. (Contributed by Victor Stinner in 36722.)
To embed Python into an application, a new --embed option must be passed to python3-config --libs --embed to get -lpython3.8 (link the application to libpython). To support both 3.8 and older, try python3-config --libs --embed first and fallback to python3-config --libs (without --embed) if the previous command fails.
Add a pkg-config python-3.8-embed module to embed Python into an application: pkg-config python-3.8-embed --libs includes -lpython3.8. To support both 3.8 and older, try pkg-config python-X.Y-embed --libs first and fallback to pkg-config python-X.Y --libs (without --embed) if the previous command fails (replace X.Y with the Python version).
On the other hand, pkg-config python3.8 --libs no longer contains -lpython3.8. C extensions must not be linked to libpython (except on Android and Cygwin, whose cases are handled by the script); this change is backward incompatible on purpose. (Contributed by Victor Stinner in 36721.)
f-strings support = for self-documenting expressions and debugging
Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression. For example:
>>> import datetime as dt >>> user = 'eric_idle' >>> member_since = dt.date(1975, 7, 31) >>> f'{user=} {member_since=}' "user='eric_idle' member_since=datetime.date(1975, 7, 31)"
The usual f-string format specifiers <f-strings> allow more control over how the result of the expression is displayed:
>>> delta = dt.date.today() - member_since
>>> f'{user=!s} {delta.days=:,d}'
'user=eric_idle delta.days=16,075'
The = specifier will display the whole expression so that calculations can be shown:
>>> print(f'{theta=} {cos(radians(theta))=:.3f}')
theta=30 cos(radians(theta))=0.866
(Contributed by Eric V. Smith and Larry Hastings in 36817.)
PEP 578: Python Runtime Audit Hooks
The PEP adds an Audit Hook and Verified Open Hook. Both are available from Python and native code, allowing applications and frameworks written in pure Python code to take advantage of extra notifications, while also allowing embedders or system administrators to deploy builds of Python where auditing is always enabled.
See 578 for full details.
PEP 587: Python Initialization Configuration
The 587 adds a new C API to configure the Python Initialization providing finer control on the whole configuration and better error reporting.
New structures:
PyConfigPyPreConfigPyStatusPyWideStringList
New functions:
PyConfig_ClearPyConfig_InitIsolatedConfigPyConfig_InitPythonConfigPyConfig_ReadPyConfig_SetArgvPyConfig_SetBytesArgvPyConfig_SetBytesStringPyConfig_SetStringPyPreConfig_InitIsolatedConfigPyPreConfig_InitPythonConfigPyStatus_ErrorPyStatus_ExceptionPyStatus_ExitPyStatus_IsErrorPyStatus_IsExitPyStatus_NoMemoryPyStatus_OkPyWideStringList_AppendPyWideStringList_InsertPy_BytesMainPy_ExitStatusExceptionPy_InitializeFromConfigPy_PreInitializePy_PreInitializeFromArgsPy_PreInitializeFromBytesArgsPy_RunMain
This PEP also adds _PyRuntimeState.preconfig (PyPreConfig type) and PyInterpreterState.config (PyConfig type) fields to these internal structures. PyInterpreterState.config becomes the new reference configuration, replacing global configuration variables and other private variables.
See Python Initialization Configuration <init-config> for the documentation.
See 587 for a full description.
(Contributed by Victor Stinner in 36763.)
PEP 590: Vectorcall: a fast calling protocol for CPython
vectorcall is added to the Python/C API. It is meant to formalize existing optimizations which were already done for various classes. Any static type <static-types> implementing a callable can use this protocol.
This is currently provisional. The aim is to make it fully public in Python 3.9.
See 590 for a full description.
(Contributed by Jeroen Demeyer, Mark Shannon and Petr Viktorin in 36974.)
Pickle protocol 5 with out-of-band data buffers
When pickle is used to transfer large data between Python processes in order to take advantage of multi-core or multi-machine processing, it is important to optimize the transfer by reducing memory copies, and possibly by applying custom techniques such as data-dependent compression.
The pickle protocol 5 introduces support for out-of-band buffers where 3118-compatible data can be transmitted separately from the main pickle stream, at the discretion of the communication layer.
See 574 for a full description.
(Contributed by Antoine Pitrou in 36785.)
Other Language Changes
-
A
continuestatement was illegal in thefinallyclause due to a problem with the implementation. In Python 3.8 this restriction was lifted. (Contributed by Serhiy Storchaka in32489.) -
The
bool,int, andfractions.Fractiontypes now have an~int.as_integer_ratiomethod like that found infloatanddecimal.Decimal. This minor API extension makes it possible to writenumerator, denominator = x.as_integer_ratio()and have it work across multiple numeric types. (Contributed by Lisa Roach in33073and Raymond Hettinger in37819.) -
Constructors of
int,floatandcomplexwill now use the~object.__index__special method, if available and the corresponding method~object.__int__,~object.__float__or~object.__complex__is not available. (Contributed by Serhiy Storchaka in20092.) -
Added support of
\\N\\{{name}\\}escapes inregular expressions <re>:>>> notice = 'Copyright © 2019' >>> copyright_year_pattern = re.compile(r'\N{copyright sign}\s*(\d{4})') >>> int(copyright_year_pattern.search(notice).group(1)) 2019(Contributed by Jonathan Eunice and Serhiy Storchaka in
30688.) -
Dict and dictviews are now iterable in reversed insertion order using
reversed. (Contributed by Rémi Lapeyre in33462.) -
The syntax allowed for keyword names in function calls was further restricted. In particular,
f((keyword)=arg)is no longer allowed. It was never intended to permit more than a bare name on the left-hand side of a keyword argument assignment term. (Contributed by Benjamin Peterson in34641.) -
Generalized iterable unpacking in
yieldandreturnstatements no longer requires enclosing parentheses. This brings the yield and return syntax into better agreement with normal assignment syntax:>>> def parse(family): ... lastname, *members = family.split() ... return lastname.upper(), *members ... >>> parse('simpsons homer marge bart lisa maggie') ('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')(Contributed by David Cuthbert and Jordan Chapman in
32117.) -
When a comma is missed in code such as
[(10, 20) (30, 40)], the compiler displays aSyntaxWarningwith a helpful suggestion. This improves on just having aTypeErrorindicating that the first tuple was not callable. (Contributed by Serhiy Storchaka in15248.) -
Arithmetic operations between subclasses of
datetime.dateordatetime.datetimeanddatetime.timedeltaobjects now return an instance of the subclass, rather than the base class. This also affects the return type of operations whose implementation (directly or indirectly) usesdatetime.timedeltaarithmetic, such as~datetime.datetime.astimezone. (Contributed by Paul Ganssle in32417.) -
When the Python interpreter is interrupted by Ctrl-C (SIGINT) and the resulting
KeyboardInterruptexception is not caught, the Python process now exits via a SIGINT signal or with the correct exit code such that the calling process can detect that it died due to a Ctrl-C. Shells on POSIX and Windows use this to properly terminate scripts in interactive sessions. (Contributed by Google via Gregory P. Smith in1054041.) -
Some advanced styles of programming require updating the
types.CodeTypeobject for an existing function. Since code objects are immutable, a new code object needs to be created, one that is modeled on the existing code object. With 19 parameters, this was somewhat tedious. Now, the newreplace()method makes it possible to create a clone with a few altered parameters.Here's an example that alters the
statistics.meanfunction to prevent the data parameter from being used as a keyword argument:>>> from statistics import mean >>> mean(data=[10, 20, 90]) 40 >>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1) >>> mean(data=[10, 20, 90]) Traceback (most recent call last): ... TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'(Contributed by Victor Stinner in
37032.) -
For integers, the three-argument form of the
powfunction now permits the exponent to be negative in the case where the base is relatively prime to the modulus. It then computes a modular inverse to the base when the exponent is-1, and a suitable power of that inverse for other negative exponents. For example, to compute the modular multiplicative inverse of 38 modulo 137, write:>>> pow(38, -1, 137) 119 >>> 119 * 38 % 137 1Modular inverses arise in the solution of linear Diophantine equations. For example, to find integer solutions for
4258𝑥 + 147𝑦 = 369, first rewrite as4258𝑥 ≡ 369 (mod 147)then solve:>>> x = 369 * pow(4258, -1, 147) % 147 >>> y = (4258 * x - 369) // -147 >>> 4258 * x + 147 * y 369
(Contributed by Mark Dickinson in
36027.) -
Dict comprehensions have been synced-up with dict literals so that the key is computed first and the value second:
>>> # Dict comprehension >>> cast = {input('role? '): input('actor? ') for i in range(2)} role? King Arthur actor? Chapman role? Black Knight actor? Cleese >>> # Dict literal >>> cast = {input('role? '): input('actor? ')} role? Sir Robin actor? Eric IdleThe guaranteed execution order is helpful with assignment expressions because variables assigned in the key expression will be available in the value expression:
>>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald'] >>> {(n := normalize('NFC', name)).casefold() : n for name in names} {'martin von löwis': 'Martin von Löwis', 'łukasz langa': 'Łukasz Langa', 'walter dörwald': 'Walter Dörwald'}(Contributed by Jörn Heissler in
35224.) -
The
object.__reduce__method can now return a tuple from two to six elements long. Formerly, five was the limit. The new, optional sixth element is a callable with a(obj, state)signature. This allows the direct control over the state-updating behavior of a specific object. If not None, this callable will have priority over the object's~object.__setstate__method. (Contributed by Pierre Glaser and Olivier Grisel in35900.)
New Modules
-
The new
importlib.metadatamodule provides (provisional) support for reading metadata from third-party packages. For example, it can extract an installed package's version number, list of entry points, and more:>>> # Note following example requires that the popular "requests" >>> # package has been installed. >>> >>> from importlib.metadata import version, requires, files >>> version('requests') '2.22.0' >>> list(requires('requests')) ['chardet (<3.1.0,>=3.0.2)'] >>> list(files('requests'))[:5] [PackagePath('requests-2.22.0.dist-info/INSTALLER'), PackagePath('requests-2.22.0.dist-info/LICENSE'), PackagePath('requests-2.22.0.dist-info/METADATA'), PackagePath('requests-2.22.0.dist-info/RECORD'), PackagePath('requests-2.22.0.dist-info/WHEEL')](Contributed by Barry Warsaw and Jason R. Coombs in
34632.)
Improved Modules
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 33416.)
The ast.parse function has some new flags:
type_comments=Truecauses it to return the text of484and526type comments associated with certain AST nodes;mode='func_type'can be used to parse484"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 treatasyncandawaitas non-reserved words.
(Contributed by Guido van Rossum in 35766.)
asyncio
asyncio.run has graduated from the provisional to stable API. This function can be used to execute a coroutine 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())
This is 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 32314.)
Running 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 37028.)
The exception asyncio.CancelledError now inherits from BaseException rather than Exception and no longer inherits from concurrent.futures.CancelledError. (Contributed by Yury Selivanov in 32528.)
On Windows, the default event loop is now ~asyncio.ProactorEventLoop. (Contributed by Victor Stinner in 34687.)
~asyncio.ProactorEventLoop now also supports UDP. (Contributed by Adam Meily and Andrew Svetlov in 29883.)
~asyncio.ProactorEventLoop can now be interrupted by KeyboardInterrupt ("CTRL+C"). (Contributed by Vladimir Matveev in 23057.)
Added asyncio.Task.get_coro for getting the wrapped coroutine within an asyncio.Task. (Contributed by Alex Grönholm in 36999.)
Asyncio tasks can now be named, either by passing the name keyword argument to asyncio.create_task or the ~asyncio.loop.create_task event loop method, or by calling the ~asyncio.Task.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 ~asyncio.Task.get_name method. (Contributed by Alex Grönholm in 34270.)
Added support for 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 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 34616)
collections
The ~collections.somenamedtuple._asdict method for collections.namedtuple now returns a dict instead of a collections.OrderedDict. This works because regular dicts have guaranteed ordering since Python 3.7. If the extra features of OrderedDict are required, the suggested remediation is to cast the result to the desired type: OrderedDict(nt._asdict()). (Contributed by Raymond Hettinger in 35864.)
cProfile
The cProfile.Profile <profile.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 29235.)
csv
The csv.DictReader now returns instances of dict instead of a collections.OrderedDict. The tool is now faster and uses less memory while still preserving the field order. (Contributed by Michael Selik in 34003.)
curses
Added a new variable holding structured version information for the underlying ncurses library: ~curses.ncurses_version. (Contributed by Serhiy Storchaka in 31680.)
ctypes
On Windows, ~ctypes.CDLL and subclasses now accept a winmode parameter to specify flags for the underlying LoadLibraryEx call. The default flags are set to only load DLL dependencies from trusted locations, including the path where the DLL is stored (if a full or partial path is used to load the initial DLL) and paths added by ~os.add_dll_directory. (Contributed by Steve Dower in 36085.)
datetime
Added new alternate constructors datetime.date.fromisocalendar and datetime.datetime.fromisocalendar, which construct ~datetime.date and ~datetime.datetime objects respectively from ISO year, week number, and weekday; these are the inverse of each class's isocalendar method. (Contributed by Paul Ganssle in 36004.)
functools
functools.lru_cache can now be used as a straight decorator rather than as a function returning a decorator. So both of these are now supported:
@lru_cache
def f(x):
...
@lru_cache(maxsize=256)
def f(x):
...
(Contributed by Raymond Hettinger in 36772.)
Added a new functools.cached_property decorator, for computed properties cached for the life of the instance. :
import functools
import statistics
class Dataset:
def __init__(self, sequence_of_numbers):
self.data = sequence_of_numbers
@functools.cached_property
def variance(self):
return statistics.variance(self.data)
(Contributed by Carl Meyer in 21145)
Added a new functools.singledispatchmethod decorator that converts methods into generic functions <generic function> using single dispatch:
from functools import singledispatchmethod
from contextlib import suppress
class TaskManager:
def __init__(self, tasks):
self.tasks = list(tasks)
@singledispatchmethod
def discard(self, value):
with suppress(ValueError):
self.tasks.remove(value)
@discard.register(list)
def _(self, tasks):
targets = set(tasks)
self.tasks = [x for x in self.tasks if x not in targets]
(Contributed by Ethan Smith in 32380)
gc
~gc.get_objects can now receive an optional generation parameter indicating a generation to get objects from. (Contributed by Pablo Galindo in 36016.)
gettext
Added ~gettext.pgettext and its variants. (Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in 2504.)
gzip
Added the mtime parameter to gzip.compress for reproducible output. (Contributed by Guo Ci Teo in 34898.)
A ~gzip.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 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 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 5680 and 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 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 13153.)
New in 3.8.1:
Add option to toggle cursor blink off. (Contributed by Zackery Spytz in 4603.)
Escape key now closes IDLE completion windows. (Contributed by Johnny Najera in 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 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, and 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 36326.)
io
In development mode (-X env) and in debug build <debug-build>, the 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 18748.)
itertools
The itertools.accumulate function added an option initial keyword argument to specify an initial value:
>>> from itertools import accumulate
>>> list(accumulate([10, 5, 30, 15], initial=1000))
[1000, 1010, 1015, 1045, 1060]
(Contributed by Lisa Roach in 34659.)
json.tool
Add option --json-lines to parse every input line as a separate JSON object. (Contributed by Weipeng Hong in 31553.)
logging
Added a 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 33897.)
math
Added new function math.dist for computing Euclidean distance between two points. (Contributed by Raymond Hettinger in 33089.)
Expanded the math.hypot function to handle multiple dimensions. Formerly, it only supported the 2-D case. (Contributed by Raymond Hettinger in 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 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 37128, 37178, and 35431.)
Added a new function 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 36887.)
The function math.factorial no longer accepts arguments that are not int-like. (Contributed by Pablo Galindo in 33083.)
mmap
The mmap.mmap class now has an ~mmap.mmap.madvise method to access the madvise() system call. (Contributed by Zackery Spytz in 32941.)
multiprocessing
Added new multiprocessing.shared_memory module. (Contributed by Davin Potts in 35813.)
On macOS, the spawn start method is now used by default. (Contributed by Victor Stinner in 33725.)
os
Added new function ~os.add_dll_directory on Windows for providing additional search paths for native dependencies when importing extension modules or loading DLLs using ctypes. (Contributed by Steve Dower in 36085.)
A new os.memfd_create function was added to wrap the memfd_create() syscall. (Contributed by Zackery Spytz and Christian Heimes in 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, os.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 os.stat_result.st_reparse_tag attribute.
On Windows, os.readlink is now able to read directory junctions. Note that ~os.path.islink will return 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 37834.)
os.path
os.path functions that return a boolean result like ~os.path.exists, ~os.path.lexists, ~os.path.isdir, ~os.path.isfile, ~os.path.islink, and ~os.path.ismount now return False instead of raising ValueError or its subclasses UnicodeEncodeError and UnicodeDecodeError for paths that contain characters or bytes unrepresentable at the OS level. (Contributed by Serhiy Storchaka in 33721.)
~os.path.expanduser on Windows now prefers the USERPROFILE environment variable and does not use HOME, which is not normally set for regular user accounts. (Contributed by Anthony Sottile in 36264.)
~os.path.isdir on Windows no longer returns True for a link to a non-existent directory.
~os.path.realpath on Windows now resolves reparse points, including symlinks and directory junctions.
(Contributed by Steve Dower in 37834.)
pathlib
pathlib.Path methods that return a boolean result like ~pathlib.Path.exists, ~pathlib.Path.is_dir, ~pathlib.Path.is_file, ~pathlib.Path.is_mount, ~pathlib.Path.is_symlink, ~pathlib.Path.is_block_device, ~pathlib.Path.is_char_device, ~pathlib.Path.is_fifo, ~pathlib.Path.is_socket now return False instead of raising ValueError or its subclass UnicodeEncodeError for paths that contain characters unrepresentable at the OS level. (Contributed by Serhiy Storchaka in 33721.)
Added !pathlib.Path.link_to which creates a hard link pointing to a path. (Contributed by Joannah Nanjekye in 26978) Note that link_to was deprecated in 3.10 and removed in 3.12 in favor of a hardlink_to method added in 3.10 which matches the semantics of the existing symlink_to method.
pickle
pickle extensions subclassing the C-optimized ~pickle.Pickler can now override the pickling logic of functions and classes by defining the special ~pickle.Pickler.reducer_override method. (Contributed by Pierre Glaser and Olivier Grisel in 35900.)
plistlib
Added new plistlib.UID and enabled support for reading and writing NSKeyedArchiver-encoded binary plists. (Contributed by Jon Janzen in 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 30670.)
py_compile
py_compile.compile now supports silent mode. (Contributed by Joannah Nanjekye in 22640.)
shlex
The new shlex.join function acts as the inverse of shlex.split. (Contributed by Bo Bayles in 32102.)
shutil
shutil.copytree now accepts a new dirs_exist_ok keyword argument. (Contributed by Josh Bronson in 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 30661.)
shutil.rmtree on Windows now removes directory junctions without recursively removing their contents first. (Contributed by Steve Dower in 37834.)
socket
Added ~socket.create_server and ~socket.has_dualstack_ipv6 convenience functions to automate the necessary tasks usually involved when creating a server socket, including accepting both IPv4 and IPv6 connections on the same socket. (Contributed by Giampaolo Rodolà in 17561.)
The socket.if_nameindex, socket.if_nametoindex, and socket.if_indextoname functions have been implemented on Windows. (Contributed by Zackery Spytz in 37007.)
ssl
Added ~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 34670.)
statistics
Added statistics.fmean as a faster, floating-point variant of statistics.mean. (Contributed by Raymond Hettinger and Steven D'Aprano in 35904.)
Added statistics.geometric_mean (Contributed by Raymond Hettinger in 27181.)
Added statistics.multimode that returns a list of the most common values. (Contributed by Raymond Hettinger in 35892.)
Added statistics.quantiles that divides data or a distribution in to equiprobable intervals (e.g. quartiles, deciles, or percentiles). (Contributed by Raymond Hettinger in 36546.)
Added statistics.NormalDist, a tool for creating and manipulating normal distributions of a random variable. (Contributed by Raymond Hettinger in 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 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 36268.)
threading
Add a new threading.excepthook function which handles uncaught threading.Thread.run exception. It can be overridden to control how uncaught threading.Thread.run exceptions are handled. (Contributed by Victor Stinner in 1230540.)
Add a new threading.get_native_id function and a ~threading.Thread.native_id attribute to the threading.Thread class. These return the native integral Thread ID of the current thread assigned by the kernel. This feature is only available on certain platforms, see get_native_id <threading.get_native_id> for more information. (Contributed by Jake Tesler in 36084.)
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 33899.)
tkinter
Added methods !selection_from, !selection_present, !selection_range and !selection_to in the !tkinter.Spinbox class. (Contributed by Juliette Monsel in 34829.)
Added method !moveto in the !tkinter.Canvas class. (Contributed by Juliette Monsel in 23831.)
The !tkinter.PhotoImage class now has !transparency_get and !transparency_set methods. (Contributed by Zackery Spytz in 25451.)
time
Added new clock ~time.CLOCK_UPTIME_RAW for macOS 10.12. (Contributed by Joannah Nanjekye in 35702.)
typing
The typing module incorporates several new features:
-
A dictionary type with per-key types. See
589andtyping.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
586andtyping.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
591,typing.Finalandtyping.final. The final qualifier instructs a static type checker to restrict subclassing, overriding, or reassignment:pi: Final[float] = 3.1415926536 -
Protocol definitions. See
544,typing.Protocolandtyping.runtime_checkable. Simple ABCs liketyping.SupportsIntare nowProtocolsubclasses. -
New protocol class
typing.SupportsIndex. -
New functions
typing.get_originandtyping.get_args.
unicodedata
The unicodedata module has been upgraded to use the Unicode 12.1.0 release.
New function ~unicodedata.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 32285 and 37966).
unittest
Added ~unittest.mock.AsyncMock to support an asynchronous version of ~unittest.mock.Mock. Appropriate new assert functions for testing have been added as well. (Contributed by Lisa Roach in 26467).
Added ~unittest.addModuleCleanup and ~unittest.TestCase.addClassCleanup to unittest to support cleanups for ~unittest.setUpModule and ~unittest.TestCase.setUpClass. (Contributed by Lisa Roach in 24412.)
Several mock assert functions now also print a list of actual calls upon failure. (Contributed by Petter Strandmark in 35047.)
unittest module gained support for coroutines to be used as test cases with unittest.IsolatedAsyncioTestCase. (Contributed by Andrew Svetlov in 32972.)
Example:
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 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 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 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 28238.)
The xml.etree.ElementTree module provides a new function ~xml.etree.ElementTree.canonicalize that implements C14N 2.0. (Contributed by Stefan Behnel in 13611.)
The target object of xml.etree.ElementTree.XMLParser can receive namespace declaration events through the new callback methods start_ns() and end_ns(). Additionally, the 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 36676 and 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 35153.)
Optimizations
-
The
subprocessmodule can now use theos.posix_spawnfunction in some cases for better performance. Currently, it is only used on macOS and Linux (using glibc 2.24 or newer) if all these conditions are met:- close_fds is false;
- preexec_fn, pass_fds, cwd and start_new_session parameters are not set;
- the executable path contains a directory.
(Contributed by Joannah Nanjekye and Victor Stinner in
35537.) -
shutil.copyfile,shutil.copy,shutil.copy2,shutil.copytreeandshutil.moveuse platform-specific "fast-copy" syscalls on Linux and macOS in order to copy the file more efficiently. "fast-copy" means that the copying operation occurs within the kernel, avoiding the use of userspace buffers in Python as in "outfd.write(infd.read())". On Windowsshutil.copyfileuses a bigger default buffer size (1 MiB instead of 16 KiB) and amemoryview-based variant ofshutil.copyfileobjis used. The speedup for copying a 512 MiB file within the same partition is about +26% on Linux, +50% on macOS and +40% on Windows. Also, much less CPU cycles are consumed. Seeshutil-platform-dependent-efficient-copy-operationssection. (Contributed by Giampaolo Rodolà in33671.) -
shutil.copytreeusesos.scandirfunction and all copy functions depending from it use cachedos.statvalues. The speedup for copying a directory with 8000 files is around +9% on Linux, +20% on Windows and +30% on a Windows SMB share. Also the number ofos.statsyscalls is reduced by 38% makingshutil.copytreeespecially faster on network filesystems. (Contributed by Giampaolo Rodolà in33695.) -
The default protocol in the
picklemodule is now Protocol 4, first introduced in Python 3.4. It offers better performance and smaller size compared to Protocol 3 available since Python 3.0. -
Removed one
Py_ssize_tmember fromPyGC_Head. All GC tracked objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes. (Contributed by Inada Naoki in33597.) -
uuid.UUIDnow uses__slots__to reduce its memory footprint. (Contributed by Wouter Bolsterlee and Tal Einat in30977) -
Improved performance of
operator.itemgetterby 33%. Optimized argument handling and added a fast path for the common case of a single non-negative integer index into a tuple (which is the typical use case in the standard library). (Contributed by Raymond Hettinger in35664.) -
Sped-up field lookups in
collections.namedtuple. They are now more than two times faster, making them the fastest form of instance variable lookup in Python. (Contributed by Raymond Hettinger, Pablo Galindo, and Joe Jevnik, Serhiy Storchaka in32492.) -
The
listconstructor does not overallocate the internal item buffer if the input iterable has a known length (the input implements__len__). This makes the created list 12% smaller on average. (Contributed by Raymond Hettinger and Pablo Galindo in33234.) -
Doubled the speed of class variable writes. When a non-dunder attribute was updated, there was an unnecessary call to update slots. (Contributed by Stefan Behnel, Pablo Galindo Salgado, Raymond Hettinger, Neil Schemenauer, and Serhiy Storchaka in
36012.) -
Reduced an overhead of converting arguments passed to many builtin functions and methods. This sped up calling some simple builtin functions and methods up to 20--50%. (Contributed by Serhiy Storchaka in
23867,35582and36127.) -
LOAD_GLOBALinstruction now uses new "per opcode cache" mechanism. It is about 40% faster now. (Contributed by Yury Selivanov and Inada Naoki in26219.)
Build and C API Changes
-
Default
sys.abiflagsbecame an empty string: themflag for pymalloc became useless (builds with and without pymalloc are ABI compatible) and so has been removed. (Contributed by Victor Stinner in36707.)Example of changes:
- Only
python3.8program is installed,python3.8mprogram is gone. - Only
python3.8-configscript is installed,python3.8m-configscript is gone. - The
mflag has been removed from the suffix of dynamic library filenames: extension modules in the standard library as well as those produced and installed by third-party packages, like those downloaded from PyPI. On Linux, for example, the Python 3.7 suffix.cpython-37m-x86_64-linux-gnu.sobecame.cpython-38-x86_64-linux-gnu.soin Python 3.8.
- Only
-
The header files have been reorganized to better separate the different kinds of APIs:
Include/*.hshould be the portable public stable C API.Include/cpython/*.hshould be the unstable C API specific to CPython; public API, with some private API prefixed by_Pyor_PY.Include/internal/*.his the private internal C API very specific to CPython. This API comes with no backward compatibility warranty and should not be used outside CPython. It is only exposed for very specific needs like debuggers and profiles which has to access to CPython internals without calling functions. This API is now installed bymake install.
(Contributed by Victor Stinner in
35134and35081, work initiated by Eric Snow in Python 3.7.) -
Some macros have been converted to static inline functions: parameter types and return type are well defined, they don't have issues specific to macros, variables have a local scopes. Examples:
Py_INCREF,Py_DECREFPy_XINCREF,Py_XDECREF!PyObject_INIT,!PyObject_INIT_VAR- Private functions:
!_PyObject_GC_TRACK,!_PyObject_GC_UNTRACK,!_Py_Dealloc
(Contributed by Victor Stinner in
35059.) -
The
!PyByteArray_Initand!PyByteArray_Finifunctions have been removed. They did nothing since Python 2.7.4 and Python 3.2.0, were excluded from the limited API (stable ABI), and were not documented. (Contributed by Victor Stinner in35713.) -
The result of
PyExceptionClass_Nameis now of typeconst char *rather ofchar *. (Contributed by Serhiy Storchaka in33818.) -
The duality of
Modules/Setup.distandModules/Setuphas been removed. Previously, when updating the CPython source tree, one had to manually copyModules/Setup.dist(inside the source tree) toModules/Setup(inside the build tree) in order to reflect any changes upstream. This was of a small benefit to packagers at the expense of a frequent annoyance to developers following CPython development, as forgetting to copy the file could produce build failures.Now the build system always reads from
Modules/Setupinside the source tree. People who want to customize that file are encouraged to maintain their changes in a git fork of CPython or as patch files, as they would do for any other change to the source tree.(Contributed by Antoine Pitrou in
32430.) -
Functions that convert Python number to C integer like
PyLong_AsLongand argument parsing functions likePyArg_ParseTuplewith integer converting format units like'i'will now use the~object.__index__special method instead of~object.__int__, if available. The deprecation warning will be emitted for objects with the__int__()method but without the__index__()method (like~decimal.Decimaland~fractions.Fraction).PyNumber_Checkwill now return1for objects implementing__index__().PyNumber_Long,PyNumber_FloatandPyFloat_AsDoublealso now use the__index__()method if available. (Contributed by Serhiy Storchaka in36048and20092.) -
Heap-allocated type objects will now increase their reference count in
PyObject_Init(and its parallel macroPyObject_INIT) instead of inPyType_GenericAlloc. Types that modify instance allocation or deallocation may need to be adjusted. (Contributed by Eddie Elizondo in35810.) -
The new function
!PyCode_NewWithPosOnlyArgsallows to create code objects like!PyCode_New, but with an extra posonlyargcount parameter for indicating the number of positional-only arguments. (Contributed by Pablo Galindo in37221.) -
!Py_SetPathnow setssys.executableto the program full path (!Py_GetProgramFullPath) rather than to the program name (!Py_GetProgramName). (Contributed by Victor Stinner in38234.)
Deprecated
-
The distutils
bdist_wininstcommand is now deprecated, usebdist_wheel(wheel packages) instead. (Contributed by Victor Stinner in37481.) -
Deprecated methods
getchildren()andgetiterator()in the~xml.etree.ElementTreemodule now emit aDeprecationWarninginstead ofPendingDeprecationWarning. They will be removed in Python 3.9. (Contributed by Serhiy Storchaka in29209.) -
Passing an object that is not an instance of
concurrent.futures.ThreadPoolExecutortoloop.set_default_executor() <asyncio.loop.set_default_executor>is deprecated and will be prohibited in Python 3.9. (Contributed by Elvis Pranskevichus in34075.) -
The
~object.__getitem__methods ofxml.dom.pulldom.DOMEventStream,wsgiref.util.FileWrapperandfileinput.FileInputhave been deprecated.Implementations of these methods have been ignoring their index parameter, and returning the next item instead. (Contributed by Berker Peksag in
9372.) -
The
typing.NamedTupleclass has deprecated the_field_typesattribute in favor of the__annotations__attribute which has the same information. (Contributed by Raymond Hettinger in36320.) -
astclassesNum,Str,Bytes,NameConstantandEllipsisare considered deprecated and will be removed in future Python versions.~ast.Constantshould be used instead. (Contributed by Serhiy Storchaka in32892.) -
ast.NodeVisitormethodsvisit_Num(),visit_Str(),visit_Bytes(),visit_NameConstant()andvisit_Ellipsis()are deprecated now and will not be called in future Python versions. Add the~ast.NodeVisitor.visit_Constantmethod to handle all constant nodes. (Contributed by Serhiy Storchaka in36917.) -
The
!asyncio.coroutinedecoratoris deprecated and will be removed in version 3.10. Instead of@asyncio.coroutine, useasync definstead. (Contributed by Andrew Svetlov in36921.) -
In
asyncio, the explicit passing of a loop argument has been deprecated and will be removed in version 3.10 for the following:asyncio.sleep,asyncio.gather,asyncio.shield,asyncio.wait_for,asyncio.wait,asyncio.as_completed,asyncio.Task,asyncio.Lock,asyncio.Event,asyncio.Condition,asyncio.Semaphore,asyncio.BoundedSemaphore,asyncio.Queue,asyncio.create_subprocess_exec, andasyncio.create_subprocess_shell. -
The explicit passing of coroutine objects to
asyncio.waithas been deprecated and will be removed in version 3.11. (Contributed by Yury Selivanov in34790.) -
The following functions and methods are deprecated in the
gettextmodule:!lgettext,!ldgettext,!lngettextand!ldngettext. They return encoded bytes, and it's possible that you will get unexpected Unicode-related exceptions if there are encoding problems with the translated strings. It's much better to use alternatives which return Unicode strings in Python 3. These functions have been broken for a long time.Function
!bind_textdomain_codeset, methods!NullTranslations.output_charsetand!NullTranslations.set_output_charset, and the codeset parameter of functions~gettext.translationand~gettext.installare also deprecated, since they are only used for thel*gettext()functions. (Contributed by Serhiy Storchaka in33710.) -
The
!isAlivemethod ofthreading.Threadhas been deprecated. (Contributed by Donghee Na in35283.) -
Many builtin and extension functions that take integer arguments will now emit a deprecation warning for
~decimal.Decimals,~fractions.Fractions and any other objects that can be converted to integers only with a loss (e.g. that have the~object.__int__method but do not have the~object.__index__method). In future version they will be errors. (Contributed by Serhiy Storchaka in36048.) -
Deprecated passing the following arguments as keyword arguments:
- func in
functools.partialmethod,weakref.finalize,profile.Profile.runcall,!cProfile.Profile.runcall,bdb.Bdb.runcall,trace.Trace.runfuncandcurses.wrapper. - function in
unittest.TestCase.addCleanup. - fn in the
~concurrent.futures.Executor.submitmethod ofconcurrent.futures.ThreadPoolExecutorandconcurrent.futures.ProcessPoolExecutor. - callback in
contextlib.ExitStack.callback,!contextlib.AsyncExitStack.callbackandcontextlib.AsyncExitStack.push_async_callback. - c and typeid in the
!createmethod of!multiprocessing.managers.Serverand!multiprocessing.managers.SharedMemoryServer. - obj in
weakref.finalize.
In future releases of Python, they will be
positional-only <positional-only_parameter>. (Contributed by Serhiy Storchaka in36492.) - func in
API and Feature Removals
The following features and APIs have been removed from Python 3.8:
- Starting with Python 3.3, importing ABCs from
collectionswas deprecated, and importing should be done fromcollections.abc. Being able to import from collections was marked for removal in 3.8, but has been delayed to 3.9. (See81134.) - The
!macpathmodule, deprecated in Python 3.7, has been removed. (Contributed by Victor Stinner in35471.) - The function
!platform.popenhas been removed, after having been deprecated since Python 3.3: useos.popeninstead. (Contributed by Victor Stinner in35345.) - The function
!time.clockhas been removed, after having been deprecated since Python 3.3: usetime.perf_counterortime.process_timeinstead, depending on your requirements, to have well-defined behavior. (Contributed by Matthias Bussonnier in36895.) - The
pyvenvscript has been removed in favor ofpython3.8 -m venvto help eliminate confusion as to what Python interpreter thepyvenvscript is tied to. (Contributed by Brett Cannon in25427.) parse_qs,parse_qsl, andescapeare removed from the!cgimodule. They are deprecated in Python 3.2 or older. They should be imported from theurllib.parseandhtmlmodules instead.filemodefunction is removed from thetarfilemodule. It is not documented and deprecated since Python 3.3.- The
~xml.etree.ElementTree.XMLParserconstructor no longer accepts the html argument. It never had an effect and was deprecated in Python 3.4. All other parameters are nowkeyword-only <keyword-only_parameter>. (Contributed by Serhiy Storchaka in29209.) - Removed the
doctype()method of~xml.etree.ElementTree.XMLParser. (Contributed by Serhiy Storchaka in29209.) - "unicode_internal" codec is removed. (Contributed by Inada Naoki in
36297.) - The
CacheandStatementobjects of thesqlite3module are not exposed to the user. (Contributed by Aviv Palivoda in30262.) - The
bufsizekeyword argument offileinput.inputandfileinput.FileInputwhich was ignored and deprecated since Python 3.6 has been removed.36952(Contributed by Matthias Bussonnier.) - The functions
!sys.set_coroutine_wrapperand!sys.get_coroutine_wrapperdeprecated in Python 3.7 have been removed;36933(Contributed by Matthias Bussonnier.)
Porting to Python 3.8
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in Python behavior
- Yield expressions (both
yieldandyield fromclauses) are now disallowed in comprehensions and generator expressions (aside from the iterable expression in the leftmost!forclause). (Contributed by Serhiy Storchaka in10544.) - The compiler now produces a
SyntaxWarningwhen identity checks (isandis not) are used with certain types of literals (e.g. strings, numbers). These can often work by accident in CPython, but are not guaranteed by the language spec. The warning advises users to use equality tests (==and!=) instead. (Contributed by Serhiy Storchaka in34850.) - The CPython interpreter can swallow exceptions in some circumstances. In Python 3.8 this happens in fewer cases. In particular, exceptions raised when getting the attribute from the type dictionary are no longer ignored. (Contributed by Serhiy Storchaka in
35459.) - Removed
__str__implementations from builtin typesbool,int,float,complexand few classes from the standard library. They now inherit__str__()fromobject. As result, defining the__repr__()method in the subclass of these classes will affect their string representation. (Contributed by Serhiy Storchaka in36793.) - On AIX,
sys.platformdoesn't contain the major version anymore. It is always'aix', instead of'aix3'..'aix7'. Since older Python versions include the version number, so it is recommended to always usesys.platform.startswith('aix'). (Contributed by M. Felt in36588.) !PyEval_AcquireLockand!PyEval_AcquireThreadnow terminate the current thread if called while the interpreter is finalizing, making them consistent withPyEval_RestoreThread,Py_END_ALLOW_THREADS, andPyGILState_Ensure. If this behavior is not desired, guard the call by checking!_Py_IsFinalizingorsys.is_finalizing. (Contributed by Joannah Nanjekye in36475.)
Changes in the Python API
- The
os.getcwdbfunction now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see529for the rationale. The function is no longer deprecated on Windows. (Contributed by Victor Stinner in37412.) subprocess.Popencan now useos.posix_spawnin some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, the~subprocess.Popenconstructor usingos.posix_spawnno longer raises an exception on errors like "missing program". Instead the child process fails with a non-zero~subprocess.Popen.returncode. (Contributed by Joannah Nanjekye and Victor Stinner in35537.)- The preexec_fn argument of *
subprocess.Popenis no longer compatible with subinterpreters. The use of the parameter in a subinterpreter now raisesRuntimeError. (Contributed by Eric Snow in34651, modified by Christian Heimes in37951.) - The
imaplib.IMAP4.logoutmethod no longer silently ignores arbitrary exceptions. (Contributed by Victor Stinner in36348.) - The function
!platform.popenhas been removed, after having been deprecated since Python 3.3: useos.popeninstead. (Contributed by Victor Stinner in35345.) - The
statistics.modefunction no longer raises an exception when given multimodal data. Instead, it returns the first mode encountered in the input data. (Contributed by Raymond Hettinger in35892.) - The
~tkinter.ttk.Treeview.selectionmethod of thetkinter.ttk.Treeviewclass no longer takes arguments. Using it with arguments for changing the selection was deprecated in Python 3.6. Use specialized methods like~tkinter.ttk.Treeview.selection_setfor changing the selection. (Contributed by Serhiy Storchaka in31508.) - The
~xml.dom.minidom.Node.writexml,~xml.dom.minidom.Node.toxmland~xml.dom.minidom.Node.toprettyxmlmethods ofxml.dom.minidomand the~xml.etree.ElementTree.ElementTree.writemethod ofxml.etree.ElementTreenow preserve the attribute order specified by the user. (Contributed by Diego Rojas and Raymond Hettinger in34160.) - A
dbm.dumbdatabase opened with flags'r'is now read-only.dbm.dumb.openwith flags'r'and'w'no longer creates a database if it does not exist. (Contributed by Serhiy Storchaka in32749.) - The
doctype()method defined in a subclass of~xml.etree.ElementTree.XMLParserwill no longer be called and will emit aRuntimeWarninginstead of aDeprecationWarning. Define thedoctype() <xml.etree.ElementTree.TreeBuilder.doctype>method on a target for handling an XML doctype declaration. (Contributed by Serhiy Storchaka in29209.) - A
RuntimeErroris now raised when the custom metaclass doesn't provide the__classcell__entry in the namespace passed totype.__new__. ADeprecationWarningwas emitted in Python 3.6--3.7. (Contributed by Serhiy Storchaka in23722.) - The
cProfile.Profile <profile.Profile>class can now be used as a context manager. (Contributed by Scott Sanderson in29235.) shutil.copyfile,shutil.copy,shutil.copy2,shutil.copytreeandshutil.moveuse platform-specific "fast-copy" syscalls (seeshutil-platform-dependent-efficient-copy-operationssection).shutil.copyfiledefault buffer size on Windows was changed from 16 KiB to 1 MiB.- The
PyGC_Headstruct has changed completely. All code that touched the struct member should be rewritten. (See33597.) - The
PyInterpreterStatestruct has been moved into the "internal" header files (specifically Include/internal/pycore_pystate.h). An opaquePyInterpreterStateis still available as part of the public API (and stable ABI). The docs indicate that none of the struct's fields are public, so we hope no one has been using them. However, if you do rely on one or more of those private fields and have no alternative then please open a BPO issue. We'll work on helping you adjust (possibly including adding accessor functions to the public API). (See35886.) - The
mmap.flush() <mmap.mmap.flush>method now returnsNoneon success and raises an exception on error under all platforms. Previously, its behavior was platform-dependent: a nonzero value was returned on success; zero was returned on error under Windows. A zero value was returned on success; an exception was raised on error under Unix. (Contributed by Berker Peksag in2122.) xml.dom.minidomandxml.saxmodules no longer process external entities by default. (Contributed by Christian Heimes in17239.)- Deleting a key from a read-only
dbmdatabase (dbm.dumb,dbm.gnuordbm.ndbm) raises!error(dbm.dumb.error,dbm.gnu.errorordbm.ndbm.error) instead ofKeyError. (Contributed by Xiang Zhang in33106.) - Simplified AST for literals. All constants will be represented as
ast.Constantinstances. Instantiating old classesNum,Str,Bytes,NameConstantandEllipsiswill return an instance ofConstant. (Contributed by Serhiy Storchaka in32892.) ~os.path.expanduseron Windows now prefers theUSERPROFILEenvironment variable and does not useHOME, which is not normally set for regular user accounts. (Contributed by Anthony Sottile in36264.)- The exception
asyncio.CancelledErrornow inherits fromBaseExceptionrather thanExceptionand no longer inherits fromconcurrent.futures.CancelledError. (Contributed by Yury Selivanov in32528.) - The function
asyncio.wait_fornow correctly waits for cancellation when using an instance ofasyncio.Task. Previously, upon reaching timeout, it was cancelled and immediately returned. (Contributed by Elvis Pranskevichus in32751.) - The function
asyncio.BaseTransport.get_extra_infonow returns a safe to use socket object when 'socket' is passed to the name parameter. (Contributed by Yury Selivanov in37027.) asyncio.BufferedProtocolhas graduated to the stable API.
- DLL dependencies for extension modules and DLLs loaded with
ctypeson Windows are now resolved more securely. Only the system paths, the directory containing the DLL or PYD file, and directories added with~os.add_dll_directoryare searched for load-time dependencies. Specifically,PATHand the current working directory are no longer used, and modifications to these will no longer have any effect on normal DLL resolution. If your application relies on these mechanisms, you should check for~os.add_dll_directoryand if it exists, use it to add your DLLs directory while loading your library. Note that Windows 7 users will need to ensure that Windows Update KB2533623 has been installed (this is also verified by the installer). (Contributed by Steve Dower in36085.) - The header files and functions related to pgen have been removed after its replacement by a pure Python implementation. (Contributed by Pablo Galindo in
36623.) types.CodeTypehas a new parameter in the second position of the constructor (posonlyargcount) to support positional-only arguments defined in570. The first argument (argcount) now represents the total number of positional arguments (including positional-only arguments). The newreplace()method oftypes.CodeTypecan be used to make the code future-proof.- The parameter
digestmodforhmac.newno longer uses the MD5 digest by default.
Changes in the C API
-
The
PyCompilerFlagsstructure got a new cf_feature_version field. It should be initialized toPY_MINOR_VERSION. The field is ignored by default, and is used if and only ifPyCF_ONLY_ASTflag is set in cf_flags. (Contributed by Guido van Rossum in35766.) -
The
!PyEval_ReInitThreadsfunction has been removed from the C API. It should not be called explicitly: usePyOS_AfterFork_Childinstead. (Contributed by Victor Stinner in36728.) -
On Unix, C extensions are no longer linked to libpython except on Android and Cygwin. When Python is embedded,
libpythonmust not be loaded withRTLD_LOCAL, butRTLD_GLOBALinstead. Previously, usingRTLD_LOCAL, it was already not possible to load C extensions which were not linked tolibpython, like C extensions of the standard library built by the*shared*section ofModules/Setup. (Contributed by Victor Stinner in21536.) -
Use of
#variants of formats in parsing or building value (e.g.PyArg_ParseTuple,Py_BuildValue,PyObject_CallFunction, etc.) withoutPY_SSIZE_T_CLEANdefined raisesDeprecationWarningnow. It will be removed in 3.10 or 4.0. Readarg-parsingfor detail. (Contributed by Inada Naoki in36381.) -
Instances of heap-allocated types (such as those created with
PyType_FromSpec) hold a reference to their type object. Increasing the reference count of these type objects has been moved fromPyType_GenericAllocto the more low-level functions,PyObject_Initand!PyObject_INIT. This makes types created throughPyType_FromSpecbehave like other classes in managed code.Statically allocated types <static-types>are not affected.For the vast majority of cases, there should be no side effect. However, types that manually increase the reference count after allocating an instance (perhaps to work around the bug) may now become immortal. To avoid this, these classes need to call Py_DECREF on the type object during instance deallocation.
To correctly port these types into 3.8, please apply the following changes:
-
Remove
Py_INCREFon the type object after allocating an instance - if any. This may happen after callingPyObject_New,PyObject_NewVar,PyObject_GC_New,PyObject_GC_NewVar, or any other custom allocator that usesPyObject_Initor!PyObject_INIT.Example:
static foo_struct * foo_new(PyObject *type) { foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type); if (foo == NULL) return NULL; #if PY_VERSION_HEX < 0x03080000 // Workaround for Python issue 35810; no longer necessary in Python 3.8 PY_INCREF(type) #endif return foo; } -
Ensure that all custom
tp_deallocfunctions of heap-allocated types decrease the type's reference count.Example:
static void foo_dealloc(foo_struct *instance) { PyObject *type = Py_TYPE(instance); PyObject_GC_Del(instance); #if PY_VERSION_HEX >= 0x03080000 // This was not needed before Python 3.8 (Python issue 35810) Py_DECREF(type); #endif }
(Contributed by Eddie Elizondo in
35810.) -
-
The
Py_DEPRECATED()macro has been implemented for MSVC. The macro now must be placed before the symbol name.Example:
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);(Contributed by Zackery Spytz in
33407.) -
The interpreter does not pretend to support binary compatibility of extension types across feature releases, anymore. A
PyTypeObjectexported by a third-party extension module is supposed to have all the slots expected in the current Python version, including~PyTypeObject.tp_finalize(Py_TPFLAGS_HAVE_FINALIZEis not checked anymore before reading~PyTypeObject.tp_finalize).(Contributed by Antoine Pitrou in
32388.) -
The functions
!PyNode_AddChildand!PyParser_AddTokennow accept two additionalintarguments end_lineno and end_col_offset. -
The
libpython38.afile to allow MinGW tools to link directly againstpython38.dllis no longer included in the regular Windows distribution. If you require this file, it may be generated with thegendefanddlltooltools, which are part of the MinGW binutils package:gendef - python38.dll > tmp.def dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.aThe location of an installed
pythonXY.dllwill depend on the installation options and the version and language of Windows. Seeusing-on-windowsfor more information. The resulting library should be placed in the same directory aspythonXY.lib, which is generally thelibsdirectory under your Python installation.(Contributed by Steve Dower in
37351.)
CPython bytecode changes
-
The interpreter loop has been simplified by moving the logic of unrolling the stack of blocks into the compiler. The compiler emits now explicit instructions for adjusting the stack of values and calling the cleaning-up code for
break,continueandreturn.Removed opcodes
!BREAK_LOOP,!CONTINUE_LOOP,!SETUP_LOOPand!SETUP_EXCEPT. Added new opcodes!ROT_FOUR,!BEGIN_FINALLY,!CALL_FINALLYand!POP_FINALLY. Changed the behavior of!END_FINALLYand!WITH_CLEANUP_START.(Contributed by Mark Shannon, Antoine Pitrou and Serhiy Storchaka in
17611.) -
Added new opcode
END_ASYNC_FORfor handling exceptions raised when awaiting a next item in anasync forloop. (Contributed by Serhiy Storchaka in33041.) -
The
MAP_ADDnow expects the value as the first element in the stack and the key as the second element. This change was made so the key is always evaluated before the value in dictionary comprehensions, as proposed by572. (Contributed by Jörn Heissler in35224.)
Demos and Tools
Added a benchmark script for timing various ways to access variables: Tools/scripts/var_access_benchmark.py. (Contributed by Raymond Hettinger in 35884.)
Here's a summary of performance improvements since Python 3.3:
Python version 3.3 3.4 3.5 3.6 3.7 3.8
-------------- --- --- --- --- --- ---
Variable and attribute read access:
read_local 4.0 7.1 7.1 5.4 5.1 3.9
read_nonlocal 5.3 7.1 8.1 5.8 5.4 4.4
read_global 13.3 15.5 19.0 14.3 13.6 7.6
read_builtin 20.0 21.1 21.6 18.5 19.0 7.5
read_classvar_from_class 20.5 25.6 26.5 20.7 19.5 18.4
read_classvar_from_instance 18.5 22.8 23.5 18.8 17.1 16.4
read_instancevar 26.8 32.4 33.1 28.0 26.3 25.4
read_instancevar_slots 23.7 27.8 31.3 20.8 20.8 20.2
read_namedtuple 68.5 73.8 57.5 45.0 46.8 18.4
read_boundmethod 29.8 37.6 37.9 29.6 26.9 27.7
Variable and attribute write access:
write_local 4.6 8.7 9.3 5.5 5.3 4.3
write_nonlocal 7.3 10.5 11.1 5.6 5.5 4.7
write_global 15.9 19.7 21.2 18.0 18.0 15.8
write_classvar 81.9 92.9 96.0 104.6 102.1 39.2
write_instancevar 36.4 44.6 45.8 40.0 38.9 35.5
write_instancevar_slots 28.7 35.6 36.1 27.3 26.6 25.7
Data structure read access:
read_list 19.2 24.2 24.5 20.8 20.8 19.0
read_deque 19.9 24.7 25.5 20.2 20.6 19.8
read_dict 19.7 24.3 25.7 22.3 23.0 21.0
read_strdict 17.9 22.6 24.3 19.5 21.2 18.9
Data structure write access:
write_list 21.2 27.1 28.5 22.5 21.6 20.0
write_deque 23.8 28.7 30.1 22.7 21.8 23.5
write_dict 25.9 31.4 33.3 29.3 29.2 24.7
write_strdict 22.9 28.4 29.9 27.5 25.2 23.1
Stack (or queue) operations:
list_append_pop 144.2 93.4 112.7 75.4 74.2 50.8
deque_append_pop 30.4 43.5 57.0 49.4 49.2 42.5
deque_append_popleft 30.8 43.7 57.3 49.7 49.7 42.8
Timing loop:
loop_overhead 0.3 0.5 0.6 0.4 0.3 0.3
The benchmarks were measured on an Intel® Core™ i7-4960HQ processor running the macOS 64-bit builds found at python.org. The benchmark script displays timings in nanoseconds.
Notable changes in Python 3.8.1
Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in 37228.)
Notable changes in Python 3.8.2
Fixed a regression with the ignore callback of shutil.copytree. The argument types are now str and List[str] again. (Contributed by Manuel Barkhau and Giampaolo Rodola in 83571.)
Notable changes in Python 3.8.3
The constant values of future flags in the __future__ module are updated in order to prevent collision with compiler flags. Previously PyCF_ALLOW_TOP_LEVEL_AWAIT was clashing with CO_FUTURE_DIVISION. (Contributed by Batuhan Taskaya in 83743)
Notable changes in Python 3.8.8
Earlier Python versions allowed using both ; and & as query parameter separators in urllib.parse.parse_qs and urllib.parse.parse_qsl. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects !cgi.parse and !cgi.parse_multipart as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in 42967.)
Notable changes in Python 3.8.9
A security fix alters the ftplib.FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel. We reuse the ftp server IP address instead. For unusual code requiring the old behavior, set a trust_server_pasv_ipv4_address attribute on your FTP instance to True. (See 87451)
Notable changes in Python 3.8.10
macOS 11.0 (Big Sur) and Apple Silicon Mac support
As of 3.8.10, Python now supports building and running on macOS 11 (Big Sur) and on Apple Silicon Macs (based on the ARM64 architecture). A new universal build variant, universal2, is now available to natively support both ARM64 and Intel 64 in one set of executables. Note that support for "weaklinking", building binaries targeted for newer versions of macOS that will also run correctly on older versions by testing at runtime for missing features, is not included in this backport from Python 3.9; to support a range of macOS versions, continue to target for and build on the oldest version in the range.
(Originally contributed by Ronald Oussoren and Lawrence D'Anna in 85272, with fixes by FX Coudert and Eli Rykoff, and backported to 3.8 by Maxime Bélanger and Ned Deily)
Notable changes in Python 3.8.10
urllib.parse
The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates 3986, ASCII newline \n, \r and tab \t characters are stripped from the URL by the parser in urllib.parse preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (See 43882)
Notable changes in Python 3.8.12
Changes in the Python API
Starting with Python 3.8.12 the ipaddress module no longer accepts any leading zeros in IPv4 address strings. Leading zeros are ambiguous and interpreted as octal notation by some libraries. For example the legacy function socket.inet_aton treats leading zeros as octal notation. glibc implementation of modern ~socket.inet_pton does not accept any leading zeros.
(Originally contributed by Christian Heimes in 36384, and backported to 3.8 by Achraf Merzouki.)
Notable security feature in 3.8.14
Converting between int and str in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for 2020-10735. This limit can be configured or disabled by environment variable, command line flag, or sys APIs. See the integer string conversion length limitation <int_max_str_digits> documentation. The default limit is 4300 digits in string form.
Notable changes in 3.8.17
tarfile
- The extraction methods in
tarfile, andshutil.unpack_archive, have a new a filter argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. Seetarfile-extraction-filterfor details. In Python 3.12, use without the filter argument will show aDeprecationWarning. In Python 3.14, the default will switch to'data'. (Contributed by Petr Viktorin in706.)
What's New In Python 3.9
Editor
Łukasz Langa
* Anyone can add text to this document. Your text might get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes will be too small or esoteric to include. If such a change is added to the text, it might get removed during final editing.
* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.
* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.
* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.
- It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in
12345.)This saves the maintainer the effort of going through the Mercurial log when researching a change.
This article explains the new features in Python 3.9, compared to 3.8. Python 3.9 was released on October 5, 2020. For full details, see the changelog <changelog>.
596 - Python 3.9 Release Schedule
Summary -- Release highlights
New syntax features:
584, union operators added todict;585, type hinting generics in standard collections;614, relaxed grammar restrictions on decorators.
New built-in features:
616, string methods to remove prefixes and suffixes.
New features in the standard library:
593, flexible function and variable annotations;os.pidfd_openadded that allows process management without races and signals.
Interpreter improvements:
573, fast access to module state from methods of C extension types;617, CPython now uses a new parser based on PEG;- a number of Python builtins (range, tuple, set, frozenset, list, dict) are now sped up using
590vectorcall; - 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 defined by PEP 489; - a number of standard library modules (
!audioop,ast,grp,!_hashlib,pwd,!_posixsubprocess,random,select,struct,termios,zlib) are now using the stable ABI defined by PEP 384.
New library modules:
615, the IANA Time Zone Database is now present in the standard library in thezoneinfomodule;- an implementation of a topological sort of a graph is now provided in the new
graphlibmodule.
Release process changes:
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 3 was kept for backward compatibility with Python 2.7. With the end of Python 2 support, these backward compatibility layers have been removed, or will be removed soon. Most of them emitted a DeprecationWarning warning for several years. For example, using collections.Mapping instead of collections.abc.Mapping emits a DeprecationWarning since Python 3.3, released in 2012.
Test your application with the -W default command-line option to see DeprecationWarning and PendingDeprecationWarning, or even with -W error to treat them as errors. Warnings Filter <warning-filter> can be used to ignore warnings from third-party code.
Python 3.9 is the last version providing those Python 2 backward compatibility layers, to give more time to Python projects maintainers to organize the removal of the Python 2 support and add support for Python 3.9.
Aliases to Abstract Base Classes <collections-abstract-base-classes> in the collections module, like collections.Mapping alias to collections.abc.Mapping, are kept for one last release for backward compatibility. They will be removed from Python 3.10.
More generally, try to run your tests in the Python Development Mode <devmode> which helps to prepare your code to make it compatible with the next Python version.
Note: a number of pre-existing deprecations were removed in this version of Python as well. Consult the removed-in-python-39 section.
New Features
Dictionary Merge & Update Operators
Merge (|) and update (|=) operators have been added to the built-in dict class. Those complement the existing dict.update and {**d1, **d2} methods of merging dictionaries.
Example:
>>> 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'}
See 584 for a full description. (Contributed by Brandt Bucher in 36144.)
New String Methods to Remove Prefixes and Suffixes
str.removeprefix(prefix)<str.removeprefix> and str.removesuffix(suffix)<str.removesuffix> have been added to easily remove an unneeded prefix or a suffix from a string. Corresponding bytes, bytearray, and collections.UserString methods have also been added. See 616 for a full description. (Contributed by Dennis Sweeney in 39939.)
Type Hinting Generics in Standard Collections
In type annotations you can now use built-in collection types such as list and dict as generic types instead of importing the corresponding capitalized types (e.g. List or Dict) from typing. Some other types in the standard library are also now generic, for example queue.Queue.
Example:
def greet_all(names: list[str]) -> None:
for name in names:
print("Hello", name)
See 585 for more details. (Contributed by Guido van Rossum, Ethan Smith, and Batuhan Taşkaya in 39481.)
New Parser
Python 3.9 uses a new parser, based on PEG instead of LL(1). The new parser's performance is roughly comparable to that of the old parser, but the PEG formalism is more flexible than LL(1) when it comes to designing new language features. We'll start using this flexibility in Python 3.10 and later.
The ast module uses the new parser and produces the same AST as the old parser.
In Python 3.10, the old parser will be deleted and so will all functionality that depends on it (primarily the !parser module, which has long been deprecated). In Python 3.9 only, you can switch back to the LL(1) parser using a command line switch (-X oldparser) or an environment variable (PYTHONOLDPARSER=1).
See 617 for more details. (Contributed by Guido van Rossum, Pablo Galindo and Lysandros Nikolaou in 40334.)
Other Language Changes
-
__import__now raisesImportErrorinstead ofValueError, which used to occur when a relative import went past its top-level package. (Contributed by Ngalim Siregar in37444.) -
Python now gets the absolute path of the script filename specified on the command line (ex:
python3 script.py): the__file__attribute of the__main__module became an absolute path, rather than a relative path. These paths now remain valid after the current directory is changed byos.chdir. As a side effect, the traceback also displays the absolute path for__main__module frames in this case. (Contributed by Victor Stinner in20443.) -
In the
Python Development Mode <devmode>and indebug build <debug-build>, the encoding and errors arguments are now checked for string encoding and decoding operations. Examples:open,str.encodeandbytes.decode.By default, for best performance, the errors argument is only checked at the first encoding/decoding error and the encoding argument is sometimes ignored for empty strings. (Contributed by Victor Stinner in
37388.) -
"".replace("", s, n)now returnssinstead of an empty string for all non-zeron. It is now consistent with"".replace("", s). There are similar changes forbytesandbytearrayobjects. (Contributed by Serhiy Storchaka in28029.) -
Any valid expression can now be used as a
decorator. Previously, the grammar was much more restrictive. See614for details. (Contributed by Brandt Bucher in39702.) -
Improved help for the
typingmodule. Docstrings are now shown for all special forms and special generic aliases (likeUnionandList). Usinghelpwith generic alias likeList[int]will show the help for the correspondent concrete type (listin this case). (Contributed by Serhiy Storchaka in40257.) -
Parallel running of
~agen.aclose/~agen.asend/~agen.athrowis now prohibited, andag_runningnow reflects the actual running status of the async generator. (Contributed by Yury Selivanov in30773.) -
Unexpected errors in calling the
__iter__method are no longer masked byTypeErrorin theinoperator and functions~operator.contains,~operator.indexOfand~operator.countOfof theoperatormodule. (Contributed by Serhiy Storchaka in40824.) -
Unparenthesized lambda expressions can no longer be the expression part in an
ifclause in comprehensions and generator expressions. See41848and43755for details.
New Modules
zoneinfo
The zoneinfo module brings support for the IANA time zone database to the standard library. It adds zoneinfo.ZoneInfo, a concrete datetime.tzinfo implementation backed by the system's time zone data.
Example:
>>> from zoneinfo import ZoneInfo
>>> import datetime as dt
>>> # Daylight saving time
>>> when = dt.datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(when)
2020-10-31 12:00:00-07:00
>>> when.tzname()
'PDT'
>>> # Standard time
>>> when += dt.timedelta(days=7)
>>> print(when)
2020-11-07 12:00:00-08:00
>>> print(when.tzname())
PST
As a fall-back source of data for platforms that don't ship the IANA database, the tzdata module was released as a first-party package -- distributed via PyPI and maintained by the CPython core team.
615 -- Support for the IANA Time Zone Database in the Standard Library
PEP written and implemented by Paul Ganssle
graphlib
A new module, graphlib, was added that contains the graphlib.TopologicalSorter class to offer functionality to perform topological sorting of graphs. (Contributed by Pablo Galindo, Tim Peters and Larry Hastings in 17005.)
Improved Modules
ast
Added the indent option to ~ast.dump which allows it to produce a multiline indented output. (Contributed by Serhiy Storchaka in 37995.)
Added ast.unparse as a function in the ast module that can be used to unparse an ast.AST object and produce a string with code that would produce an equivalent ast.AST object when parsed. (Contributed by Pablo Galindo and Batuhan Taskaya in 38870.)
Added docstrings to AST nodes that contains the ASDL signature used to construct that node. (Contributed by Batuhan Taskaya in 39638.)
asyncio
Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in 37228.)
Added a new coroutine ~asyncio.loop.shutdown_default_executor that schedules a shutdown for the default executor that waits on the ~concurrent.futures.ThreadPoolExecutor to finish closing. Also, asyncio.run has been updated to use the new coroutine. (Contributed by Kyle Stanley in 34037.)
Added !asyncio.PidfdChildWatcher, a Linux-specific child watcher implementation that polls process file descriptors. (38692)
Added a new coroutine asyncio.to_thread. It is mainly used for running IO-bound functions in a separate thread to avoid blocking the event loop, and essentially works as a high-level version of ~asyncio.loop.run_in_executor that can directly take keyword arguments. (Contributed by Kyle Stanley and Yury Selivanov in 32309.)
When cancelling the task due to a timeout, asyncio.wait_for will now wait until the cancellation is complete also in the case when timeout is <= 0, like it does with positive timeouts. (Contributed by Elvis Pranskevichus in 32751.)
asyncio now raises TypeError when calling incompatible methods with an ssl.SSLSocket socket. (Contributed by Ido Michael in 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 in 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 in 38112.)
concurrent.futures
Added a new cancel_futures parameter to concurrent.futures.Executor.shutdown that cancels all pending futures which have not started running, instead of waiting for them to complete before shutting down the executor. (Contributed by Kyle Stanley in 39349.)
Removed daemon threads from ~concurrent.futures.ThreadPoolExecutor and ~concurrent.futures.ProcessPoolExecutor. This improves compatibility with subinterpreters and predictability in their shutdown processes. (Contributed by Kyle Stanley in 39812.)
Workers in ~concurrent.futures.ProcessPoolExecutor are now spawned on demand, only when there are no available idle workers to reuse. This optimizes startup overhead and reduces the amount of lost CPU time to idle workers. (Contributed by Kyle Stanley in 39207.)
curses
Added curses.get_escdelay, curses.set_escdelay, curses.get_tabsize, and curses.set_tabsize functions. (Contributed by Anthony Sottile in 38312.)
datetime
The ~datetime.date.isocalendar of datetime.date and ~datetime.datetime.isocalendar of datetime.datetime methods now returns a ~collections.namedtuple instead of a tuple. (Contributed by Donghee Na in 24416.)
distutils
The upload command now creates SHA2-256 and Blake2b-256 hash digests. It skips MD5 on platforms that block MD5 digest. (Contributed by Christian Heimes in 40698.)
fcntl
Added constants !fcntl.F_OFD_GETLK, !fcntl.F_OFD_SETLK and !fcntl.F_OFD_SETLKW. (Contributed by Donghee Na in 38602.)
ftplib
~ftplib.FTP and ~ftplib.FTP_TLS now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Donghee Na in 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 have been executed), do not block the collection of all objects that are still unreachable. (Contributed by Pablo Galindo and Tim Peters in 38379.)
Added a new function gc.is_finalized to check if an object has been finalized by the garbage collector. (Contributed by Pablo Galindo in 39322.)
hashlib
The hashlib module can now use SHA3 hashes and SHAKE XOF from OpenSSL when available. (Contributed by Christian Heimes in 37630.)
Builtin hash modules can now be disabled with ./configure --without-builtin-hashlib-hashes or selectively enabled with e.g. ./configure --with-builtin-hashlib-hashes=sha3,blake2 to force use of OpenSSL based implementation. (Contributed by Christian Heimes in 40479)
http
HTTP status codes 103 EARLY_HINTS, 418 IM_A_TEAPOT and 425 TOO_EARLY are added to http.HTTPStatus. (Contributed by Donghee Na in 39509 and Ross Rhodes in 39507.)
IDLE and idlelib
Added option to toggle cursor blink off. (Contributed by Zackery Spytz in 4603.)
Escape key now closes IDLE completion windows. (Contributed by Johnny Najera in 38944.)
Added keywords to module name completion list. (Contributed by Terry J. Reedy in 37765.)
New in 3.9 maintenance releases
Make IDLE invoke sys.excepthook (when started without '-n'). User hooks were previously ignored. (Contributed by Ken Hilton in 43008.)
The changes above have been backported to 3.8 maintenance releases.
Rearrange the settings dialog. Split the General tab into Windows and Shell/Ed tabs. Move help sources, which extend the Help menu, to the Extensions tab. Make space for new options and shorten the dialog. The latter makes the dialog better fit small screens. (Contributed by Terry Jan Reedy in 40468.) Move the indent space setting from the Font tab to the new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy in 33962.)
Apply syntax highlighting to .pyi files. (Contributed by Alex Waygood and Terry Jan Reedy in 45447.)
imaplib
~imaplib.IMAP4 and ~imaplib.IMAP4_SSL now have an optional timeout parameter for their constructors. Also, the ~imaplib.IMAP4.open method now has an optional timeout parameter with this change. The overridden methods of ~imaplib.IMAP4_SSL and ~imaplib.IMAP4_stream were applied to this change. (Contributed by Donghee Na in 38615.)
imaplib.IMAP4.unselect is added. imaplib.IMAP4.unselect frees server's resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as imaplib.IMAP4.close, except that no messages are permanently removed from the currently selected mailbox. (Contributed by Donghee Na in 40375.)
importlib
To improve consistency with import statements, importlib.util.resolve_name now raises ImportError instead of ValueError for invalid relative import attempts. (Contributed by Ngalim Siregar in 37444.)
Import loaders which publish immutable module objects can now publish immutable packages in addition to individual modules. (Contributed by Dino Viehland in 39336.)
Added importlib.resources.files function with support for subdirectories in package data, matching backport in importlib_resources version 1.5. (Contributed by Jason R. Coombs in 39791.)
Refreshed importlib.metadata from importlib_metadata version 1.6.1.
inspect
inspect.BoundArguments.arguments is changed from OrderedDict to regular dict. (Contributed by Inada Naoki in 36350 and 39775.)
ipaddress
ipaddress now supports IPv6 Scoped Addresses (IPv6 address with suffix %<scope_id>).
Scoped IPv6 addresses can be parsed using ipaddress.IPv6Address. If present, scope zone ID is available through the ~ipaddress.IPv6Address.scope_id attribute. (Contributed by Oleksandr Pavliuk in 34788.)
Starting with Python 3.9.5 the ipaddress module no longer accepts any leading zeros in IPv4 address strings. (Contributed by Christian Heimes in 36384).
math
Expanded the math.gcd function to handle multiple arguments. Formerly, it only supported two arguments. (Contributed by Serhiy Storchaka in 39648.)
Added math.lcm: return the least common multiple of specified arguments. (Contributed by Mark Dickinson, Ananthakrishnan and Serhiy Storchaka in 39479 and 39648.)
Added math.nextafter: return the next floating-point value after x towards y. (Contributed by Victor Stinner in 39288.)
Added math.ulp: return the value of the least significant bit of a float. (Contributed by Victor Stinner in 39310.)
multiprocessing
The multiprocessing.SimpleQueue class has a new ~multiprocessing.SimpleQueue.close method to explicitly close the queue. (Contributed by Victor Stinner in 30966.)
nntplib
!NNTP and !NNTP_SSL now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Donghee Na in 39259.)
os
Added ~os.CLD_KILLED and ~os.CLD_STOPPED for !si_code. (Contributed by Donghee Na in 38493.)
Exposed the Linux-specific os.pidfd_open (38692) and os.P_PIDFD (38713) for process management with file descriptors.
The os.unsetenv function is now also available on Windows. (Contributed by Victor Stinner in 39413.)
The os.putenv and os.unsetenv functions are now always available. (Contributed by Victor Stinner in 39395.)
Added os.waitstatus_to_exitcode function: convert a wait status to an exit code. (Contributed by Victor Stinner in 40094.)
pathlib
Added pathlib.Path.readlink which acts similarly to os.readlink. (Contributed by Girts Folkmanis in 30618)
pdb
On Windows now ~pdb.Pdb supports ~/.pdbrc. (Contributed by Tim Hopper and Dan Lidral-Porter in 20523.)
poplib
~poplib.POP3 and ~poplib.POP3_SSL now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Donghee Na in 39259.)
pprint
pprint can now pretty-print types.SimpleNamespace. (Contributed by Carl Bordum Hansen in 37376.)
pydoc
The documentation string is now shown not only for class, function, method etc, but for any object that has its own ~definition.__doc__ attribute. (Contributed by Serhiy Storchaka in 40257.)
random
Added a new random.Random.randbytes method: generate random bytes. (Contributed by Victor Stinner in 40286.)
signal
Exposed the Linux-specific signal.pidfd_send_signal for sending to signals to a process using a file descriptor instead of a pid. (38712)
smtplib
~smtplib.SMTP and ~smtplib.SMTP_SSL now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Donghee Na in 39259.)
~smtplib.LMTP constructor now has an optional timeout parameter. (Contributed by Donghee Na in 39329.)
socket
The socket module now exports the ~socket.CAN_RAW_JOIN_FILTERS constant on Linux 4.1 and greater. (Contributed by Stefan Tatschner and Zackery Spytz in 25780.)
The socket module now supports the ~socket.CAN_J1939 protocol on platforms that support it. (Contributed by Karl Ding in 40291.)
The socket module now has the socket.send_fds and socket.recv_fds functions. (Contributed by Joannah Nanjekye, Shinya Okano and Victor Stinner in 28724.)
time
On AIX, ~time.thread_time is now implemented with thread_cputime() which has nanosecond resolution, rather than clock_gettime(CLOCK_THREAD_CPUTIME_ID) which has a resolution of 10 milliseconds. (Contributed by Batuhan Taskaya in 40192)
sys
Added a new sys.platlibdir attribute: name of the platform-specific library directory. It is used to build the path of standard library and the paths of installed extension modules. It is equal to "lib" on most platforms. 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 in 1294959.)
Previously, sys.stderr was block-buffered when non-interactive. Now stderr defaults to always being line-buffered. (Contributed by Jendrik Seipp in 13601.)
tracemalloc
Added tracemalloc.reset_peak to set the peak size of traced memory blocks to the current size, to measure the peak of specific pieces of code. (Contributed by Huon Wilson in 40630.)
typing
593 introduced an typing.Annotated type to decorate existing types with context-specific metadata and new include_extras parameter to typing.get_type_hints to access the metadata at runtime. (Contributed by Till Varoquaux and Konstantin Kashin.)
unicodedata
The Unicode database has been updated to version 13.0.0. (39926).
venv
The activation scripts provided by venv now all specify their prompt customization 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 default case), and one used __VENV_NAME__ instead. (Contributed by Brett Cannon in 37663.)
xml
White space characters within attributes are now preserved when serializing xml.etree.ElementTree to XML file. EOLNs are no longer normalized to "n". This is the result of discussion about how to interpret section 2.11 of XML spec. (Contributed by Mefistotelis in 39011.)
Optimizations
-
Optimized the idiom for assignment a temporary variable in comprehensions. Now
for y in [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 the outer scope.(Contributed by Serhiy Storchaka in
32856.) -
Optimized signal handling in multithreaded applications. If a thread different than the main thread gets a signal, the bytecode evaluation loop is no longer interrupted at each bytecode instruction to check for pending signals which cannot be handled. Only the main thread of the main interpreter can handle signals.
Previously, the bytecode evaluation loop was interrupted at each instruction until the main thread handles signals. (Contributed by Victor Stinner in
40010.) -
Optimized the
subprocessmodule on FreeBSD usingclosefrom(). (Contributed by Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak and Victor Stinner in38061.) -
PyLong_FromDoubleis now up to 1.87x faster for values that fit intolong. (Contributed by Sergey Fedoseev in37986.) -
A number of Python builtins (
range,tuple,set,frozenset,list,dict) are now sped up by using590vectorcall protocol. (Contributed by Donghee Na, Mark Shannon, Jeroen Demeyer and Petr Viktorin in37207.) -
Optimized
!set.difference_updatefor the case when the other set is much larger than the base set. (Suggested by Evgeny Kapun with code contributed by Michele Orrù in8425.) -
Python's small object allocator (
obmalloc.c) now allows (no more than) one empty arena to remain available for immediate reuse, without returning it to the OS. This prevents thrashing in simple loops where an arena could be created and destroyed anew on each iteration. (Contributed by Tim Peters in37257.) -
floor divisionof float operation now has a better performance. Also the message ofZeroDivisionErrorfor this operation is updated. (Contributed by Donghee Na in39434.) -
Decoding short ASCII strings with UTF-8 and ascii codecs is now about 15% faster. (Contributed by Inada Naoki in
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.1
Variable 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.8
Data 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.5
Data 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.5
Stack (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.4
Timing 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 timings in nanoseconds. The benchmarks were measured on an Intel® Core™ i7-4960HQ processor running the macOS 64-bit builds found at python.org.
Deprecated
-
The distutils
bdist_msicommand is now deprecated, usebdist_wheel(wheel packages) instead. (Contributed by Hugo van Kemenade in39586.) -
Currently
math.factorialacceptsfloatinstances with non-negative integer values (like5.0). It raises aValueErrorfor non-integral and negative floats. It is now deprecated. In future Python versions it will raise aTypeErrorfor all floats. (Contributed by Serhiy Storchaka in37315.) -
The
!parserand!symbolmodules are deprecated and will be removed in future versions of Python. For the majority of use cases, users can leverage the Abstract Syntax Tree (AST) generation and compilation stage, using theastmodule. -
The Public C API functions
!PyParser_SimpleParseStringFlags,!PyParser_SimpleParseStringFlagsFilename,!PyParser_SimpleParseFileFlagsand!PyNode_Compileare deprecated and will be removed in Python 3.10 together with the old parser. -
Using
NotImplementedin a boolean context has been deprecated, as it is almost exclusively the result of incorrect rich comparator implementations. It will be made aTypeErrorin a future version of Python. (Contributed by Josh Rosenberg in35712.) -
The
randommodule currently accepts any hashable type as a possible seed value. Unfortunately, some of those types are not guaranteed to have a deterministic hash value. After Python 3.9, the module will restrict its seeds toNone,int,float,str,bytes, andbytearray. -
Opening the
~gzip.GzipFilefile for writing without specifying the mode argument is deprecated. In future Python versions it will always be opened for reading by default. Specify the mode argument for opening it for writing and silencing a warning. (Contributed by Serhiy Storchaka in28286.) -
Deprecated the
split()method of!_tkinter.TkappTypein favour of thesplitlist()method which has more consistent and predictable behavior. (Contributed by Serhiy Storchaka in38371.) -
The explicit passing of coroutine objects to
asyncio.waithas been deprecated and will be removed in version 3.11. (Contributed by Yury Selivanov and Kyle Stanley in34790.) -
binhex4 and hexbin4 standards are now deprecated. The
!binhexmodule and the followingbinasciifunctions are now deprecated:!b2a_hqx,!a2b_hqx!rlecode_hqx,!rledecode_hqx
(Contributed by Victor Stinner in
39353.) -
astclassesslice,IndexandExtSliceare considered deprecated and will be removed in future Python versions.valueitself should be used instead ofIndex(value).Tuple(slices, Load())should be used instead ofExtSlice(slices). (Contributed by Serhiy Storchaka in34822.) -
astclassesSuite,Param,AugLoadandAugStoreare considered deprecated and will be removed in future Python versions. They were not generated by the parser and not accepted by the code generator in Python 3. (Contributed by Batuhan Taskaya in39639and39969and Serhiy Storchaka in39988.) -
The
!PyEval_InitThreadsand!PyEval_ThreadsInitializedfunctions are now deprecated and will be removed in Python 3.11. Calling!PyEval_InitThreadsnow does nothing. TheGILis initialized byPy_Initializesince Python 3.7. (Contributed by Victor Stinner in39877.) -
Passing
Noneas the first argument to theshlex.splitfunction has been deprecated. (Contributed by Zackery Spytz in33262.) -
!smtpd.MailmanProxyis now deprecated as it is unusable without an external module,mailman. (Contributed by Samuel Colvin in35800.) -
The
!lib2to3module now emits aPendingDeprecationWarning. Python 3.9 switched to a PEG parser (see617), and Python 3.10 may include new language syntax that is not parsable by lib2to3's LL(1) parser. The!lib2to3module may be removed from the standard library in a future Python version. Consider third-party alternatives such as LibCST or parso. (Contributed by Carl Meyer in40360.) -
The random parameter of
random.shufflehas been deprecated. (Contributed by Raymond Hettinger in40465)
Removed
- 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 extensions are not supported or not enabled by NNTP server administrators. Forxgtitle(), please use!nntplib.NNTP.descriptionsor!nntplib.NNTP.descriptioninstead. (Contributed by Donghee Na in39366.)array.array:tostring()andfromstring()methods have been removed. They were aliases totobytes()andfrombytes(), deprecated since Python 3.2. (Contributed by Victor Stinner in38916.)- The undocumented
sys.callstats()function has been removed. Since Python 3.7, it was deprecated and always returnedNone. It required a special build optionCALL_PROFILEwhich was already removed in Python 3.7. (Contributed by Victor Stinner in37414.) - The
sys.getcheckinterval()andsys.setcheckinterval()functions have been removed. They were deprecated since Python 3.2. Usesys.getswitchintervalandsys.setswitchintervalinstead. (Contributed by Victor Stinner in37392.) - The C function
PyImport_Cleanup()has been removed. It was documented as: "Empty the module table. For internal use only." (Contributed by Victor Stinner in36710.) _dummy_threadanddummy_threadingmodules have been removed. These modules were deprecated since Python 3.7 which requires threading support. (Contributed by Victor Stinner in37312.)aifc.openfp()alias toaifc.open(),sunau.openfp()alias tosunau.open(), andwave.openfp()alias towave.openhave been removed. They were deprecated since Python 3.7. (Contributed by Victor Stinner in37320.)- The
!isAlivemethod ofthreading.Threadhas been removed. It was deprecated since Python 3.8. Use~threading.Thread.is_aliveinstead. (Contributed by Donghee Na in37804.) - Methods
getchildren()andgetiterator()of classes~xml.etree.ElementTree.ElementTreeand~xml.etree.ElementTree.Elementin the~xml.etree.ElementTreemodule 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 in36543.) - The old
plistlibAPI has been removed, it was deprecated since Python 3.4. Use the~plistlib.load,~plistlib.loads,~plistlib.dump, and~plistlib.dumpsfunctions. Additionally, the use_builtin_types parameter was removed, standardbytesobjects are always used instead. (Contributed by Jon Janzen in36409.) - The C function
PyGen_NeedsFinalizinghas been removed. It was not documented, tested, or used anywhere within CPython after the implementation of442. Patch by Joannah Nanjekye. (Contributed by Joannah Nanjekye in15088) base64.encodestring()andbase64.decodestring(), aliases deprecated since Python 3.1, have been removed: usebase64.encodebytesandbase64.decodebytesinstead. (Contributed by Victor Stinner in39351.)fractions.gcd()function has been removed, it was deprecated since Python 3.5 (22486): usemath.gcdinstead. (Contributed by Victor Stinner in39350.)- The buffering parameter of
bz2.BZ2Filehas been removed. Since Python 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 in39357.) - The encoding parameter of
json.loadshas been removed. As of Python 3.1, it was deprecated and ignored; using it has emitted aDeprecationWarningsince Python 3.8. (Contributed by Inada Naoki in39377) with (await asyncio.lock):andwith (yield from asyncio.lock):statements are not longer supported, useasync with lockinstead. The same is correct forasyncio.Conditionandasyncio.Semaphore. (Contributed by Andrew Svetlov in34793.)- The
!sys.getcountsfunction, the-X showalloccountcommand line option and theshow_alloc_countfield of the C structurePyConfighave been removed. They required a special Python build by definingCOUNT_ALLOCSmacro. (Contributed by Victor Stinner in39489.) - The
_field_typesattribute of thetyping.NamedTupleclass has been removed. It was deprecated since Python 3.8. Use the__annotations__attribute instead. (Contributed by Serhiy Storchaka in40182.) - The
!symtable.SymbolTable.has_execmethod has been removed. It was deprecated since 2006, and only returningFalsewhen it's called. (Contributed by Batuhan Taskaya in40208) - The
!asyncio.Task.current_taskand!asyncio.Task.all_taskshave been removed. They were deprecated since Python 3.7 and you can useasyncio.current_taskandasyncio.all_tasksinstead. (Contributed by Rémi Lapeyre in40967) - The
unescape()method in thehtml.parser.HTMLParserclass has been removed (it was deprecated since Python 3.4).html.unescapeshould be used for converting character references to the corresponding unicode characters.
Porting to Python 3.9
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in the Python API
__import__andimportlib.util.resolve_namenow raiseImportErrorwhere it previously raisedValueError. Callers catching the specific exception type and supporting both Python 3.9 and earlier versions will need to catch both usingexcept (ImportError, ValueError):.- The
venvactivation scripts no longer special-case when__VENV_PROMPT__is set to"". - The
select.epoll.unregistermethod no longer ignores the~errno.EBADFerror. (Contributed by Victor Stinner in39239.) - The compresslevel parameter of
bz2.BZ2Filebecame keyword-only, since the buffering parameter has been removed. (Contributed by Victor Stinner in39357.) - Simplified AST for subscription. Simple indices will be represented by their value, extended slices will be represented as tuples.
Index(value)will return avalueitself,ExtSlice(slices)will returnTuple(slices, Load()). (Contributed by Serhiy Storchaka in34822.) - The
importlibmodule now ignores thePYTHONCASEOKenvironment variable when the-Eor-Icommand line options are being used. - The encoding parameter has been added to the classes
ftplib.FTPandftplib.FTP_TLSas a keyword-only parameter, and the default encoding is changed from Latin-1 to UTF-8 to follow2640. asyncio.loop.shutdown_default_executorhas been added to~asyncio.AbstractEventLoop, meaning alternative event loops that inherit from it should have this method defined. (Contributed by Kyle Stanley in34037.)- The constant values of future flags in the
__future__module is updated in order to prevent collision with compiler flags. PreviouslyPyCF_ALLOW_TOP_LEVEL_AWAITwas clashing withCO_FUTURE_DIVISION. (Contributed by Batuhan Taskaya in39562) array('u')now useswchar_tas C type instead ofPy_UNICODE. This change doesn't affect to its behavior becausePy_UNICODEis alias ofwchar_tsince Python 3.3. (Contributed by Inada Naoki in34538.)- The
logging.getLoggerAPI now returns the root logger when passed the name'root', whereas previously it returned a non-root logger named'root'. This could affect cases where user code explicitly wants a non-root logger named'root', or instantiates a logger usinglogging.getLogger(__name__)in some top-level module called'root.py'. (Contributed by Vinay Sajip in37742.) - Division handling of
~pathlib.PurePathnow returnsNotImplementedinstead of raising aTypeErrorwhen passed something other than an instance ofstror~pathlib.PurePath. This allows creating compatible classes that don't inherit from those mentioned types. (Contributed by Roger Aiudi in34775). - Starting with Python 3.9.5 the
ipaddressmodule no longer accepts any leading zeros in IPv4 address strings. Leading zeros are ambiguous and interpreted as octal notation by some libraries. For example the legacy functionsocket.inet_atontreats leading zeros as octal notatation. glibc implementation of modern~socket.inet_ptondoes not accept any leading zeros. (Contributed by Christian Heimes in36384). codecs.lookupnow normalizes the encoding name the same way asencodings.normalize_encoding, except thatcodecs.lookupalso converts the name to lower case. For example,"latex+latin1"encoding name is now normalized to"latex_latin1". (Contributed by Jordon Xu in37751.)
Changes in the C API
-
Instances of
heap-allocated types <heap-types>(such as those created withPyType_FromSpecand similar APIs) hold a reference to their type object since Python 3.8. As indicated in the "Changes in the C API" of Python 3.8, for the vast majority of cases, there should be no side effect but for types that have a custom~PyTypeObject.tp_traversefunction, ensure that all customtp_traversefunctions of heap-allocated types visit the object's type.Example:
int foo_traverse(PyObject *self, visitproc visit, 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_traverseof its base class (or another type), ensure thatPy_TYPE(self)is visited only once. Note that onlyheap type <heap-types>are expected to visit the type intp_traverse.For example, if your
tp_traversefunction 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(See
35810and40217for more information.) -
The functions
PyEval_CallObject,PyEval_CallFunction,PyEval_CallMethodandPyEval_CallObjectWithKeywordsare deprecated. UsePyObject_Calland its variants instead. (See more details in29548.)
CPython bytecode changes
-
The
!LOAD_ASSERTION_ERRORopcode was added for handling theassertstatement. Previously, the assert statement would not work correctly if theAssertionErrorexception was being shadowed. (Contributed by Zackery Spytz in34880.) -
The
COMPARE_OPopcode was split into four distinct instructions:COMPARE_OPfor rich comparisonsIS_OPfor 'is' and 'is not' testsCONTAINS_OPfor 'in' and 'not in' testsJUMP_IF_NOT_EXC_MATCHfor checking exceptions in 'try-except' statements.
(Contributed by Mark Shannon in
39156.)
Build Changes
- Added
--with-platlibdiroption to theconfigurescript: name of the platform-specific library directory, stored in the newsys.platlibdirattribute. Seesys.platlibdirattribute for more information. (Contributed by Jan Matějek, Matěj Cepl, Charalampos Stratakis and Victor Stinner in1294959.) - The
COUNT_ALLOCSspecial build macro has been removed. (Contributed by Victor Stinner in39489.) - On non-Windows platforms, the
!setenvand!unsetenvfunctions are now required to build Python. (Contributed by Victor Stinner in39395.) - On non-Windows platforms, creating
bdist_wininstinstallers is now officially unsupported. (See10945for more details.) - When building Python on macOS from source,
_tkinternow links with non-system Tcl and Tk frameworks if they are installed in/Library/Frameworks, as had been the case on older releases of macOS. If a macOS SDK is explicitly configured, by using--enable-universalsdkor-isysroot, only the SDK itself is searched. The default behavior can still be overridden with--with-tcltk-includesand--with-tcltk-libs. (Contributed by Ned Deily in34956.) - Python can now be built for Windows 10 ARM64. (Contributed by Steve Dower in
33125.) - Some individual tests are now skipped when
--pgois used. The tests in question increased the PGO task time significantly and likely didn't help improve optimization of the final executable. This speeds up the task by a factor of about 15x. Running the full unit test suite is slow. This change may result in a slightly less optimized build since not as many code branches will be executed. If you are willing to wait for the much slower build, the old behavior can be restored using./configure [..] PROFILE_TASK="-m test --pgo-extended". We make no guarantees as to which PGO task set produces a faster build. Users who care should run their own relevant benchmarks as results can depend on the environment, workload, and compiler tool chain. (See36044and37707for more details.)
C API Changes
New Features
-
573: AddedPyType_FromModuleAndSpecto associate a module with a class;PyType_GetModuleandPyType_GetModuleStateto retrieve the module and its state; andPyCMethodandMETH_METHODto allow a method to access the class it was defined in. (Contributed by Marcel Plch and Petr Viktorin in38787.) -
Added
PyFrame_GetCodefunction: get a frame code. AddedPyFrame_GetBackfunction: get the frame next outer frame. (Contributed by Victor Stinner in40421.) -
Added
PyFrame_GetLineNumberto the limited C API. (Contributed by Victor Stinner in40421.) -
Added
PyThreadState_GetInterpreterandPyInterpreterState_Getfunctions to get the interpreter. AddedPyThreadState_GetFramefunction to get the current frame of a Python thread state. AddedPyThreadState_GetIDfunction: get the unique identifier of a Python thread state. (Contributed by Victor Stinner in39947.) -
Added a new public
PyObject_CallNoArgsfunction to the C API, which calls a callable Python object without any arguments. It is the most efficient way to call a callable Python object without any argument. (Contributed by Victor Stinner in37194.) -
Changes in the limited C API (if
Py_LIMITED_APImacro is defined):- Provide
Py_EnterRecursiveCallandPy_LeaveRecursiveCallas regular functions for the limited API. Previously, there were defined as macros, but these macros didn't compile with the limited C API which cannot accessPyThreadState.recursion_depthfield (the structure is opaque in the limited C API). PyObject_INIT()andPyObject_INIT_VAR()become regular "opaque" function to hide implementation details.
(Contributed by Victor Stinner in
38644and39542.) - Provide
-
The
PyModule_AddTypefunction is added to help adding a type to a module. (Contributed by Donghee Na in40024.) -
Added the functions
PyObject_GC_IsTrackedandPyObject_GC_IsFinalizedto the public API to allow to query if Python objects are being currently tracked or have been already finalized by the garbage collector respectively. (Contributed by Pablo Galindo Salgado in40241.) -
Added
!_PyObject_FunctionStrto get a user-friendly string representation of a function-like object. (Patch by Jeroen Demeyer in37645.) -
Added
PyObject_CallOneArgfor calling an object with one positional argument (Patch by Jeroen Demeyer in37483.)
Porting to Python 3.9
-
PyInterpreterState.eval_frame(523) now requires a new mandatory tstate parameter (PyThreadState*). (Contributed by Victor Stinner in38500.) -
Extension modules:
~PyModuleDef.m_traverse,~PyModuleDef.m_clearand~PyModuleDef.m_freefunctions ofPyModuleDefare no longer called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed (Py_mod_execfunction). More precisely, these functions are not called if~PyModuleDef.m_sizeis greater than 0 and the module state (as returned byPyModule_GetState) isNULL.Extension modules without module state (
m_size <= 0) are not affected. -
If
Py_AddPendingCallis called in a subinterpreter, the function is now scheduled to be called from the subinterpreter, rather than being called from the main interpreter. Each subinterpreter now has its own list of scheduled calls. (Contributed by Victor Stinner in39984.) -
The Windows registry is no longer used to initialize
sys.pathwhen the-Eoption is used (ifPyConfig.use_environmentis set to0). This is significant when embedding Python on Windows. (Contributed by Zackery Spytz in8901.) -
The global variable
PyStructSequence_UnnamedFieldis now a constant and refers to a constant string. (Contributed by Serhiy Storchaka in38650.) -
The
!PyGC_Headstructure is now opaque. It is only defined in the internal C API (pycore_gc.h). (Contributed by Victor Stinner in40241.) -
The
Py_UNICODE_COPY,Py_UNICODE_FILL,PyUnicode_WSTR_LENGTH,!PyUnicode_FromUnicode,!PyUnicode_AsUnicode,_PyUnicode_AsUnicode, and!PyUnicode_AsUnicodeAndSizeare marked as deprecated in C. They have been deprecated by393since Python 3.3. (Contributed by Inada Naoki in36346.) -
The
Py_FatalErrorfunction is replaced with a macro which logs automatically the name of the current function, unless thePy_LIMITED_APImacro is defined. (Contributed by Victor Stinner in39882.) -
The vectorcall protocol now requires that the caller passes only strings as keyword names. (See
37540for more information.) -
Implementation details of a number of macros and functions are now hidden:
PyObject_IS_GCmacro was converted to a function.- The
!PyObject_NEWmacro becomes an alias to thePyObject_Newmacro, and the!PyObject_NEW_VARmacro becomes an alias to thePyObject_NewVarmacro. They no longer access directly thePyTypeObject.tp_basicsizemember. !PyObject_GET_WEAKREFS_LISTPTRmacro was converted to a function: the macro accessed directly thePyTypeObject.tp_weaklistoffsetmember.PyObject_CheckBuffermacro was converted to a function: the macro accessed directly thePyTypeObject.tp_as_buffermember.PyIndex_Checkis now always declared as an opaque function to hide implementation details: removed thePyIndex_Check()macro. The macro accessed directly thePyTypeObject.tp_as_numbermember.
(See
40170for more details.)
Removed
-
Excluded
PyFPE_START_PROTECT()andPyFPE_END_PROTECT()macros ofpyfpe.hfrom the limited C API. (Contributed by Victor Stinner in38835.) -
The
tp_printslot ofPyTypeObject <type-structs>has been removed. It was used for printing objects to files in Python 2.7 and before. Since Python 3.0, it has been ignored and unused. (Contributed by Jeroen Demeyer in36974.) -
Changes in the limited C API (if
Py_LIMITED_APImacro is defined):- Excluded the following functions from the limited C API:
PyThreadState_DeleteCurrent()(Contributed by Joannah Nanjekye in37878.)_Py_CheckRecursionLimit_Py_NewReference()_Py_ForgetReference()_PyTraceMalloc_NewReference()_Py_GetRefTotal()- The trashcan mechanism which never worked in the limited C API.
PyTrash_UNWIND_LEVELPy_TRASHCAN_BEGIN_CONDITIONPy_TRASHCAN_BEGINPy_TRASHCAN_ENDPy_TRASHCAN_SAFE_BEGINPy_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_REFSbuild)
(Contributed by Victor Stinner in
38644and39542.) - Excluded the following functions from the limited C API:
-
Removed
_PyRuntime.getframehook and removed_PyThreadState_GetFramemacro which was an alias to_PyRuntime.getframe. They were only exposed by the internal C API. Removed alsoPyThreadFrameGettertype. (Contributed by Victor Stinner in39946.) -
Removed the following functions from the C API. Call
PyGC_Collectexplicitly to clear all free lists. (Contributed by Inada Naoki and Victor Stinner in37340,38896and40428.)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 removed in Python 3.4.PyTuple_ClearFreeList()PyUnicode_ClearFreeList(): the Unicode free list has been removed in Python 3.3.
-
Removed
_PyUnicode_ClearStaticStrings()function. (Contributed by Victor Stinner in39465.) -
Removed
Py_UNICODE_MATCH. It has been deprecated by393, and broken since Python 3.3. ThePyUnicode_Tailmatchfunction can be used instead. (Contributed by Inada Naoki in36346.) -
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 in39372.)
Notable changes in Python 3.9.1
typing
The behavior of typing.Literal was changed to conform with 586 and to match the behavior of static type checkers specified in the PEP.
-
Literalnow de-duplicates parameters. -
Equality comparisons between
Literalobjects are now order independent. -
Literalcomparisons now respect types. For example,Literal[0] == Literal[False]previously evaluated toTrue. It is nowFalse. To support this change, the internally used type cache now supports differentiating types. -
Literalobjects will now raise aTypeErrorexception during equality comparisons if any of their parameters are nothashable. Note that declaringLiteralwith mutable parameters will not throw an error:>>> from typing import Literal >>> Literal[{0}] >>> Literal[{0}] == Literal[{False}] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set'
(Contributed by Yurii Karabas in 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 the ARM64 architecture). A new universal build variant, universal2, is now available to natively support both ARM64 and Intel 64 in one set of executables. Binaries can also now be built on current versions of macOS to be deployed on a range of older macOS versions (tested to 10.9) while making some newer OS functions and options conditionally available based on the operating system version in use at runtime ("weaklinking").
(Contributed by Ronald Oussoren and Lawrence D'Anna in 41100.)
Notable changes in Python 3.9.2
collections.abc
collections.abc.Callable generic now flattens type parameters, similar to what typing.Callable currently does. This means that collections.abc.Callable[[int, str], str] will have __args__ of (int, str, str); previously this was ([int, str], str). To allow this change, types.GenericAlias can now be subclassed, and a subclass will be returned when subscripting the collections.abc.Callable type. Code which accesses the arguments via typing.get_args or __args__ need to account for this change. A DeprecationWarning may be emitted for invalid forms of parameterizing collections.abc.Callable which may have passed silently in Python 3.9.1. This DeprecationWarning will become a TypeError in Python 3.10. (Contributed by Ken Jin in 42195.)
urllib.parse
Earlier Python versions allowed using both ; and & as query parameter separators in urllib.parse.parse_qs and urllib.parse.parse_qsl. Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects !cgi.parse and !cgi.parse_multipart as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in 42967.)
Notable changes in Python 3.9.3
A security fix alters the ftplib.FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel. We reuse the ftp server IP address instead. For unusual code requiring the old behavior, set a trust_server_pasv_ipv4_address attribute on your FTP instance to True. (See 87451)
Notable changes in Python 3.9.5
urllib.parse
The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates 3986, ASCII newline \n, \r and tab \t characters are stripped from the URL by the parser in urllib.parse preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (See 88048)
Notable security feature in 3.9.14
Converting between int and str in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for 2020-10735. This limit can be configured or disabled by environment variable, command line flag, or sys APIs. See the integer string conversion length limitation <int_max_str_digits> documentation. The default limit is 4300 digits in string form.
Notable changes in 3.9.17
tarfile
- The extraction methods in
tarfile, andshutil.unpack_archive, have a new a filter argument that allows limiting tar features than may be surprising or dangerous, such as creating files outside the destination directory. Seetarfile-extraction-filterfor details. In Python 3.12, use without the filter argument will show aDeprecationWarning. In Python 3.14, the default will switch to'data'. (Contributed by Petr Viktorin in706.)
changelog
Changelog
../build/NEWS
What's New in Python
The "What's New in Python" series of essays takes tours through the most important changes between major Python versions. They are a "must read" for anyone wishing to stay up-to-date after a new release.
3.16.rst 3.15.rst 3.14.rst 3.13.rst 3.12.rst 3.11.rst 3.10.rst 3.9.rst 3.8.rst 3.7.rst 3.6.rst 3.5.rst 3.4.rst 3.3.rst 3.2.rst 3.1.rst 3.0.rst 2.7.rst 2.6.rst 2.5.rst 2.4.rst 2.3.rst 2.2.rst 2.1.rst 2.0.rst
The "Changelog" is an HTML version of the file built<blurb> from the contents of the Misc/NEWS.d directory tree, which contains all nontrivial changes to Python for the current version.
changelog.rst