https://docs.python.org/3/whatsnew/3.2.html
- PEP 384: Defining a Stable ABI
- PEP 389:
Argparse
Command Line Parsing Module - PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The
concurrent.futures
module - PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged
.so
Files - PEP 3333: Python Web Server Gateway Interface v1.0.1
- String formatting for
format()
andstr.format()
gained 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, andDecimal
, causing the output to always have a decimal point even when no digits follow it. - There is also a new
str.format_map()
method that extends the capabilities of the existingstr.format()
method by accepting arbitrary mapping objects. This new method makes it possible to use string formatting with any of Python's many dictionary-like objects such asdefaultdict
,Shelf
,ConfigParser
, ordbm
. It is also useful with customdict
subclasses that normalize keys before look-up or that supply a__missing__()
method for unknown keys. - 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.flags
attribute. - The
hasattr()
function works by callinggetattr()
and detecting whether an exception is raised. This technique allows it to detect methods created dynamically by__getattr__()
or__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 catchAttributeError
and let other exceptions pass through. - The
str()
of a float or complex number is now the same as itsrepr()
. Previously, thestr()
form was shorter but that just caused confusion and is no longer needed now that the shortest possiblerepr()
is displayed by default. -
memoryview
objects now have arelease()
method 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. - Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block. This is now allowed.
- The internal
structsequence
tool now creates subclasses of tuple. This means that C structures like those returned byos.stat()
,time.gmtime()
, andsys.version_info
now work like a named tuple and 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. - Warnings are now easier to control using the
PYTHONWARNINGS
environment variable as an alternative to using-W
at the command line. - 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 thewarnings
module, or on the command line. AResourceWarning
is issued at interpreter shutdown if thegc.garbage
list isn't empty, and ifgc.DEBUG_UNCOLLECTABLE
is set, all uncollectable objects are printed. This is meant to make the programmer aware that their code contains object finalization issues. AResourceWarning
is also issued when a file object is 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. -
range
objects now supportindex
andcount
methods. This is part of an effort to make more objects fully implement thecollections.Sequence
abstract base class. As a result, the language will have a more uniform API. In addition,range
objects now support slicing and negative indices, even with values larger thansys.maxsize
. This makesrange
more interoperable with lists. - The
callable()
builtin function from Py2.x was resurrected. It provides a concise, readable alternative to using an abstract base class in an expression likeisinstance(x, collections.Callable)
. - 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.
-
email
- New functions
message_from_bytes()
andmessage_from_binary_file()
, and new classesBytesFeedParser
andBytesParser
allow binary message data to be parsed into model objects. - Given bytes input to the model,
get_payload()
will by default decode a message body that has aContent-Transfer-Encoding
of 8bit using the charset specified in the MIME headers and return the resulting string. - Given bytes input to the model, Generator will convert message bodies that have a
Content-Transfer-Encoding
of 8bit to instead have a 7bitContent-Transfer-Encoding
. Headers with unencoded non-ASCII bytes are deemed to be RFC 2047-encoded using the unknown-8bit character set. - A new class
BytesGenerator
produces 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-Encoding
of 8bit. - The
smtplib
SMTP class now accepts a byte string for themsg
argument to thesendmail()
method, and a new method,send_message()
accepts aMessage
object and can optionally obtain thefrom_addr
andto_addrs
addresses directly from the object.
- New functions
- The
xml.etree.ElementTree
package and itsxml.etree.cElementTree
counterpart have been updated to version 1.3. -
functools
- The
functools
module includes a new decorator for caching function calls.functools.lru_cache()
can save repeated queries to an external resource whenever the results are expected to be the same. - The
functools.wraps()
decorator now adds a__wrapped__
attribute pointing to the original callable function. This allows wrapped functions to be introspected. It also copies__annotations__
if defined. And now it also gracefully skips over missing attributes such as__doc__
which might not be defined for the wrapped callable. - To help write classes with rich comparison methods, a new decorator
functools.total_ordering()
will use existing equality and inequality methods to fill in the remaining methods. - To aid in porting programs from Python 2, the
functools.cmp_to_key()
function converts an old-style comparison function to modern key function.
- The
- The
itertools
module has anew accumulate()
function modeled on APL's scan operator and Numpy'saccumulate
function. -
collections
- The
collections.Counter
class now has two forms of in-place subtraction, the existing-=
operator for saturating subtraction and the newsubtract()
method 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. - The
collections.OrderedDict
class has a new methodmove_to_end()
which 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 withod[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. - The
collections.deque
class grew two new methodscount()
andreverse()
that make them more substitutable forlist
objects.
- The
-
threading
-
datetime
andtime
- The
datetime
module has a new typetimezone
that implements thetzinfo
interface by returning a fixed UTC offset and timezone name. This makes it easier to create timezone-awaredatetime
objects. - Also,
timedelta
objects can now be multiplied byfloat
and divided byfloat
andint
objects. Andtimedelta
objects can now divide one another. - The
datetime.date.strftime()
method 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 isTrue
which means that for a two-digit year, the century is guessed according to the POSIX rules governing the%y
strptime
format. Starting with Py3.2, use of the century guessing heuristic will emit aDeprecationWarning
. Instead, it is recommended thattime.accept2dyear
be set toFalse
so that large date ranges can be used without guesswork. Several functions now have significantly expanded date ranges. Whentime.accept2dyear
is false, thetime.asctime()
function will accept any year that fits in a Cint
, while thetime.mktime()
andtime.strftime()
functions will accept the full range supported by the corresponding operating system functions.
- The
- math
- The
isfinite()
function provides a reliable and fast way to detect special values. It returnsTrue
for regular numbers andFalse
forNan
orInfinity
. - The
expm1()
function computese**x-1
for small values ofx
without incurring the loss of precision that usually accompanies the subtraction of nearly equal quantities. - The
erf()
function computes a probability integral or Gaussian error function. The complementary error function,erfc()
, is1 - erf(x)
: - The
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 algamma()
function for computing the natural logarithm of the gamma function.
- The
-
abc
-
io
-
reprlib
-
logging
-
csv
-
contextlib
-
decimal and fractions
-
ftp
-
popen
-
select
-
gzip and zipfile
-
tarfile
-
hashlib
-
ast
-
os
-
shutil
-
sqlite3
-
html
-
socket
-
ssl
-
nntp
-
certificates
-
imaplib
-
http.client
-
unittest
-
random
-
poplib
-
asyncore
-
tempfile
-
inspect
-
pydoc
-
dis
-
dbm
-
ctypes
- A new type,
ctypes.c_ssize_t
represents the Cssize_t
datatype.
- A new type,
-
site
-
sysconfig
-
pdb
-
configparser
-
urllib.parse
-
mailbox
-
turtledemo
- The
configparser
module has a number of clean-ups. - The
nntplib
module was reworked extensively, meaning that its APIs are often incompatible with the 3.1 APIs. -
bytearray
objects can no longer be used as filenames; instead, they should be converted tobytes
. - The
array.tostring()
andarray.fromstring()
have been renamed toarray.tobytes()
andarray.frombytes()
for clarity. The old names have been deprecated. (See issue 8990.) - The
sys.setfilesystemencoding()
function was removed because it had a flawed design. - The
random.seed()
function 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.maketrans()
function has been removed in favor of the static methodsbytes.maketrans()
andbytearray.maketrans()
. This change solves the confusion around which types were supported by the string module. Now,str
,bytes
, andbytearray
each have their ownmaketrans
andtranslate
methods with intermediate translation tables of the appropriate type. - The previously deprecated
contextlib.nested()
function has been removed in favor of a plainwith
statement 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. -
struct.pack()
now only allows bytes for the s string 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 asstruct.pack('<6sHHBBB', 'GIF87a', x, y)
should be rewritten with to use bytes instead of text,struct.pack('<6sHHBBB', b'GIF87a', x, y)
. - The
xml.etree.ElementTree
class now raises anxml.etree.ElementTree.ParseError
when a parse fails. Previously it raised anxml.parsers.expat.ExpatError
. - The new, longer
str()
value on floats may breakdoctest
s which rely on the old output format. - In
subprocess.Popen
, the default value forclose_fds
is nowTrue
under Unix; under Windows, it isTrue
if the three standard streams are set toNone
,False
otherwise. Previously,close_fds
was alwaysFalse
by 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.request
andhttp.client
. Such support is still present on the server side (inhttp.server
). - SSL sockets in timeout mode now raise
socket.timeout
when a timeout occurs, rather than a genericSSLError
. - Due to security risks,
asyncore.handle_accept()
has been deprecated, and a new function,asyncore.handle_accepted()
, was added to replace it.