Spaces:
Running on Zero
A newer version of the Gradio SDK is available: 6.22.0
What's New in Python 2.6 {#whats-new-in-2.6}
Author : A.M. Kuchling (amk at amk.ca)
This article explains the new features in Python 2.6, released on October 1, 2008. The release schedule is described in 361{.interpreted-text role="pep"}.
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{.interpreted-text role="mod"} module and a !-3{.interpreted-text role="option"} 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{.interpreted-text role="mod"} and json{.interpreted-text role="mod"} 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
__complex__{.interpreted-text role="meth"} method for converting objects to a complex number. - Alternate syntax for catching exceptions:
except TypeError as exc. - The addition of
functools.reduce{.interpreted-text role="func"} as a synonym for the built-inreduce{.interpreted-text role="func"} function.
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{.interpreted-text role="func"} have simply been added to Python 2.6, but existing builtins haven't been changed; instead, the !future_builtins{.interpreted-text role="mod"} 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{.interpreted-text role="option"}, 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{.interpreted-text role="data"}, and to C extension code as !Py_Py3kWarningFlag{.interpreted-text role="c:data"}.
::: seealso
The 3xxx series of PEPs, which contains proposals for Python 3.0. 3000{.interpreted-text role="pep"} describes the development process for Python 3.0. Start with 3100{.interpreted-text role="pep"} 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.
::: seealso
: The Python bug tracker.
: 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.
::: seealso
: Describes how to write for Python's documentation.
: Documentation and code for the Sphinx toolchain.
: The underlying reStructuredText parser and toolset. :::
PEP 343: The 'with' statement {#pep-0343}
The previous version, Python 2.5, added the 'with{.interpreted-text role="keyword"}' 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{.interpreted-text role="keyword"} 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{.interpreted-text role="keyword"}' statement from Python 2.5, you can skip this section.
The 'with{.interpreted-text role="keyword"}' 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{.interpreted-text role="keyword"}' 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__{.interpreted-text role="meth"} and ~object.__exit__{.interpreted-text role="meth"} methods).
The object's ~object.__enter__{.interpreted-text role="meth"} 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__{.interpreted-text role="meth"} 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{.interpreted-text role="keyword"}' 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{.interpreted-text role="keyword"} loop raised an exception part-way through the block.
:::: note ::: title Note :::
In this case, f is the same object created by open{.interpreted-text role="func"}, because ~object.__enter__{.interpreted-text role="meth"} returns self.
::::
The threading{.interpreted-text role="mod"} module's locks and condition variables also support the 'with{.interpreted-text role="keyword"}' 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{.interpreted-text role="func"} function in the decimal{.interpreted-text role="mod"} 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 {#new-26-context-managers}
Under the hood, the 'with{.interpreted-text role="keyword"}' statement is fairly complicated. Most people will only use '!with{.interpreted-text role="keyword"}' 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__{.interpreted-text role="meth"} and~object.__exit__{.interpreted-text role="meth"} methods. - The context manager's
~object.__enter__{.interpreted-text role="meth"} 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__{.interpreted-text role="meth"} method is called with three arguments, the exception details (type, value, traceback, the same values returned bysys.exc_info{.interpreted-text role="func"}, 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{.interpreted-text role="keyword"}' statement will never realize anything went wrong. - If BLOCK didn't raise an exception, the
~object.__exit__{.interpreted-text role="meth"} 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{.interpreted-text role="class"} 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__{.interpreted-text role="meth"} 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{.interpreted-text role="keyword"}' 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__{.interpreted-text role="meth"} 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{.interpreted-text role="keyword"} 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 {#new-module-contextlib}
The contextlib{.interpreted-text role="mod"} module provides some functions and a decorator that are useful when writing objects for use with the 'with{.interpreted-text role="keyword"}' statement.
The decorator is called ~contextlib.contextmanager{.interpreted-text role="func"}, 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{.interpreted-text role="keyword"} will be executed as the ~object.__enter__{.interpreted-text role="meth"} method, and the value yielded will be the method's return value that will get bound to the variable in the 'with{.interpreted-text role="keyword"}' statement's !as{.interpreted-text role="keyword"} clause, if any. The code after the !yield{.interpreted-text role="keyword"} will be executed in the ~object.__exit__{.interpreted-text role="meth"} method. Any exception raised in the block will be raised by the !yield{.interpreted-text role="keyword"} 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{.interpreted-text role="mod"} module also has a nested(mgr1, mgr2, ...) function that combines a number of context managers so you don't need to write nested 'with{.interpreted-text role="keyword"}' statements. In this example, the single '!with{.interpreted-text role="keyword"}' 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{.interpreted-text role="func"} 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)
::: seealso
343{.interpreted-text role="pep"} - 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{.interpreted-text role="keyword"}' statement, which can be helpful in learning how the statement works.
The documentation for the contextlib{.interpreted-text role="mod"} module.
:::
PEP 366: Explicit Relative Imports From a Main Module {#pep-0366}
Python's -m{.interpreted-text role="option"} 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__{.interpreted-text role="attr"} attribute. When this attribute is present, relative imports will be relative to the value of this attribute instead of the ~module.__name__{.interpreted-text role="attr"} attribute.
PEP 302-style importers can then set ~module.__package__{.interpreted-text role="attr"} as necessary. The runpy{.interpreted-text role="mod"} module that implements the -m{.interpreted-text role="option"} 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 {#pep-0370}
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/{.interpreted-text role="file"} - Windows:
%APPDATA%/Python{.interpreted-text role="file"}
Within this directory, there will be version-specific subdirectories, such as lib/python2.6/site-packages{.interpreted-text role="file"} on Unix/Mac OS and Python26/site-packages{.interpreted-text role="file"} on Windows.
If you don't like the default directory, it can be overridden by an environment variable. PYTHONUSERBASE{.interpreted-text role="envvar"} 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{.interpreted-text role="envvar"} environment variable. You can also modify the site.py{.interpreted-text role="file"} file for your Python installation.
The feature can be disabled entirely by running Python with the -s{.interpreted-text role="option"} option or setting the PYTHONNOUSERSITE{.interpreted-text role="envvar"} environment variable.
::: seealso
370{.interpreted-text role="pep"} - Per-user site-packages Directory
: PEP written and implemented by Christian Heimes. :::
PEP 371: The multiprocessing Package {#pep-0371}
The new multiprocessing{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} module started out as an exact emulation of the threading{.interpreted-text role="mod"} 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{.interpreted-text role="class"}, which is passed a callable object and a collection of arguments. The ~multiprocessing.Process.start{.interpreted-text role="meth"} method sets the callable running in a subprocess, after which you can call the ~multiprocessing.Process.is_alive{.interpreted-text role="meth"} method to check whether the subprocess is still running and the ~multiprocessing.Process.join{.interpreted-text role="meth"} 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{.interpreted-text role="class"} is used to communicate the result of the factorial. The ~queue.Queue{.interpreted-text role="class"} 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{.interpreted-text role="class"}, 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{.interpreted-text role="class"} and ~multiprocessing.Manager{.interpreted-text role="class"}, provide higher-level interfaces. ~multiprocessing.pool.Pool{.interpreted-text role="class"} will create a fixed number of worker processes, and requests can then be distributed to the workers by calling ~multiprocessing.pool.Pool.apply{.interpreted-text role="meth"} or ~multiprocessing.pool.Pool.apply_async{.interpreted-text role="meth"} to add a single request, and ~multiprocessing.pool.Pool.map{.interpreted-text role="meth"} or ~multiprocessing.pool.Pool.map_async{.interpreted-text role="meth"} to add a number of requests. The following code uses a ~multiprocessing.pool.Pool{.interpreted-text role="class"} 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{.interpreted-text role="class"} 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{.interpreted-text role="meth"} 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{.interpreted-text role="class"}'s methods also include ~multiprocessing.managers.SyncManager.Lock{.interpreted-text role="meth"}, ~multiprocessing.managers.SyncManager.RLock{.interpreted-text role="meth"}, and ~multiprocessing.managers.SyncManager.Semaphore{.interpreted-text role="meth"} 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...
::: seealso
The documentation for the multiprocessing{.interpreted-text role="mod"} module.
371{.interpreted-text role="pep"} - 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 {#pep-3101}
In Python 3.0, the % operator is supplemented by a more powerful string formatting method, format{.interpreted-text role="meth"}. Support for the str.format{.interpreted-text role="meth"} 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>{.interpreted-text role="ref"}; 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__{.interpreted-text role="meth"} 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{.interpreted-text role="func"} builtin that will format a single value. It calls the type's ~object.__format__{.interpreted-text role="meth"} method with the provided specifier:
>>> format(75.6564, '.2f')
'75.66'
::: seealso
formatstrings{.interpreted-text role="ref"}
: The reference documentation for format fields.
3101{.interpreted-text role="pep"} - Advanced String Formatting
: PEP written by Talin. Implemented by Eric Smith. :::
PEP 3105: print As a Function {#pep-3105}
The print statement becomes the print{.interpreted-text role="func"} function in Python 3.0. Making print{.interpreted-text role="func"} 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.
::: seealso
3105{.interpreted-text role="pep"} - Make print a function
: PEP written by Georg Brandl. :::
PEP 3110: Exception-Handling Changes {#pep-3110}
One error that Python programmers occasionally make is writing the following code:
try:
...
except TypeError, ValueError: # Wrong!
...
The author is probably trying to catch both TypeError{.interpreted-text role="exc"} and ValueError{.interpreted-text role="exc"} exceptions, but this code actually does something different: it will catch TypeError{.interpreted-text role="exc"} and bind the resulting exception object to the local name "ValueError". The ValueError{.interpreted-text role="exc"} exception will not be caught at all. The correct code specifies a tuple of exceptions:
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.
::: seealso
3110{.interpreted-text role="pep"} - Catching Exceptions in Python 3000
: PEP written and implemented by Collin Winter. :::
PEP 3112: Byte Literals {#pep-3112}
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{.interpreted-text role="class"} constructor. For future compatibility, Python 2.6 adds bytes{.interpreted-text role="class"} as a synonym for the str{.interpreted-text role="class"} type, and it also supports the b'' notation.
The 2.6 str{.interpreted-text role="class"} differs from 3.0's bytes{.interpreted-text role="class"} 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{.interpreted-text role="func"} of the list.
The primary use of bytes{.interpreted-text role="class"} 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{.interpreted-text role="class"} or str{.interpreted-text role="class"} 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{.interpreted-text role="c:type"} in Python 2.x, to PyBytesObject{.interpreted-text role="c:type"}. Python 2.6 uses #define to support using the names PyBytesObject{.interpreted-text role="c:func"}, PyBytes_Check{.interpreted-text role="c:func"}, PyBytes_FromStringAndSize{.interpreted-text role="c:func"}, and all the other functions and macros used with strings.
Instances of the bytes{.interpreted-text role="class"} type are immutable just as strings are. A new bytearray{.interpreted-text role="class"} 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{.interpreted-text role="meth"}/~bytearray.endswith{.interpreted-text role="meth"}, ~bytearray.find{.interpreted-text role="meth"}/~bytearray.rfind{.interpreted-text role="meth"}, and some of the methods of lists, such as ~bytearray.append{.interpreted-text role="meth"}, ~bytearray.pop{.interpreted-text role="meth"}, and ~bytearray.reverse{.interpreted-text role="meth"}.
>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
>>> b
bytearray(b'ABCde')
There's also a corresponding C API, with PyByteArray_FromObject{.interpreted-text role="c:func"}, PyByteArray_FromStringAndSize{.interpreted-text role="c:func"}, and various other functions.
::: seealso
3112{.interpreted-text role="pep"} - Bytes literals in Python 3000
: PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes. :::
PEP 3116: New I/O Library {#pep-3116}
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{.interpreted-text role="meth"} and !write{.interpreted-text role="meth"}, but they may not support !readline{.interpreted-text role="meth"}, for example. Python 3.0 introduces a layered I/O library in the io{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} module:
~io.RawIOBase{.interpreted-text role="class"} defines raw I/O operations:~io.RawIOBase.read{.interpreted-text role="meth"},~io.RawIOBase.readinto{.interpreted-text role="meth"},~io.RawIOBase.write{.interpreted-text role="meth"},~io.IOBase.seek{.interpreted-text role="meth"},~io.IOBase.tell{.interpreted-text role="meth"},~io.IOBase.truncate{.interpreted-text role="meth"}, and~io.IOBase.close{.interpreted-text role="meth"}. Most of the methods of this class will often map to a single system call. There are also~io.IOBase.readable{.interpreted-text role="meth"},~io.IOBase.writable{.interpreted-text role="meth"}, and~io.IOBase.seekable{.interpreted-text role="meth"} methods 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.BufferedIOBase{.interpreted-text role="class"} is 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{.interpreted-text role="class"}, and adds a~io.BufferedIOBase.raw{.interpreted-text role="attr"} attribute holding the underlying raw object.There are five concrete classes implementing this ABC.
~io.BufferedWriter{.interpreted-text role="class"} and~io.BufferedReader{.interpreted-text role="class"} are for objects that support write-only or read-only usage that have a~io.IOBase.seek{.interpreted-text role="meth"} method for random access.~io.BufferedRandom{.interpreted-text role="class"} objects support read and write access upon the same underlying stream, and~io.BufferedRWPair{.interpreted-text role="class"} is for objects such as TTYs that have both read and write operations acting upon unconnected streams of data. The~io.BytesIO{.interpreted-text role="class"} class supports reading, writing, and seeking over an in-memory buffer.::: index single: universal newlines; What's new :::
~io.TextIOBase{.interpreted-text role="class"}: Provides functions for reading and writing strings (remember, strings will be Unicode in Python 3.0), and supportinguniversal newlines{.interpreted-text role="term"}.~io.TextIOBase{.interpreted-text role="class"} defines thereadline{.interpreted-text role="meth"} method and supports iteration upon objects.There are two concrete implementations.
~io.TextIOWrapper{.interpreted-text role="class"} wraps a buffered I/O object, supporting all of the methods for text I/O and adding a~io.TextIOBase.buffer{.interpreted-text role="attr"} attribute for access to the underlying object.~io.StringIO{.interpreted-text role="class"} simply buffers everything in memory without ever writing anything to disk.(In Python 2.6,
io.StringIO{.interpreted-text role="class"} is implemented in pure Python, so it's pretty slow. You should therefore stick with the existing!StringIO{.interpreted-text role="mod"} module or!cStringIO{.interpreted-text role="mod"} for now. At some point Python 3.0'sio{.interpreted-text role="mod"} module 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{.interpreted-text role="mod"} 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.
::: seealso
3116{.interpreted-text role="pep"} - 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 {#pep-3118}
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{.interpreted-text role="mod"} 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{.interpreted-text role="c:func"} specifies constraints upon the memory returned. Some examples are:
PyBUF_WRITABLE{.interpreted-text role="c:macro"} indicates that the memory must be writable.PyBUF_LOCK{.interpreted-text role="c:macro"} requests a read-only or exclusive lock on the memory.PyBUF_C_CONTIGUOUS{.interpreted-text role="c:macro"} andPyBUF_F_CONTIGUOUS{.interpreted-text role="c:macro"} requests 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{.interpreted-text role="c:func"}, s* and z*, return locked buffer objects for a parameter.
::: seealso
3118{.interpreted-text role="pep"} - Revising the buffer protocol
: PEP written by Travis Oliphant and Carl Banks; implemented by Travis Oliphant. :::
PEP 3119: Abstract Base Classes {#pep-3119}
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{.interpreted-text role="mod"} module containing a metaclass called ~abc.ABCMeta{.interpreted-text role="class"}, special handling of this metaclass by the isinstance{.interpreted-text role="func"} and issubclass{.interpreted-text role="func"} 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{.interpreted-text role="meth"}, !values{.interpreted-text role="meth"}, and !items{.interpreted-text role="meth"} methods? What about the iterative variants such as !iterkeys{.interpreted-text role="meth"}? !copy`and :meth:{.interpreted-text role="meth"}!update`? Iterating over the object with !iter{.interpreted-text role="func"}?
The Python 2.6 collections{.interpreted-text role="mod"} module includes a number of different ABCs that represent these distinctions. Iterable{.interpreted-text role="class"} indicates that a class defines ~object.__iter__{.interpreted-text role="meth"}, and Container{.interpreted-text role="class"} means the class defines a ~object.__contains__{.interpreted-text role="meth"} method and therefore supports x in y expressions. The basic dictionary interface of getting items, setting items, and !keys{.interpreted-text role="meth"}, !values{.interpreted-text role="meth"}, and !items{.interpreted-text role="meth"}, is defined by the MutableMapping{.interpreted-text role="class"} 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{.interpreted-text role="meth"} 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{.interpreted-text role="meth"} 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{.interpreted-text role="class"} 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{.interpreted-text role="class"} ABC above, the !draw_doubled{.interpreted-text role="meth"} method renders the object at twice its size and can be implemented in terms of other methods described in !Drawable{.interpreted-text role="class"}. Classes implementing this ABC therefore don't need to provide their own implementation of !draw_doubled{.interpreted-text role="meth"}, though they can do so. An implementation of !draw{.interpreted-text role="meth"} is necessary, though; the ABC can't provide a useful generic implementation.
You can apply the ~abc.abstractmethod{.interpreted-text role="deco"} decorator to methods such as !draw{.interpreted-text role="meth"} 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.
::: seealso
3119{.interpreted-text role="pep"} - 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 {#pep-3127}
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{.interpreted-text role="func"} builtin still returns numbers prefixed with a leading zero, and a new bin{.interpreted-text role="func"} builtin returns the binary representation for a number:
>>> oct(42)
'052'
>>> future_builtins.oct(42)
'0o52'
>>> bin(173)
'0b10101101'
The int{.interpreted-text role="func"} and long{.interpreted-text role="func"} 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
::: seealso
3127{.interpreted-text role="pep"} - Integer Literal Support and Syntax
: PEP written by Patrick Maupin; backported to 2.6 by Eric Smith. :::
PEP 3129: Class Decorators {#pep-3129}
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))
::: seealso
3129{.interpreted-text role="pep"} - Class Decorators
: PEP written by Collin Winter. :::
PEP 3141: A Type Hierarchy for Numbers {#pep-3141}
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{.interpreted-text role="mod"} module.
The most general ABC is Number{.interpreted-text role="class"}. It defines no operations at all, and only exists to allow checking if an object is a number by doing isinstance(obj, Number).
Complex{.interpreted-text role="class"} is a subclass of Number{.interpreted-text role="class"}. 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 Complex{.interpreted-text role="class"}.
Real{.interpreted-text role="class"} further derives from Complex{.interpreted-text role="class"}, and adds operations that only work on real numbers: floor{.interpreted-text role="func"}, trunc{.interpreted-text role="func"}, rounding, taking the remainder mod N, floor division, and comparisons.
Rational{.interpreted-text role="class"} numbers derive from Real{.interpreted-text role="class"}, have numerator{.interpreted-text role="attr"} and denominator{.interpreted-text role="attr"} properties, and can be converted to floats. Python 2.6 adds a simple rational-number class, Fraction{.interpreted-text role="class"}, in the fractions{.interpreted-text role="mod"} module. (It's called Fraction{.interpreted-text role="class"} instead of Rational{.interpreted-text role="class"} to avoid a name clash with numbers.Rational{.interpreted-text role="class"}.)
Integral{.interpreted-text role="class"} numbers derive from Rational{.interpreted-text role="class"}, 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{.interpreted-text role="func"}, math.floor{.interpreted-text role="func"}, math.ceil{.interpreted-text role="func"}, and adds a new one, math.trunc{.interpreted-text role="func"}, that's been backported to Python 2.6. math.trunc{.interpreted-text role="func"} rounds toward zero, returning the closest Integral{.interpreted-text role="class"} that's between the function's argument and zero.
::: seealso
3141{.interpreted-text role="pep"} - 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{.interpreted-text role="mod"} Module
To fill out the hierarchy of numeric types, the fractions{.interpreted-text role="mod"} 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 Fraction{.interpreted-text role="class"} constructor takes two Integral{.interpreted-text role="class"} 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 as_integer_ratio{.interpreted-text role="meth"} 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{.interpreted-text role="mod"} module is based upon an implementation by Sjoerd Mullender that was in Python's Demo/classes/{.interpreted-text role="file"} 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__.py{.interpreted-text role="file"} file 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{.interpreted-text role="issue"}.)The
hasattr{.interpreted-text role="func"} function was catching and ignoring all errors, under the assumption that they meant a__getattr__{.interpreted-text role="meth"} method was failing somehow and the return value ofhasattr{.interpreted-text role="func"} would therefore beFalse. This logic shouldn't be applied toKeyboardInterrupt{.interpreted-text role="exc"} andSystemExit{.interpreted-text role="exc"}, however; Python 2.6 will no longer discard such exceptions whenhasattr{.interpreted-text role="func"} encounters them. (Fixed by Benjamin Peterson;2196{.interpreted-text role="issue"}.)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{.interpreted-text role="issue"}.)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{.interpreted-text role="issue"}.)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, theStopIteration{.interpreted-text role="exc"} exception will be raised. (Backported in2719{.interpreted-text role="issue"}.)Tuples now have
~tuple.index{.interpreted-text role="meth"} and~tuple.count{.interpreted-text role="meth"} methods matching the list type's~list.index{.interpreted-text role="meth"} and~list.count{.interpreted-text role="meth"} methods:>>> 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 attributes,
getter{.interpreted-text role="attr"},setter{.interpreted-text role="attr"} anddeleter{.interpreted-text role="attr"}, 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 / 2Several methods of the built-in set types now accept multiple iterables:
intersection{.interpreted-text role="meth"},intersection_update{.interpreted-text role="meth"},union{.interpreted-text role="meth"},update{.interpreted-text role="meth"},difference{.interpreted-text role="meth"} anddifference_update{.interpreted-text role="meth"}.>>> 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
float{.interpreted-text role="func"} function 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{.interpreted-text role="issue"}.)Other functions in the
math{.interpreted-text role="mod"} module,isinf{.interpreted-text role="func"} andisnan{.interpreted-text role="func"}, return true if their floating-point argument is infinite or Not A Number. (1640{.interpreted-text role="issue"})Conversion functions were added to convert floating-point numbers into hexadecimal strings (
3008{.interpreted-text role="issue"}). These functions convert floats to and from a string representation without introducing rounding errors from the conversion between decimal and binary. Floats have ahex{.interpreted-text role="meth"} method 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
complex{.interpreted-text role="func"} constructor will now preserve the sign of the zero. (Fixed by Mark T. Dickinson;1507{.interpreted-text role="issue"}.)Classes that inherit a
__hash__{.interpreted-text role="meth"} method from a parent class can set__hash__ = Noneto indicate that the class isn't hashable. This will makehash(obj)raise aTypeError{.interpreted-text role="exc"} and the class will not be indicated as implementing theHashable{.interpreted-text role="class"} ABC.You should do this when you've defined a
__cmp__{.interpreted-text role="meth"} or__eq__{.interpreted-text role="meth"} 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__hash__{.interpreted-text role="meth"} method inherited from a parent class, so assigningNonewas implemented as an override. At the C level, extensions can settp_hashtoPyObject_HashNotImplemented{.interpreted-text role="c:func"}. (Fixed by Nick Coghlan and Amaury Forgeot d'Arc;2235{.interpreted-text role="issue"}.)The
GeneratorExit{.interpreted-text role="exc"} exception now subclassesBaseException{.interpreted-text role="exc"} instead ofException{.interpreted-text role="exc"}. This means that an exception handler that doesexcept Exception:will not inadvertently catchGeneratorExit{.interpreted-text role="exc"}. (Contributed by Chad Austin;1537{.interpreted-text role="issue"}.)Generator objects now have a
gi_code{.interpreted-text role="attr"} attribute that refers to the original code object backing the generator. (Contributed by Collin Winter;1473257{.interpreted-text role="issue"}.)The
compile{.interpreted-text role="func"} built-in function now accepts keyword arguments as well as positional parameters. (Contributed by Thomas Wouters;1444529{.interpreted-text role="issue"}.)The
complex{.interpreted-text role="func"} constructor 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{.interpreted-text role="issue"})The string
translate{.interpreted-text role="meth"} method 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{.interpreted-text role="issue"}.)The built-in
dir{.interpreted-text role="func"} function now checks for a__dir__{.interpreted-text role="meth"} 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 thatdir{.interpreted-text role="func"} produces. Objects that have__getattr__{.interpreted-text role="meth"} or__getattribute__{.interpreted-text role="meth"} methods can use this to advertise pseudo-attributes they will honor. (1591665{.interpreted-text role="issue"})Instance method objects have new attributes for the object and function comprising the method; the new synonym for
!im_self{.interpreted-text role="attr"} is~method.__self__{.interpreted-text role="attr"}, and!im_func{.interpreted-text role="attr"} is also available as~method.__func__{.interpreted-text role="attr"}. The old names are still supported in Python 2.6, but are gone in 3.0.An obscure change: when you use the
locals{.interpreted-text role="func"} function inside aclass{.interpreted-text role="keyword"} statement, the resulting dictionary no longer returns free variables. (Free variables, in this case, are variables referenced in the!class{.interpreted-text role="keyword"} statement that aren't attributes of the class.)
Optimizations
The
warnings{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)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{.interpreted-text role="issue"}.)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_TAG{.interpreted-text role="c:macro"} to 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. See1878{.interpreted-text role="issue"} for 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{.interpreted-text role="issue"}.)All of the functions in the
struct{.interpreted-text role="mod"} module 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
split{.interpreted-text role="meth"} method by about 25% andsplitlines{.interpreted-text role="meth"} by 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__{.interpreted-text role="meth"} 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 {#new-26-interpreter}
Two command-line options have been reserved for use by other Python implementations. The !-J{.interpreted-text role="option"} switch has been reserved for use by Jython for Jython-specific options, such as switches that are passed to the underlying JVM. -X{.interpreted-text role="option"} 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{.interpreted-text role="file"} or .pyo{.interpreted-text role="file"} files by supplying the -B{.interpreted-text role="option"} switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE{.interpreted-text role="envvar"} 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{.interpreted-text role="envvar"} 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{.interpreted-text role="file"} file in the source tree for a more complete list of changes, or look through the Subversion logs for all the details.
The
!asyncore{.interpreted-text role="mod"} and!asynchat{.interpreted-text role="mod"} modules are being actively maintained again, and a number of patches and bugfixes were applied. (Maintained by Josiah Carlson; see1736190{.interpreted-text role="issue"} for one patch.)The
bsddb{.interpreted-text role="mod"} module 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.dbshelve{.interpreted-text role="mod"} module now uses the highest pickling protocol available, instead of restricting itself to protocol 1. (Contributed by W. Barnes.)The
!cgi{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)The
parse_qs{.interpreted-text role="func"} andparse_qsl{.interpreted-text role="func"} functions have been relocated from the!cgi{.interpreted-text role="mod"} module to theurlparse <urllib.parse>{.interpreted-text role="mod"} module. The versions still available in the!cgi{.interpreted-text role="mod"} module will triggerPendingDeprecationWarning{.interpreted-text role="exc"} messages in 2.6 (600362{.interpreted-text role="issue"}).The
cmath{.interpreted-text role="mod"} module underwent extensive revision, contributed by Mark Dickinson and Christian Heimes. Five new functions were added:polar{.interpreted-text role="func"} converts a complex number to polar form, returning the modulus and argument of the complex number.rect{.interpreted-text role="func"} does the opposite, turning a modulus, argument pair back into the corresponding complex number.phase{.interpreted-text role="func"} returns the argument (also called the angle) of a complex number.isnan{.interpreted-text role="func"} returns True if either the real or imaginary part of its argument is a NaN.isinf{.interpreted-text role="func"} returns True if either the real or imaginary part of its argument is infinite.
The revisions also improved the numerical soundness of the
cmath{.interpreted-text role="mod"} module. For all functions, the real and imaginary parts of the results are accurate to within a few units of least precision (ulps) whenever possible. See1381{.interpreted-text role="issue"} for the details. The branch cuts forasinh{.interpreted-text role="func"},atanh{.interpreted-text role="func"}: andatan{.interpreted-text role="func"} have 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
cmath{.interpreted-text role="mod"} module 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
collections{.interpreted-text role="mod"} module: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
namedtuple{.interpreted-text role="func"} instances. For example, theDecimal.as_tuple{.interpreted-text role="meth"} method now returns a named tuple withsign{.interpreted-text role="attr"},digits{.interpreted-text role="attr"}, andexponent{.interpreted-text role="attr"} fields.(Contributed by Raymond Hettinger.)
Another change to the
collections{.interpreted-text role="mod"} module is that thedeque{.interpreted-text role="class"} type 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>{.interpreted-text role="mod"} module's~http.cookies.Morsel{.interpreted-text role="class"} objects now support an~http.cookies.Morsel.httponly{.interpreted-text role="attr"} attribute. In some browsers. cookies with this attribute set cannot be accessed or manipulated by JavaScript code. (Contributed by Arvin Schnell;1638033{.interpreted-text role="issue"}.)A new window method in the
curses{.interpreted-text role="mod"} module,chgat{.interpreted-text role="meth"}, 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
Textbox{.interpreted-text role="class"} class in thecurses.textpad{.interpreted-text role="mod"} module 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 theTextbox{.interpreted-text role="class"} instance.The
datetime{.interpreted-text role="mod"} module'sstrftime{.interpreted-text role="meth"} methods 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{.interpreted-text role="issue"}.)The
decimal{.interpreted-text role="mod"} module was updated to version 1.66 of the General Decimal Specification. New features include some methods for some basic mathematical functions such asexp{.interpreted-text role="meth"} andlog10{.interpreted-text role="meth"}:>>> Decimal(1).exp() Decimal("2.718281828459045235360287471") >>> Decimal("2.7182818").ln() Decimal("0.9999999895305022877376682436") >>> Decimal(1000).log10() Decimal("3")The
as_tuple{.interpreted-text role="meth"} method ofDecimal{.interpreted-text role="class"} objects now returns a named tuple withsign{.interpreted-text role="attr"},digits{.interpreted-text role="attr"}, andexponent{.interpreted-text role="attr"} fields.(Implemented by Facundo Batista and Mark Dickinson. Named tuple support added by Raymond Hettinger.)
The
difflib{.interpreted-text role="mod"} module'sSequenceMatcher{.interpreted-text role="class"} class now returns named tuples representing matches, witha{.interpreted-text role="attr"},b{.interpreted-text role="attr"}, andsize{.interpreted-text role="attr"} attributes. (Contributed by Raymond Hettinger.)An optional
timeoutparameter, specifying a timeout measured in seconds, was added to theftplib.FTP{.interpreted-text role="class"} class constructor as well as theconnect{.interpreted-text role="meth"} method. (Added by Facundo Batista.) Also, theFTP{.interpreted-text role="class"} class'sstorbinary{.interpreted-text role="meth"} andstorlines{.interpreted-text role="meth"} now 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{.interpreted-text role="issue"}.)The
reduce{.interpreted-text role="func"} built-in function is also available in thefunctools{.interpreted-text role="mod"} module. In Python 3.0, the builtin has been dropped andreduce{.interpreted-text role="func"} is only available fromfunctools{.interpreted-text role="mod"}; currently there are no plans to drop the builtin in the 2.x series. (Patched by Christian Heimes;1739906{.interpreted-text role="issue"}.)When possible, the
getpass{.interpreted-text role="mod"} module will now use/dev/tty{.interpreted-text role="file"} to 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.glob{.interpreted-text role="func"} function can now return Unicode filenames if a Unicode path was used and Unicode filenames are matched within the directory. (1001604{.interpreted-text role="issue"})A new function in the
heapq{.interpreted-text role="mod"} module,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 toheappush{.interpreted-text role="func"} and thenheappop{.interpreted-text role="func"}.heapq{.interpreted-text role="mod"} is now implemented to only use less-than comparison, instead of the less-than-or-equal comparison it previously used. This makesheapq{.interpreted-text role="mod"}'s usage of a type match thelist.sort{.interpreted-text role="meth"} method. (Contributed by Raymond Hettinger.)An optional
timeoutparameter, specifying a timeout measured in seconds, was added to thehttplib.HTTPConnection <http.client.HTTPConnection>{.interpreted-text role="class"} andHTTPSConnection <http.client.HTTPSConnection>{.interpreted-text role="class"} class constructors. (Added by Facundo Batista.)Most of the
inspect{.interpreted-text role="mod"} module's functions, such asgetmoduleinfo{.interpreted-text role="func"} andgetargs{.interpreted-text role="func"}, 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
isgenerator{.interpreted-text role="func"},isgeneratorfunction{.interpreted-text role="func"}, andisabstract{.interpreted-text role="func"}.The
itertools{.interpreted-text role="mod"} module 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 initertools{.interpreted-text role="mod"} that gained a new constructor in Python 2.6.itertools.chain.from_iterable(iterable)takes a single iterable that should return other iterables.chain{.interpreted-text role="func"} will 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
logging{.interpreted-text role="mod"} module'sFileHandler{.interpreted-text role="class"} class and its subclassesWatchedFileHandler{.interpreted-text role="class"},RotatingFileHandler{.interpreted-text role="class"}, andTimedRotatingFileHandler{.interpreted-text role="class"} now have an optional delay parameter to their constructors. If delay is true, opening of the log file is deferred until the firstemit{.interpreted-text role="meth"} call is made. (Contributed by Vinay Sajip.)TimedRotatingFileHandler{.interpreted-text role="class"} also 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
math{.interpreted-text role="mod"} module:~math.isinf{.interpreted-text role="func"} and~math.isnan{.interpreted-text role="func"} determine whether a given float is a (positive or negative) infinity or a NaN (Not a Number), respectively.~math.copysign{.interpreted-text role="func"} copies 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.factorial{.interpreted-text role="func"} computes the factorial of a number. (Contributed by Raymond Hettinger;2138{.interpreted-text role="issue"}.)~math.fsum{.interpreted-text role="func"} adds 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{.interpreted-text role="issue"}.)~math.acosh{.interpreted-text role="func"},~math.asinh{.interpreted-text role="func"} and~math.atanh{.interpreted-text role="func"} compute the inverse hyperbolic functions.~math.log1p{.interpreted-text role="func"} returns the natural logarithm of 1+x (base e).trunc{.interpreted-text role="func"} rounds a number toward zero, returning the closestIntegral{.interpreted-text role="class"} that's between the function's argument and zero. Added as part of the backport of PEP 3141's type hierarchy for numbers.
The
math{.interpreted-text role="mod"} module 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 aValueError{.interpreted-text role="exc"} across 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{.interpreted-text role="exc"}. Where Annex 'F' of the C99 standard recommends signaling 'overflow', Python will raiseOverflowError{.interpreted-text role="exc"}. (See711019{.interpreted-text role="issue"} and1640{.interpreted-text role="issue"}.)(Contributed by Christian Heimes and Mark Dickinson.)
~mmap.mmap{.interpreted-text role="class"} objects now have arfind{.interpreted-text role="meth"} method that searches for a substring beginning at the end of the string and searching backwards. Thefind{.interpreted-text role="meth"} method also gained an end parameter giving an index at which to stop searching. (Contributed by John Lenton.)The
operator{.interpreted-text role="mod"} module gained amethodcaller{.interpreted-text role="func"} function 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
attrgetter{.interpreted-text role="func"} function 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
os{.interpreted-text role="mod"} module 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.)chflags{.interpreted-text role="func"} andlchflags{.interpreted-text role="func"} are 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 thestat{.interpreted-text role="mod"} module; some possible values includeUF_IMMUTABLE{.interpreted-text role="const"} to signal the file may not be changed andUF_APPEND{.interpreted-text role="const"} to 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 thesubprocess{.interpreted-text role="mod"} module to make starting processes faster. (Contributed by Georg Brandl;1663329{.interpreted-text role="issue"}.)The
os.environobject'sclear{.interpreted-text role="meth"} method will now unset the environment variables usingos.unsetenv{.interpreted-text role="func"} in addition to clearing the object's keys. (Contributed by Martin Horcicka;1181{.interpreted-text role="issue"}.)The
os.walk{.interpreted-text role="func"} function 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{.interpreted-text role="issue"})In the
os.path{.interpreted-text role="mod"} module, thesplitext{.interpreted-text role="func"} function 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{.interpreted-text role="issue"})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{.interpreted-text role="issue"}.)On Windows,
os.path.expandvars{.interpreted-text role="func"} will 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{.interpreted-text role="issue"}.)The Python debugger provided by the
pdb{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)The
pdb.post_mortem{.interpreted-text role="func"} function, used to begin debugging a traceback, will now use the traceback returned bysys.exc_info{.interpreted-text role="func"} if no traceback is supplied. (Contributed by Facundo Batista;1106316{.interpreted-text role="issue"}.)The
pickletools{.interpreted-text role="mod"} module now has anoptimize{.interpreted-text role="func"} function 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
get_data{.interpreted-text role="func"} function was added to thepkgutil{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)The
pyexpat{.interpreted-text role="mod"} module'sParser{.interpreted-text role="class"} objects now allow setting theirbuffer_size{.interpreted-text role="attr"} attribute to change the size of the buffer used to hold character data. (Contributed by Achim Gaedke;1137{.interpreted-text role="issue"}.)The
Queue{.interpreted-text role="mod"} module now provides queue variants that retrieve entries in different orders. ThePriorityQueue{.interpreted-text role="class"} class stores queued items in a heap and retrieves them in priority order, andLifoQueue{.interpreted-text role="class"} retrieves the most recently added entries first, meaning that it behaves like a stack. (Contributed by Raymond Hettinger.)The
random{.interpreted-text role="mod"} module'sRandom{.interpreted-text role="class"} objects 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'sRandom{.interpreted-text role="class"} objects can't be unpickled correctly on earlier versions of Python. (Contributed by Shawn Ligocki;1727780{.interpreted-text role="issue"}.)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{.interpreted-text role="issue"}.)Long regular expression searches carried out by the
re{.interpreted-text role="mod"} module will check for signals being delivered, so time-consuming searches can now be interrupted. (Contributed by Josh Hoyt and Ralf Schmitt;846388{.interpreted-text role="issue"}.)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{.interpreted-text role="issue"}.)The
rlcompleter{.interpreted-text role="mod"} module'sCompleter.complete{.interpreted-text role="meth"} method will now ignore exceptions triggered while evaluating a name. (Fixed by Lorenz Quack;2250{.interpreted-text role="issue"}.)The
sched{.interpreted-text role="mod"} module'sscheduler{.interpreted-text role="class"} instances now have a read-onlyqueue{.interpreted-text role="attr"} attribute 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{.interpreted-text role="issue"}.)The
select{.interpreted-text role="mod"} module now has wrapper functions for the Linux!epoll{.interpreted-text role="c:func"} and BSD!kqueue{.interpreted-text role="c:func"} system calls.modify{.interpreted-text role="meth"} method was added to the existingpoll{.interpreted-text role="class"} objects;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{.interpreted-text role="issue"}.)The
shutil.copytree{.interpreted-text role="func"} function 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
shutil{.interpreted-text role="mod"} module also provides anignore_patterns{.interpreted-text role="func"} function for use with this new parameter.ignore_patterns{.interpreted-text role="func"} takes 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.svn{.interpreted-text role="file"} directories 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{.interpreted-text role="issue"}.)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
signal{.interpreted-text role="mod"} module 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{.interpreted-text role="c:func"}, 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
set_wakeup_fd{.interpreted-text role="func"}, and the readable descriptor will be added to the list of descriptors monitored by the event loop via!select{.interpreted-text role="c:func"} or!poll{.interpreted-text role="c:func"}. 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{.interpreted-text role="issue"}.)The
siginterrupt{.interpreted-text role="func"} function is now available from Python code, and allows changing whether signals can interrupt system calls or not. (Contributed by Ralf Schmitt.)The
setitimer{.interpreted-text role="func"} andgetitimer{.interpreted-text role="func"} functions have also been added (where they're available).setitimer{.interpreted-text role="func"} allows 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{.interpreted-text role="issue"}.)The
smtplib{.interpreted-text role="mod"} module now supports SMTP over SSL thanks to the addition of theSMTP_SSL{.interpreted-text role="class"} class. This class supports an interface identical to the existingSMTP{.interpreted-text role="class"} class. (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{.interpreted-text role="rfc"}) 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{.interpreted-text role="issue"}.)SMTP.starttls{.interpreted-text role="meth"} now complies with3207{.interpreted-text role="rfc"} and forgets any knowledge obtained from the server not obtained from the TLS negotiation itself. (Patch contributed by Bill Fenner;829951{.interpreted-text role="issue"}.)The
socket{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)A new function,
create_connection{.interpreted-text role="func"}, 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 usecreate_connection{.interpreted-text role="func"} instead ofsocket(socket.AF_INET, ...)may be all that's required to make your code work with IPv6.The base classes in the
SocketServer <socketserver>{.interpreted-text role="mod"} module now support calling a~socketserver.BaseServer.handle_timeout{.interpreted-text role="meth"} method after a span of inactivity specified by the server's~socketserver.BaseServer.timeout{.interpreted-text role="attr"} attribute. (Contributed by Michael Pomraning.) The~socketserver.BaseServer.serve_forever{.interpreted-text role="meth"} method 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{.interpreted-text role="issue"},1193577{.interpreted-text role="issue"}.)The
sqlite3{.interpreted-text role="mod"} module, maintained by Gerhard Häring, has been updated from version 2.3.2 in Python 2.5 to version 2.4.1.The
struct{.interpreted-text role="mod"} module now supports the C99_Bool{.interpreted-text role="c:expr"} type, using the format character'?'. (Contributed by David Remahl.)The
~subprocess.Popen{.interpreted-text role="class"} objects provided by thesubprocess{.interpreted-text role="mod"} module now have~subprocess.Popen.terminate{.interpreted-text role="meth"},~subprocess.Popen.kill{.interpreted-text role="meth"}, and~subprocess.Popen.send_signal{.interpreted-text role="meth"} methods. On Windows,!send_signal{.interpreted-text role="meth"} only supports the~signal.SIGTERM{.interpreted-text role="py:const"} signal, and all these methods are aliases for the Win32 API function!TerminateProcess{.interpreted-text role="c:func"}. (Contributed by Christian Heimes.)A new variable in the
sys{.interpreted-text role="mod"} module,float_info{.interpreted-text role="attr"}, is an object containing information derived from thefloat.h{.interpreted-text role="file"} file about the platform's floating-point support. Attributes of this object includemant_dig{.interpreted-text role="attr"} (number of digits in the mantissa),epsilon{.interpreted-text role="attr"} (smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes;1534{.interpreted-text role="issue"}.)Another new variable,
dont_write_bytecode{.interpreted-text role="attr"}, controls whether Python writes any.pyc{.interpreted-text role="file"} or.pyo{.interpreted-text role="file"} files 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-B{.interpreted-text role="option"} switch to the Python interpreter, or by setting thePYTHONDONTWRITEBYTECODE{.interpreted-text role="envvar"} environment 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, theverbose{.interpreted-text role="attr"} attribute is true if Python was executed in verbose mode,debug{.interpreted-text role="attr"} is true in debugging mode, etc. These attributes are all read-only. (Contributed by Christian Heimes.)A new function,
getsizeof{.interpreted-text role="func"}, 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__{.interpreted-text role="meth"} method to return the object's size. (Contributed by Robert Schuppenies;2898{.interpreted-text role="issue"}.)It's now possible to determine the current profiler and tracer functions by calling
sys.getprofile{.interpreted-text role="func"} andsys.gettrace{.interpreted-text role="func"}. (Contributed by Georg Brandl;1648{.interpreted-text role="issue"}.)The
tarfile{.interpreted-text role="mod"} module 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.add{.interpreted-text role="meth"} method 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 toadd{.interpreted-text role="meth"} and to the names of files in recursively added directories.(All changes contributed by Lars Gustäbel).
An optional
timeoutparameter was added to the!telnetlib.Telnet{.interpreted-text role="class"} class constructor, specifying a timeout measured in seconds. (Added by Facundo Batista.)The
tempfile.NamedTemporaryFile{.interpreted-text role="class"} class 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{.interpreted-text role="issue"}.)A new class,
SpooledTemporaryFile{.interpreted-text role="class"}, 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
NamedTemporaryFile{.interpreted-text role="class"} andSpooledTemporaryFile{.interpreted-text role="class"} classes both work as context managers, so you can writewith tempfile.NamedTemporaryFile() as tmp: .... (Contributed by Alexander Belopolsky;2021{.interpreted-text role="issue"}.)The
test.test_support <test.support>{.interpreted-text role="mod"} module gained a number of context managers useful for writing tests.~test.support.os_helper.EnvironmentVarGuard{.interpreted-text role="func"} is a context manager that temporarily changes environment variables and automatically restores them to their old values.Another context manager,
TransientResource{.interpreted-text role="class"}, 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,
check_warnings{.interpreted-text role="func"} resets thewarning{.interpreted-text role="mod"} module's warning filters and returns an object that will record all warning messages triggered (3781{.interpreted-text role="issue"}):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
textwrap{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)The
threading{.interpreted-text role="mod"} module API is being changed to use properties such asdaemon{.interpreted-text role="attr"} instead ofsetDaemon{.interpreted-text role="meth"} andisDaemon{.interpreted-text role="meth"} methods, and some methods have been renamed to use underscores instead of camel-case; for example, theactiveCount{.interpreted-text role="meth"} method is renamed toactive_count{.interpreted-text role="meth"}. 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
threading{.interpreted-text role="mod"} module'sThread{.interpreted-text role="class"} objects gained anident{.interpreted-text role="attr"} property that returns the thread's identifier, a nonzero integer. (Contributed by Gregory P. Smith;2871{.interpreted-text role="issue"}.)The
timeit{.interpreted-text role="mod"} module now accepts callables as well as strings for the statement being timed and for the setup code. Two convenience functions were added for creatingTimer{.interpreted-text role="class"} instances:repeat(stmt, setup, time, repeat, number)andtimeit(stmt, setup, time, number)create an instance and call the corresponding method. (Contributed by Erik Demaine;1533909{.interpreted-text role="issue"}.)The
Tkinter{.interpreted-text role="mod"} module 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{.interpreted-text role="issue"}.)The
turtle{.interpreted-text role="mod"} module 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
delay{.interpreted-text role="meth"},tracer{.interpreted-text role="meth"}, andspeed{.interpreted-text role="meth"} methods. - The ability to set new shapes for the turtle, and to define a new coordinate system.
- Turtles now have an
undo{.interpreted-text role="meth"} method 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.cfg{.interpreted-text role="file"} file 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{.interpreted-text role="issue"})An optional
timeoutparameter was added to theurllib.urlopen <urllib.request.urlopen>{.interpreted-text role="func"} function and theurllib.ftpwrapper{.interpreted-text role="class"} class constructor, as well as theurllib2.urlopen <urllib.request.urlopen>{.interpreted-text role="func"} 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
unicodedata{.interpreted-text role="mod"} module has been updated to version 5.1.0. (Updated by Martin von Löwis;3811{.interpreted-text role="issue"}.)The
warnings{.interpreted-text role="mod"} module'sformatwarning{.interpreted-text role="func"} andshowwarning{.interpreted-text role="func"} gained an optional line argument that can be used to supply the line of source code. (Added as part of1631171{.interpreted-text role="issue"}, which re-implemented part of thewarnings{.interpreted-text role="mod"} module in C code.)A new function,
catch_warnings{.interpreted-text role="func"}, is a context manager intended for testing purposes that lets you temporarily modify the warning filters and then restore their original values (3781{.interpreted-text role="issue"}).The XML-RPC
SimpleXMLRPCServer <xmlrpc.server>{.interpreted-text role="class"} andDocXMLRPCServer <xmlrpc.server>{.interpreted-text role="class"} classes 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'sallow_reuse_address{.interpreted-text role="attr"} attribute before calling theserver_bind{.interpreted-text role="meth"} andserver_activate{.interpreted-text role="meth"} methods to open the socket and begin listening for connections. (Contributed by Peter Parente;1599845{.interpreted-text role="issue"}.)SimpleXMLRPCServer{.interpreted-text role="class"} also has a_send_traceback_header{.interpreted-text role="attr"} attribute; 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>{.interpreted-text role="mod"} module no longer automatically convertsdatetime.date{.interpreted-text role="class"} anddatetime.time{.interpreted-text role="class"} to thexmlrpclib.DateTime <xmlrpc.client.DateTime>{.interpreted-text role="class"} type; the conversion semantics were not necessarily correct for all applications. Code using!xmlrpclib{.interpreted-text role="mod"} should convertdate{.interpreted-text role="class"} and~datetime.time{.interpreted-text role="class"} instances. (1330538{.interpreted-text role="issue"}) The code can also handle dates before 1900 (contributed by Ralf Schmitt;2014{.interpreted-text role="issue"}) and 64-bit integers represented by using<i8>in XML-RPC responses (contributed by Riku Lindblad;2985{.interpreted-text role="issue"}).The
zipfile{.interpreted-text role="mod"} module'sZipFile{.interpreted-text role="class"} class now hasextract{.interpreted-text role="meth"} andextractall{.interpreted-text role="meth"} methods 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{.interpreted-text role="issue"}.)The
open{.interpreted-text role="meth"},read{.interpreted-text role="meth"} andextract{.interpreted-text role="meth"} methods can now take either a filename or aZipInfo{.interpreted-text role="class"} object. This is useful when an archive accidentally contains a duplicated filename. (Contributed by Graham Horler;1775025{.interpreted-text role="issue"}.)Finally,
zipfile{.interpreted-text role="mod"} now supports using Unicode filenames for archived files. (Contributed by Alexey Borzenkov;1734346{.interpreted-text role="issue"}.)
The ast{.interpreted-text role="mod"} module
The ast{.interpreted-text role="mod"} 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 parse{.interpreted-text role="func"} function takes an expression and returns an AST. The dump{.interpreted-text role="func"} 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 literal_eval{.interpreted-text role="func"} 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{.interpreted-text role="func"} call, literal_eval{.interpreted-text role="func"} 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 NodeVisitor{.interpreted-text role="class"} and NodeTransformer{.interpreted-text role="class"} classes for traversing and modifying an AST, and functions for common transformations such as changing line numbers.
The !future_builtins{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} 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{.interpreted-text role="func"}. In Python 3.0,repr{.interpreted-text role="func"} will return a Unicode string, whileascii{.interpreted-text role="func"} will 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__{.interpreted-text role="meth"} or__oct__{.interpreted-text role="meth"} methods, these versions will call the__index__{.interpreted-text role="meth"} method and convert the result to hexadecimal or octal.oct{.interpreted-text role="func"} will use the new0onotation for its result.
The json{.interpreted-text role="mod"} module: JavaScript Object Notation
The new json{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} (originally called simplejson) was written by Bob Ippolito.
The plistlib{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} module has been promoted to the standard library.
Using the module is simple:
import sys
import plistlib
import datetime
# Create data structure
data_struct = dict(lastAccessed=datetime.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{.interpreted-text role="mod"} module.
ctypes{.interpreted-text role="mod"} now supports a c_bool{.interpreted-text role="class"} datatype that represents the C99 bool type. (Contributed by David Remahl; 1649190{.interpreted-text role="issue"}.)
The ctypes{.interpreted-text role="mod"} 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{.interpreted-text role="mod"} data types now support from_buffer{.interpreted-text role="meth"} and from_buffer_copy{.interpreted-text role="meth"} methods that create a ctypes instance based on a provided buffer object. from_buffer_copy{.interpreted-text role="meth"} copies the contents of the object, while from_buffer{.interpreted-text role="meth"} will share the same memory area.
A new calling convention tells ctypes{.interpreted-text role="mod"} to clear the errno or Win32 LastError variables at the outset of each wrapped call. (Implemented by Thomas Heller; 1798{.interpreted-text role="issue"}.)
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{.interpreted-text role="func"} function and then call the module-level methods set_errno{.interpreted-text role="meth"} and get_errno{.interpreted-text role="meth"} to set and retrieve the error value.
The Win32 LastError variable is similarly supported by the DLL{.interpreted-text role="func"}, OleDLL{.interpreted-text role="func"}, and WinDLL{.interpreted-text role="func"} functions. You supply use_last_error=True as a keyword parameter and then call the module-level methods set_last_error{.interpreted-text role="meth"} and get_last_error{.interpreted-text role="meth"}.
The byref{.interpreted-text role="func"} 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{.interpreted-text role="mod"}, 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{.interpreted-text role="mod"} 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{.interpreted-text role="func"} function. It's possible to specify whether a certificate is required, and to obtain certificate info by calling the getpeercert{.interpreted-text role="meth"} method.
::: seealso
The documentation for the ssl{.interpreted-text role="mod"} module.
:::
Deprecations and Removals
String exceptions have been removed. Attempting to use them raises a
TypeError{.interpreted-text role="exc"}.Changes to the
Exception{.interpreted-text role="class"} interface as dictated by352{.interpreted-text role="pep"} continue to be made. For 2.6, the!message{.interpreted-text role="attr"} attribute is being deprecated in favor of the~BaseException.args{.interpreted-text role="attr"} attribute.(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{.interpreted-text role="mod"},!bgenlocations{.interpreted-text role="mod"},!buildtools{.interpreted-text role="mod"},!bundlebuilder{.interpreted-text role="mod"},!Canvas{.interpreted-text role="mod"},!compiler{.interpreted-text role="mod"},!dircache{.interpreted-text role="mod"},!dl{.interpreted-text role="mod"},!fpformat{.interpreted-text role="mod"},!gensuitemodule{.interpreted-text role="mod"},!ihooks{.interpreted-text role="mod"},!imageop{.interpreted-text role="mod"},!imgfile{.interpreted-text role="mod"},!linuxaudiodev{.interpreted-text role="mod"},!mhlib{.interpreted-text role="mod"},!mimetools{.interpreted-text role="mod"},!multifile{.interpreted-text role="mod"},!new{.interpreted-text role="mod"},!pure{.interpreted-text role="mod"},!statvfs{.interpreted-text role="mod"},!sunaudiodev{.interpreted-text role="mod"},!test.testall{.interpreted-text role="mod"}, and!toaiff{.interpreted-text role="mod"}.The
!gopherlib{.interpreted-text role="mod"} module has been removed.The
!MimeWriter{.interpreted-text role="mod"} module and!mimify{.interpreted-text role="mod"} module have been deprecated; use theemail{.interpreted-text role="mod"} package instead.The
!md5{.interpreted-text role="mod"} module has been deprecated; use thehashlib{.interpreted-text role="mod"} module instead.The
!posixfile{.interpreted-text role="mod"} module has been deprecated;fcntl.lockf{.interpreted-text role="func"} provides better locking.The
!popen2{.interpreted-text role="mod"} module has been deprecated; use thesubprocess{.interpreted-text role="mod"} module.The
!rgbimg{.interpreted-text role="mod"} module has been removed.The
!sets{.interpreted-text role="mod"} module has been deprecated; it's better to use the built-inset{.interpreted-text role="class"} andfrozenset{.interpreted-text role="class"} types.The
!sha{.interpreted-text role="mod"} module has been deprecated; use thehashlib{.interpreted-text role="mod"} module 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
!memmove{.interpreted-text role="c:func"} and!strerror{.interpreted-text role="c:func"}, 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
PCbuild{.interpreted-text role="file"} directory 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
configure{.interpreted-text role="program"} script can take a!--with-universal-archs=[32-bit|64-bit|all]{.interpreted-text role="option"} 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{.interpreted-text role="c:func"}, 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{.interpreted-text role="c:func"}, 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{.interpreted-text role="file"}) that your application would then import and run.If you maintain a C/C++ application that embeds Python, check whether you're calling
!PySys_SetArgv{.interpreted-text role="c:func"} and carefully consider whether the application should be using!PySys_SetArgvEx{.interpreted-text role="c:func"} with 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_SetArgv{.interpreted-text role="c:func"} alone and callPyRun_SimpleString("sys.path.pop(0)\n")afterwards to discard the firstsys.pathcomponent.Security issue reported as
2008-5983{.interpreted-text role="cve"}; discussed in50003{.interpreted-text role="gh"}, 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 thebsddb{.interpreted-text role="mod"} module for their own purposes. (Contributed by Duncan Grisby.)The new buffer interface, previously described in the PEP 3118 section, adds
PyObject_GetBuffer{.interpreted-text role="c:func"} andPyBuffer_Release{.interpreted-text role="c:func"}, 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_IncUseCount{.interpreted-text role="c:func"} and!PyFile_DecUseCount{.interpreted-text role="c:func"} functions. File objects can't be closed unless the reference count is zero.!PyFile_IncUseCount{.interpreted-text role="c:func"} should be called while the GIL is still held, before carrying out an I/O operation using theFILE *pointer, and!PyFile_DecUseCount{.interpreted-text role="c:func"} should 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{.interpreted-text role="exc"}. A new API function,!PyImport_ImportModuleNoBlock{.interpreted-text role="c:func"}, 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, anImportError{.interpreted-text role="exc"} is raised. (Contributed by Christian Heimes.)Several functions return information about the platform's floating-point support.
PyFloat_GetMax{.interpreted-text role="c:func"} returns the maximum representable floating-point value, andPyFloat_GetMin{.interpreted-text role="c:func"} returns the minimum positive value.PyFloat_GetInfo{.interpreted-text role="c:func"} returns an object containing more information from thefloat.h{.interpreted-text role="file"} file, 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{.interpreted-text role="issue"}.)C functions and methods that use
PyComplex_AsCComplex{.interpreted-text role="c:func"} will now accept arguments that have a__complex__{.interpreted-text role="meth"} method. In particular, the functions in thecmath{.interpreted-text role="mod"} module will now accept objects with this method. This is a backport of a Python 3.0 change. (Contributed by Mark Dickinson;1675423{.interpreted-text role="issue"}.)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{.interpreted-text role="issue"}.)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_AddStringMacro{.interpreted-text role="c:macro"} andPyModule_AddIntMacro(){.interpreted-text role="c:macro"}. (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(){.interpreted-text role="c:macro"} becamePy_SIZE(){.interpreted-text role="c:macro"},!Py_Type(){.interpreted-text role="c:macro"} becamePy_TYPE(){.interpreted-text role="c:macro"}, and!Py_Refcnt(){.interpreted-text role="c:macro"} becamePy_REFCNT(){.interpreted-text role="c:macro"}. The mixed-case macros are still available in Python 2.6 for backward compatibility. (1629{.interpreted-text role="issue"})Distutils now places C extensions it builds in a different directory when running on a debug version of Python. (Contributed by Collin Winter;
1530959{.interpreted-text role="issue"}.)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/ACKS{.interpreted-text role="file"} andMisc/NEWS{.interpreted-text role="file"} files 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
PCbuild{.interpreted-text role="file"} directory 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
msvcrt{.interpreted-text role="mod"} module now supports both the normal and wide char variants of the console I/O API. The~msvcrt.getwch{.interpreted-text role="func"} function reads a keypress and returns a Unicode value, as does the~msvcrt.getwche{.interpreted-text role="func"} function. The~msvcrt.putwch{.interpreted-text role="func"} function takes a Unicode character and writes it to the console. (Contributed by Christian Heimes.)os.path.expandvars{.interpreted-text role="func"} will 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{.interpreted-text role="issue"}.)The
socket{.interpreted-text role="mod"} module's socket objects now have an~socket.socket.ioctl{.interpreted-text role="meth"} method that provides a limited interface to theWSAIoctl{.interpreted-text role="c:func"} system interface.The
_winreg <winreg>{.interpreted-text role="mod"} module now has a function,~winreg.ExpandEnvironmentStrings{.interpreted-text role="func"}, 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 inwith{.interpreted-text role="keyword"} statements. (Contributed by Christian Heimes.)_winreg <winreg>{.interpreted-text role="mod"} also has better support for x64 systems, exposing the~winreg.DisableReflectionKey{.interpreted-text role="func"},~winreg.EnableReflectionKey{.interpreted-text role="func"}, and~winreg.QueryReflectionKey{.interpreted-text role="func"} functions, which enable and disable registry reflection for 32-bit processes running on 64-bit systems. (1753245{.interpreted-text role="issue"})The
!msilib{.interpreted-text role="mod"} module's!Record{.interpreted-text role="class"} object gained!GetInteger{.interpreted-text role="meth"} and!GetString{.interpreted-text role="meth"} methods that return field values as an integer or a string. (Contributed by Floris Bruynooghe;2125{.interpreted-text role="issue"}.)
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={.interpreted-text role="option"} option to theconfigure{.interpreted-text role="program"} script. - The
!macfs{.interpreted-text role="mod"} module has been removed. This in turn required the!macostools.touched{.interpreted-text role="func"} function to be removed because it depended on the!macfs{.interpreted-text role="mod"} module. (1490190{.interpreted-text role="issue"}) - Many other Mac OS modules have been deprecated and will be removed in Python 3.0:
!_builtinSuites{.interpreted-text role="mod"},!aepack{.interpreted-text role="mod"},!aetools{.interpreted-text role="mod"},!aetypes{.interpreted-text role="mod"},!applesingle{.interpreted-text role="mod"},!appletrawmain{.interpreted-text role="mod"},!appletrunner{.interpreted-text role="mod"},!argvemulator{.interpreted-text role="mod"},!Audio_mac{.interpreted-text role="mod"},!autoGIL{.interpreted-text role="mod"},!Carbon{.interpreted-text role="mod"},!cfmfile{.interpreted-text role="mod"},!CodeWarrior{.interpreted-text role="mod"},!ColorPicker{.interpreted-text role="mod"},!EasyDialogs{.interpreted-text role="mod"},!Explorer{.interpreted-text role="mod"},!Finder{.interpreted-text role="mod"},!FrameWork{.interpreted-text role="mod"},!findertools{.interpreted-text role="mod"},!ic{.interpreted-text role="mod"},!icglue{.interpreted-text role="mod"},!icopen{.interpreted-text role="mod"},!macerrors{.interpreted-text role="mod"},!MacOS{.interpreted-text role="mod"},!macfs{.interpreted-text role="mod"},!macostools{.interpreted-text role="mod"},!macresource{.interpreted-text role="mod"},!MiniAEFrame{.interpreted-text role="mod"},!Nav{.interpreted-text role="mod"},!Netscape{.interpreted-text role="mod"},!OSATerminology{.interpreted-text role="mod"},!pimp{.interpreted-text role="mod"},!PixMapWrapper{.interpreted-text role="mod"},!StdSuites{.interpreted-text role="mod"},!SystemEvents{.interpreted-text role="mod"},!Terminal{.interpreted-text role="mod"}, and!terminalcommand{.interpreted-text role="mod"}.
Port-Specific Changes: IRIX
A number of old IRIX-specific modules were deprecated and will be removed in Python 3.0: !al{.interpreted-text role="mod"} and !AL{.interpreted-text role="mod"}, !cd{.interpreted-text role="mod"}, !cddb{.interpreted-text role="mod"}, !cdplayer{.interpreted-text role="mod"}, !CL{.interpreted-text role="mod"} and !cl{.interpreted-text role="mod"}, !DEVICE{.interpreted-text role="mod"}, !ERRNO{.interpreted-text role="mod"}, !FILE{.interpreted-text role="mod"}, !FL{.interpreted-text role="mod"} and !fl{.interpreted-text role="mod"}, !flp{.interpreted-text role="mod"}, !fm{.interpreted-text role="mod"}, !GET{.interpreted-text role="mod"}, !GLWS{.interpreted-text role="mod"}, !GL{.interpreted-text role="mod"} and !gl{.interpreted-text role="mod"}, !IN{.interpreted-text role="mod"}, !IOCTL{.interpreted-text role="mod"}, !jpeg{.interpreted-text role="mod"}, !panelparser{.interpreted-text role="mod"}, !readcd{.interpreted-text role="mod"}, !SV{.interpreted-text role="mod"} and !sv{.interpreted-text role="mod"}, !torgb{.interpreted-text role="mod"}, !videoreader{.interpreted-text role="mod"}, and !WAIT{.interpreted-text role="mod"}.
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{.interpreted-text role="exc"}.The
__init__{.interpreted-text role="meth"} method ofcollections.deque{.interpreted-text role="class"} now clears any existing contents of the deque before adding elements from the iterable. This change makes the behavior matchlist.__init__().object.__init__{.interpreted-text role="meth"} previously accepted arbitrary arguments and keyword arguments, ignoring them. In Python 2.6, this is no longer allowed and will result in aTypeError{.interpreted-text role="exc"}. This will affect__init__{.interpreted-text role="meth"} methods that end up calling the corresponding method onobject{.interpreted-text role="class"} (perhaps through usingsuper{.interpreted-text role="func"}). See1683368{.interpreted-text role="issue"} for discussion.The
Decimal{.interpreted-text role="class"} constructor now accepts leading and trailing whitespace when passed a string. Previously it would raise anInvalidOperation{.interpreted-text role="exc"} exception. On the other hand, thecreate_decimal{.interpreted-text role="meth"} method ofContext{.interpreted-text role="class"} objects now explicitly disallows extra whitespace, raising aConversionSyntax{.interpreted-text role="exc"} exception.Due to an implementation accident, if you passed a file path to the built-in
__import__{.interpreted-text role="func"} 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{.interpreted-text role="exc"}.C API: the
PyImport_Import{.interpreted-text role="c:func"} andPyImport_ImportModule{.interpreted-text role="c:func"} functions 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{.interpreted-text role="c:func"}.The
socket{.interpreted-text role="mod"} module exceptionsocket.error{.interpreted-text role="exc"} now inherits fromIOError{.interpreted-text role="exc"}. Previously it wasn't a subclass ofStandardError{.interpreted-text role="exc"} but now it is, throughIOError{.interpreted-text role="exc"}. (Implemented by Gregory P. Smith;1706815{.interpreted-text role="issue"}.)The
xmlrpclib <xmlrpc.client>{.interpreted-text role="mod"} module no longer automatically convertsdatetime.date{.interpreted-text role="class"} anddatetime.time{.interpreted-text role="class"} to thexmlrpclib.DateTime <xmlrpc.client.DateTime>{.interpreted-text role="class"} type; the conversion semantics were not necessarily correct for all applications. Code using!xmlrpclib{.interpreted-text role="mod"} should convertdate{.interpreted-text role="class"} and~datetime.time{.interpreted-text role="class"} instances. (1330538{.interpreted-text role="issue"})(3.0-warning mode) The
Exception{.interpreted-text role="class"} class now warns when accessed using slicing or index access; havingException{.interpreted-text role="class"} behave 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_SetArgvEx{.interpreted-text role="c:func"} function was added in Python 2.6.6, letting applications close a security hole when the existing!PySys_SetArgv{.interpreted-text role="c:func"} function was used. Check whether you're calling!PySys_SetArgv{.interpreted-text role="c:func"} and carefully consider whether the application should be using!PySys_SetArgvEx{.interpreted-text role="c:func"} with updatepath set to false.
Acknowledgements {#26acks}
The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner.