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.
New syntax features:
New library modules:
New built-in features:
Implementation improvements:
Significantly Improved Library Modules:
Security improvements:
Please read on for a comprehensive list of user-facing changes..
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 PEP 420).
(Contributed by Stefan Krah in issue 10181)).
Changes introduced by PEP 393 are the following:
The storage of Unicode strings now depends on the highest codepoint in the string: issue 3561).
See also
Launcher documentation: Python Launcher for Windows
Installer PATH modification: Finding the Python executable>'
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..
issue 2377 - Replace __import__ w/ importlib.__import__ issue 13959 - Re-implement parts of imp in pure Python issue 14605 - Make import machinery explicit issue)
Some smaller changes made to the core Python language are:
Added support for Unicode name aliases and named sequences. Both unicodedata.lookup() and '\N{...}' now resolve name aliases, and unicodedata.lookup() resolves named sequences too.
(Contributed by Ezio Melotti in issue 12753)
Unicode database updated to UCD version 6.1.0
Equality comparisons on range() objects now return a result reflecting the equality of the underlying sequences generated by those range objects. (issue 13201)
The count(), find(), rfind(), index() and rindex() methods of bytes and bytearray objects now accept an integer between 0 and 255 as their first argument.
(Contributed by Petri Lehtinen in issue 12170)
The rjust(), ljust(), and center() methods of bytes and bytearray now accept a bytearray for the fill argument. (Contributed by Petri Lehtinen in issue 12380.)
New methods have been added to list and bytearray: copy() and clear() (issue 10516). Consequently, MutableSequence now also defines a clear() method (issue 11388).
Raw bytes literals can now be written rb"..." as well as br"...".
(Contributed by Antoine Pitrou in issue 13748.)
dict.setdefault() now does only one lookup for the given key, making it atomic when used with built-in types.
(Contributed by Filip Gruszczyński in issue 13521.)
The error messages produced when a function call does not match the function signature have been significantly improved.
(Contributed by Benjamin Peterson.) issue 9260.)
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 PEP 3144)
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 issue 6715)
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.abstractproperty has been deprecated, use property with abc.abstractmethod() instead.
- abc.abstractclassmethod has been deprecated, use classmethod with abc.abstractmethod() instead.
- abc.abstractstaticmethod has been deprecated, use staticmethod with abc.abstractmethod() instead.
(Contributed by Darren Dale in issue 11610)
abc.ABCMeta.register() now returns the registered subclass, which means it can now be used as a class decorator (issue 10868).
The array module supports the long long type using q and Q type codes.
(Contributed by Oren Tirosh and Hirokazu Yamamoto in issue 1172711)
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 issue 13641.)
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 issue 13637.)
The bz2 module has been rewritten from scratch. In the process, several new features have been added:
New bz2.open() function: open a bzip2-compressed file in binary or text mode.
bz2.BZ2File can now read from and write to arbitrary file-like objects, by means of its constructor’s fileobj argument.
(Contributed by Nadeem Vawda in issue 5863)
bz2.BZ2File and bz2.decompress() can now decompress multi-stream inputs (such as those produced by the pbzip2 tool). bz2.BZ2File can now also be used to create this type of file, using the 'a' (append) mode.
(Contributed by Nir Aides in issue 1625)
bz2.BZ2File now implements all of the io.BufferedIOBase API, except for the detach() and truncate() methods. (issue:
$ ./python -q >>>.
Addition of a new ChainMap class to allow treating a number of mappings as a single unit. (Written by Raymond Hettinger for issue 11089, made public in issue 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. (issue 11085)
The Counter class now supports the unary + and - operators, as well as the in-place operators +=, -=, |=, and &=. (Contributed by Raymond Hettinger in issue 13121.)).
Addition of salt and modular crypt format (hashing method) and the mksalt() function to the crypt module.
- If the curses module 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-8 to encode Unicode strings.
- curses.window has a new curses.window.encoding attribute.
- The curses.window class has a new get_wch() method to get a wide character
- The curses module has a new unget_wch() function to push a wide character so the next get_wch() will return it
(Contributed by Iñigo Serna in issue 6755)
- Equality comparisons between naive and aware datetime instances now return False instead of raising TypeError (issue 15006).
- New datetime.datetime.timestamp() method: Return POSIX timestamp corresponding to the datetime instance.
- The datetime.datetime.strftime() method supports formatting years older than 1000.
- The datetime.datetime.astimezone() method can now be called without arguments to convert datetime instance to the system timezone..
The C module has the following context limits, depending on the machine architecture:
In the context templates (DefaultContext, BasicContext and ExtendedContext) the magnitude of Emax and Emin has changed to 999999.
The Decimal constructor 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 InvalidOperation and traps always refer to the same MutableMapping that the context was initialized with. If a new signal dictionary is assigned, flags and traps are updated with the new values, but they do not reference the RHS dictionary.
Pickling a Context produces a different output in order to have a common interchange format for the Python and C versions.
The order of arguments in the Context constructor has been changed to match the order displayed by repr().
The watchexp parameter in the quantize() method is deprecated. Message, EmailPolicy, email.header if the offset is -0000.
- localtime(): With no argument, returns the current local time as an aware datetime using the local timezone. Given an aware datetime, converts it into an aware datetime using the local timezone.
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 issue 13227.)
It is now possible to register callbacks invoked by the garbage collector before and after collection using the new callbacks list.
A new compare_digest() function has been added to prevent side channel attacks on digests through timing analysis. (Contributed by Nick Coghlan and Christian Heimes in issue 15061)
http.server.BaseHTTPRequestHandler now buffers the headers and writes them all at once when end_headers() is called. A new method flush_headers() can be used to directly manage when the accumlated headers are sent. (Contributed by Andrew Schaaf in issue 3709.)
http.server now produces valid HTML 4.01 strict output. (Contributed by Ezio Melotti in issue 13295.)
http.client.HTTPResponse now has a readinto() method, which means it can be used as a io.RawIOBase class. (Contributed by John Kuhn in issue 13464.) issue 15114, and issue 14538, issue 13993, issue 13960, issue 13358, issue 1745761, issue 755670, issue 13357, issue 12629, issue 1200313, issue 670664, issue 13273, issue 12888, issue issue 11113 and issue 15156)
The IMAP4_SSL constructor now accepts an SSLContext parameter to control parameters of the secure channel.
(Contributed by Sijin Joseph in issue 8808) issue 13062)
A new 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 issue 15153) issue.
accumulate() now takes an optional func argument for providing a user-supplied binary function. deamons it is required while for others it is passed through to the log.
The math module has a new function, log2(), which returns the base-2 logarithm of x.
(Written by Mark Dickinson in issue 11888).
The 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 issue 12021.)
The new multiprocessing.connection.wait() function allows to poll multiple objects (such as connections, sockets and pipes) with a timeout. (Contributed by Richard Oudkerk in issue 12328.)
multiprocessing.Connection objects can now be transferred over multiprocessing connections. (Contributed by Richard Oudkerk in issue 4892.)
multiprocessing.Process now accepts a daemon keyword argument to override the default behavior of inheriting the daemon flag from the parent process (issue 6064).
New attribute issue 12708.)
The nntplib.NNTP class now supports the context manager issue 9795)
The os module has a new pipe2() function that makes it possible to create a pipe with O_CLOEXEC or O_NONBLOCK flags set atomically. This is especially useful to avoid race conditions in multi-threaded programs.
The os module has a new sendfile() function which provides an efficent  issue (issue 4761, issue 10755 and issue 14626).
access() accepts an effective_ids keyword 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 supports_effective_ids set.
The os module has two new functions: getpriority() and setpriority(). They can be used to get or set process niceness/priority in a fashion similar to os.nice() but extended to all processes instead of just the current one.
(Patch submitted by Giampaolo Rodolà in issue 10784.)
The new os.replace() function allows cross-platform renaming of a file with overwriting the destination. With os.rename(), an existing destination file is overwritten under POSIX, but raises an error under Windows. (Contributed by Antoine Pitrou in issue issue 14127.)
The new os.get_terminal_size() function queries the size of the terminal attached to a file descriptor. See also shutil.get_terminal_size(). (Contributed by Zbigniew Jędrzejewski-Szmek in issue 13609.)
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 issue 14210)
pickle.Pickler objects now have an optional dispatch_table attribute allowing to set per-pickler reduction functions.
(Contributed by Richard Oudkerk in issue 14166.)
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.
str regular expressions now support \u and \U escapes.
(Contributed by Serhiy Storchaka in issue 3665.)
Solaris and derivatives platforms have a new class select.devpoll for high performance asynchronous sockets via /dev/poll. (Contributed by Jesús Cea Avión in issue 6397.)
The previously undocumented helper function quote from the pipes modules has been moved to the shlex module and documented. quote() properly escapes all characters in a string that might be otherwise given special meaning by the shell.. issue 8739)
The SMTP, SMTP_SSL, and 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 issue 11281.)
SMTP now supports the context manager protocol, allowing an SMTP instance to be used in a with statement. (Contributed by Giampaolo Rodolà in issue 11289.)
The SMTP_SSL constructor and the starttls() method now accept an SSLContext parameter to control parameters of the secure channel. (Contributed by Kasun Herath in issue 8809)
The socket class now exposes additional methods to process ancillary data when supported by the underlying platform:
(Contributed by David Watson in issue 6560, based on an earlier patch by Heiko Wundram)
The socket class now supports the PF_CAN protocol family (), on Linux ().
(Contributed by Matthias Fuchs, updated by Tiago Gonçalves in issue 10141)
The socket class now supports the PF_RDS protocol family ( and).
The socket class now supports the PF_SYSTEM protocol family on OS X. (Contributed by Michael Goderbauer in issue 13777.)
New function sethostname() allows the hostname to be set on unix systems if the calling process has sufficient privileges. (Contributed by Ross Lagerwall in issue 10866.)
BaseServer now has an overridable method service_actions() that is called by the serve_forever() method in the service loop. ForkingMixIn now uses this to clean up zombie child proceses. (Contributed by Justin Warkentin in issue 11109.)
New sqlite3.Connection method set_trace_callback() can be used to capture a trace of all sql commands processed by sqlite. (Contributed by Torsten Landschoff in issue 11688.)
The ssl module has two new random generation functions:
(Contributed by Victor Stinner in issue 12049)
The ssl module now exposes a finer-grained exception hierarchy in order to make it easier to inspect the various kinds of errors. (Contributed by Antoine Pitrou in issue 11183)
load_cert_chain() now accepts a password argument to be used if the private key is encrypted. (Contributed by Adam Simpkins in issue 12803)
Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is now supported through the load_dh_params() and set_ecdh_curve() methods. (Contributed by Antoine Pitrou in issue 13626 and issue 13627)
SSL sockets have a new get_channel_binding() method allowing the implementation of certain authentication mechanisms such as SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in issue 12551)
You can query the SSL compression algorithm used by an SSL socket, thanks to its new compression() method. The new attribute OP_NO_COMPRESSION can be used to disable compression. (Contributed by Antoine Pitrou in issue 13634)
Support has been added for the Next Procotol Negotiation extension using the ssl.SSLContext.set_npn_protocols() method. (Contributed by Colin Marc in issue 14204)
SSL errors can now be introspected more easily thanks to library and reason attributes. (Contributed by Antoine Pitrou in issue 14837)
The get_server_certificate() function now supports IPv6. (Contributed by Charles-François Natali in issue 11811.)
New attribute OP_CIPHER_SERVER_PREFERENCE allows setting SSLv3 server sockets to use the server’s cipher ordering preference rather than the client’s (issue 13635).
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 issue 14807)
The struct module now supports ssize_t and size_t via the new codes n and N, respectively. (Contributed by Antoine Pitrou in issue 3163.)
Command strings can now be bytes objects on posix platforms. (Contributed by Victor Stinner in issue 8513.)
A new constant DEVNULL allows suppressing output in a platform-independent fashion. (Contributed by Ross Lagerwall in issue 5870.)
The sys module has a new thread_info struct sequence holding informations about the thread implementation (issue 11223).
tarfile now supports lzma encoding via the lzma module. (Contributed by Lars Gustäbel in issue 5689.)
tempfile.SpooledTemporaryFile‘s truncate() method now accepts a size parameter. (Contributed by Ryan Kelly in issue 9957.)
The textwrap module has a new indent() that makes it straightforward to add a common prefix to selected lines in a block of text (issue 13857). issue 10968).
The threading.Thread constructor now accepts a daemon keyword argument to override the default behavior of inheriting the deamon flag value from the parent thread (issue.
The PEP 418 added new functions to the time module:
Other new functions:
To improve cross platform consistency, 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.
Add a new types.MappingProxyType class: Read-only proxy of a mapping. (issue 14386)
The new functions types.new_class and types.prepare_class provide support for PEP 3115 compliant dynamic type creation. (issue 14588)
assertRaises(), assertRaisesRegex(), assertWarns(), and assertWarnsRegex() now accept a keyword argument msg when used as context managers. (Contributed by Ezio Melotti and Winston Ewert in issue 10775)
unittest.TestCase.run() now returns the TestResult object.
The Request class, now accepts a method argument used by get_method() to determine what HTTP method should be used. For example, this will send a 'HEAD' request:
>>> urlopen(Request('', method='HEAD')) issue 13620, the latter by Matthias Klose in issue 14493).
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 issue 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 issue 12306.)
Major performance enhancements have been added:
Thanks to PEP 393, some operations on Unicode strings have been optimized:
UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster.
(contributed by Serhiy Storchaka, issue 14624, issue 14738 and issue 15026.)
Changes to Python’s build process and to the C API include:.
The Py_UNICODE has been deprecated by PEP 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:
Functions and macros manipulating Py_UNICODE* strings:
Encoders:
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.
This section lists previously described changes and other bugfixes that may require changes to your code.
In the course of changes to the buffer API the undocumented smalltable member of the Py_buffer structure has been removed and the layout of the PyMemoryViewObject has changed.
All extensions relying on the relevant parts in memoryobject.h or object.h must be rebuilt.
Due to PEP 393, the Py_UNICODE type upon failure.
As a negative value for the level argument to __import__() is no longer valid, the same now holds for PyImport_ImportModuleLevel(). This also means that the value of level used by PyImport_ImportModuleEx() is now 0 instead of -1.
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.so and xxxmodule.cpython-*.so are no longer recognized as implementing the xxx module. If you had been generating such files, you have to switch to the other spellings (i.e., remove the module string from the file names).
(implemented in issue 14040.)
The -Q command-line flag and related artifacts have been removed. Code checking sys.flags.division_warning will need updating.
(issue 10998, contributed by Éric Araujo.)
When python is started with -S, import site will no longer add site-specific paths to the module search paths. In previous versions, it did.
(issue 11591, contributed by Carl Meyer with editions by Éric Araujo.)