blob: fa237ca7ed73afbc103ea046b50225e9539b2445 [file] [log] [blame]
Guido van Rossum715287f2008-12-02 22:34:15 +00001.. _whats-new-in-2.6:
2
Georg Brandl116aa622007-08-15 14:28:22 +00003****************************
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00004 What's New in Python 2.6
Georg Brandl116aa622007-08-15 14:28:22 +00005****************************
6
Christian Heimes02781dc2008-03-21 01:11:52 +00007.. XXX add trademark info for Apple, Microsoft, SourceForge.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008
Benjamin Petersondcc1e112008-09-03 22:22:18 +00009:Author: A.M. Kuchling (amk at amk.ca)
Georg Brandl116aa622007-08-15 14:28:22 +000010:Release: |release|
11:Date: |today|
12
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000013.. $Id$
Christian Heimes5b5e81c2007-12-31 16:14:33 +000014 Rules for maintenance:
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000015
Christian Heimes5b5e81c2007-12-31 16:14:33 +000016 * Anyone can add text to this document. Do not spend very much time
17 on the wording of your changes, because your text will probably
18 get rewritten to some degree.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000019
Christian Heimes5b5e81c2007-12-31 16:14:33 +000020 * The maintainer will go through Misc/NEWS periodically and add
21 changes; it's therefore more important to add your changes to
22 Misc/NEWS than to this file.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000023
Christian Heimes5b5e81c2007-12-31 16:14:33 +000024 * This is not a complete list of every single change; completeness
25 is the purpose of Misc/NEWS. Some changes I consider too small
26 or esoteric to include. If such a change is added to the text,
27 I'll just remove it. (This is another reason you shouldn't spend
28 too much time on writing your addition.)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000029
Christian Heimes5b5e81c2007-12-31 16:14:33 +000030 * If you want to draw your new text to the attention of the
31 maintainer, add 'XXX' to the beginning of the paragraph or
32 section.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000033
Christian Heimes5b5e81c2007-12-31 16:14:33 +000034 * It's OK to just add a fragmentary note about a change. For
35 example: "XXX Describe the transmogrify() function added to the
36 socket module." The maintainer will research the change and
37 write the necessary text.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000038
Christian Heimes5b5e81c2007-12-31 16:14:33 +000039 * You can comment out your additions if you like, but it's not
40 necessary (especially when a final release is some months away).
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000041
Christian Heimes5b5e81c2007-12-31 16:14:33 +000042 * Credit the author of a patch or bugfix. Just the name is
43 sufficient; the e-mail address isn't necessary.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000044
Alexandre Vassalotti6461e102008-05-15 22:09:29 +000045 * It's helpful to add the bug/patch number in a parenthetical comment.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000046
Christian Heimes5b5e81c2007-12-31 16:14:33 +000047 XXX Describe the transmogrify() function added to the socket
48 module.
Christian Heimes33fe8092008-04-13 13:53:33 +000049 (Contributed by P.Y. Developer; :issue:`12345`.)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000050
Alexandre Vassalotti6461e102008-05-15 22:09:29 +000051 This saves the maintainer some effort going through the SVN logs
Christian Heimes5b5e81c2007-12-31 16:14:33 +000052 when researching a change.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000054This article explains the new features in Python 2.6, released on October 1
552008. The release schedule is described in :pep:`361`.
Georg Brandl116aa622007-08-15 14:28:22 +000056
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000057The major theme of Python 2.6 is preparing the migration path to
58Python 3.0, a major redesign of the language. Whenever possible,
59Python 2.6 incorporates new features and syntax from 3.0 while
60remaining compatible with existing code by not removing older features
61or syntax. When it's not possible to do that, Python 2.6 tries to do
62what it can, adding compatibility functions in a
63:mod:`future_builtins` module and a :option:`-3` switch to warn about
64usages that will become unsupported in 3.0.
65
66Some significant new packages have been added to the standard library,
Benjamin Petersonae5360b2008-09-08 23:05:23 +000067such as the :mod:`multiprocessing` and :mod:`json` modules, but
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000068there aren't many new features that aren't related to Python 3.0 in
69some way.
70
71Python 2.6 also sees a number of improvements and bugfixes throughout
72the source. A search through the change logs finds there were 259
73patches applied and 612 bugs fixed between Python 2.5 and 2.6. Both
74figures are likely to be underestimates.
75
Christian Heimes33fe8092008-04-13 13:53:33 +000076This article doesn't attempt to provide a complete specification of
77the new features, but instead provides a convenient overview. For
78full details, you should refer to the documentation for Python 2.6. If
Alexandre Vassalotti6461e102008-05-15 22:09:29 +000079you want to understand the rationale for the design and
80implementation, refer to the PEP for a particular new feature.
81Whenever possible, "What's New in Python" links to the bug/patch item
82for each change.
Georg Brandl116aa622007-08-15 14:28:22 +000083
Christian Heimes5b5e81c2007-12-31 16:14:33 +000084.. Compare with previous release in 2 - 3 sentences here.
85 add hyperlink when the documentation becomes available online.
Georg Brandl116aa622007-08-15 14:28:22 +000086
Christian Heimes5b5e81c2007-12-31 16:14:33 +000087.. ========================================================================
88.. Large, PEP-level features and changes should be described here.
Christian Heimes5b5e81c2007-12-31 16:14:33 +000089.. ========================================================================
Georg Brandl116aa622007-08-15 14:28:22 +000090
Thomas Wouters1b7f8912007-09-19 03:06:30 +000091Python 3.0
92================
93
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000094The development cycle for Python versions 2.6 and 3.0 was
95synchronized, with the alpha and beta releases for both versions being
96made on the same days. The development of 3.0 has influenced many
97features in 2.6.
Georg Brandl9afde1c2007-11-01 20:32:30 +000098
99Python 3.0 is a far-ranging redesign of Python that breaks
100compatibility with the 2.x series. This means that existing Python
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000101code will need some conversion in order to run on
Georg Brandl9afde1c2007-11-01 20:32:30 +0000102Python 3.0. However, not all the changes in 3.0 necessarily break
103compatibility. In cases where new features won't cause existing code
104to break, they've been backported to 2.6 and are described in this
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000105document in the appropriate place. Some of the 3.0-derived features
Georg Brandl9afde1c2007-11-01 20:32:30 +0000106are:
107
108* A :meth:`__complex__` method for converting objects to a complex number.
109* Alternate syntax for catching exceptions: ``except TypeError as exc``.
110* The addition of :func:`functools.reduce` as a synonym for the built-in
111 :func:`reduce` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000112
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000113Python 3.0 adds several new built-in functions and changes the
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000114semantics of some existing builtins. Functions that are new in 3.0
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000115such as :func:`bin` have simply been added to Python 2.6, but existing
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000116builtins haven't been changed; instead, the :mod:`future_builtins`
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000117module has versions with the new 3.0 semantics. Code written to be
118compatible with 3.0 can do ``from future_builtins import hex, map`` as
119necessary.
120
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000121A new command-line switch, :option:`-3`, enables warnings
122about features that will be removed in Python 3.0. You can run code
123with this switch to see how much work will be necessary to port
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000124code to 3.0. The value of this switch is available
125to Python code as the boolean variable :data:`sys.py3kwarning`,
Christian Heimes90aa7642007-12-19 02:45:37 +0000126and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127
128.. seealso::
129
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000130 The 3xxx series of PEPs, which contains proposals for Python 3.0.
131 :pep:`3000` describes the development process for Python 3.0.
132 Start with :pep:`3100` that describes the general goals for Python
133 3.0, and then explore the higher-numbered PEPS that propose
134 specific features.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000135
Christian Heimes90aa7642007-12-19 02:45:37 +0000136
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000137Changes to the Development Process
Christian Heimes90aa7642007-12-19 02:45:37 +0000138==================================================
139
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000140While 2.6 was being developed, the Python development process
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000141underwent two significant changes: we switched from SourceForge's
142issue tracker to a customized Roundup installation, and the
143documentation was converted from LaTeX to reStructuredText.
Christian Heimes90aa7642007-12-19 02:45:37 +0000144
145
146New Issue Tracker: Roundup
147--------------------------------------------------
148
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000149For a long time, the Python developers had been growing increasingly
Christian Heimes02781dc2008-03-21 01:11:52 +0000150annoyed by SourceForge's bug tracker. SourceForge's hosted solution
151doesn't permit much customization; for example, it wasn't possible to
152customize the life cycle of issues.
Christian Heimes90aa7642007-12-19 02:45:37 +0000153
Christian Heimes02781dc2008-03-21 01:11:52 +0000154The infrastructure committee of the Python Software Foundation
155therefore posted a call for issue trackers, asking volunteers to set
156up different products and import some of the bugs and patches from
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000157SourceForge. Four different trackers were examined: `Jira
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000158<http://www.atlassian.com/software/jira/>`__,
159`Launchpad <http://www.launchpad.net>`__,
160`Roundup <http://roundup.sourceforge.net/>`__, and
161`Trac <http://trac.edgewall.org/>`__.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000162The committee eventually settled on Jira
Christian Heimes02781dc2008-03-21 01:11:52 +0000163and Roundup as the two candidates. Jira is a commercial product that
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000164offers no-cost hosted instances to free-software projects; Roundup
Christian Heimes02781dc2008-03-21 01:11:52 +0000165is an open-source project that requires volunteers
166to administer it and a server to host it.
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000167
Christian Heimes02781dc2008-03-21 01:11:52 +0000168After posting a call for volunteers, a new Roundup installation was
169set up at http://bugs.python.org. One installation of Roundup can
170host multiple trackers, and this server now also hosts issue trackers
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000171for Jython and for the Python web site. It will surely find
Christian Heimes33fe8092008-04-13 13:53:33 +0000172other uses in the future. Where possible,
173this edition of "What's New in Python" links to the bug/patch
174item for each change.
Christian Heimes02781dc2008-03-21 01:11:52 +0000175
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000176Hosting of the Python bug tracker is kindly provided by
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000177`Upfront Systems <http://www.upfrontsystems.co.za/>`__
Christian Heimes33fe8092008-04-13 13:53:33 +0000178of Stellenbosch, South Africa. Martin von Loewis put a
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +0000179lot of effort into importing existing bugs and patches from
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000180SourceForge; his scripts for this import operation are at
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000181http://svn.python.org/view/tracker/importer/ and may be useful to
Benjamin Peterson206e3072008-10-19 14:07:49 +0000182other projects wishing to move from SourceForge to Roundup.
Christian Heimes02781dc2008-03-21 01:11:52 +0000183
184.. seealso::
185
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000186 http://bugs.python.org
Martin v. Löwis2a241ca2008-04-05 18:58:09 +0000187 The Python bug tracker.
Christian Heimes02781dc2008-03-21 01:11:52 +0000188
Martin v. Löwis2a241ca2008-04-05 18:58:09 +0000189 http://bugs.jython.org:
190 The Jython bug tracker.
Christian Heimes02781dc2008-03-21 01:11:52 +0000191
Martin v. Löwis2a241ca2008-04-05 18:58:09 +0000192 http://roundup.sourceforge.net/
193 Roundup downloads and documentation.
Christian Heimes02781dc2008-03-21 01:11:52 +0000194
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000195 http://svn.python.org/view/tracker/importer/
196 Martin von Loewis's conversion scripts.
Christian Heimes90aa7642007-12-19 02:45:37 +0000197
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000198New Documentation Format: reStructuredText Using Sphinx
Martin v. Löwis2a241ca2008-04-05 18:58:09 +0000199-----------------------------------------------------------
Christian Heimes90aa7642007-12-19 02:45:37 +0000200
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000201The Python documentation was written using LaTeX since the project
202started around 1989. In the 1980s and early 1990s, most documentation
203was printed out for later study, not viewed online. LaTeX was widely
204used because it provided attractive printed output while remaining
Benjamin Petersondcc1e112008-09-03 22:22:18 +0000205straightforward to write once the basic rules of the markup were
Christian Heimes02781dc2008-03-21 01:11:52 +0000206learned.
Christian Heimes90aa7642007-12-19 02:45:37 +0000207
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000208Today LaTeX is still used for writing publications destined for
209printing, but the landscape for programming tools has shifted. We no
210longer print out reams of documentation; instead, we browse through it
211online and HTML has become the most important format to support.
212Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
213L. Drake Jr., the long-time Python documentation editor, spent a lot
214of time maintaining the conversion process. Occasionally people would
215suggest converting the documentation into SGML and later XML, but
216performing a good conversion is a major task and no one ever committed
217the time required to finish the job.
Christian Heimes90aa7642007-12-19 02:45:37 +0000218
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000219During the 2.6 development cycle, Georg Brandl put a lot of effort
220into building a new toolchain for processing the documentation. The
221resulting package is called Sphinx, and is available from
222http://sphinx.pocoo.org/.
223
224Sphinx concentrates on HTML output, producing attractively styled and
225modern HTML; printed output is still supported through conversion to
226LaTeX. The input format is reStructuredText, a markup syntax
227supporting custom extensions and directives that is commonly used in
228the Python community.
229
230Sphinx is a standalone package that can be used for writing, and
231almost two dozen other projects
232(`listed on the Sphinx web site <http://sphinx.pocoo.org/examples.html>`__)
233have adopted Sphinx as their documentation tool.
Christian Heimes90aa7642007-12-19 02:45:37 +0000234
235.. seealso::
236
Martin v. Löwis2a241ca2008-04-05 18:58:09 +0000237 :ref:`documenting-index`
238 Describes how to write for Python's documentation.
Christian Heimes90aa7642007-12-19 02:45:37 +0000239
Martin v. Löwis2a241ca2008-04-05 18:58:09 +0000240 `Sphinx <http://sphinx.pocoo.org/>`__
241 Documentation and code for the Sphinx toolchain.
242
243 `Docutils <http://docutils.sf.net>`__
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000244 The underlying reStructuredText parser and toolset.
Christian Heimes90aa7642007-12-19 02:45:37 +0000245
246
Guido van Rossum715287f2008-12-02 22:34:15 +0000247.. _pep-0343:
248
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000249PEP 343: The 'with' statement
250=============================
251
252The previous version, Python 2.5, added the ':keyword:`with`'
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000253statement as an optional feature, to be enabled by a ``from __future__
Guido van Rossumb00324f2007-12-04 01:13:14 +0000254import with_statement`` directive. In 2.6 the statement no longer needs to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000255be specially enabled; this means that :keyword:`with` is now always a
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000256keyword. The rest of this section is a copy of the corresponding
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000257section from the "What's New in Python 2.5" document; if you're
258familiar with the ':keyword:`with`' statement
259from Python 2.5, you can skip this section.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000260
261The ':keyword:`with`' statement clarifies code that previously would use
262``try...finally`` blocks to ensure that clean-up code is executed. In this
263section, I'll discuss the statement as it will commonly be used. In the next
264section, I'll examine the implementation details and show how to write objects
265for use with this statement.
266
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000267The ':keyword:`with`' statement is a control-flow structure whose basic
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000268structure is::
269
270 with expression [as variable]:
271 with-block
272
273The expression is evaluated, and it should result in an object that supports the
274context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
Benjamin Petersone0124bd2009-03-09 21:04:33 +0000275methods).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000276
277The object's :meth:`__enter__` is called before *with-block* is executed and
278therefore can run set-up code. It also may return a value that is bound to the
279name *variable*, if given. (Note carefully that *variable* is *not* assigned
280the result of *expression*.)
281
282After execution of the *with-block* is finished, the object's :meth:`__exit__`
283method is called, even if the block raised an exception, and can therefore run
284clean-up code.
285
286Some standard Python objects now support the context management protocol and can
287be used with the ':keyword:`with`' statement. File objects are one example::
288
289 with open('/etc/passwd', 'r') as f:
290 for line in f:
291 print line
292 ... more processing code ...
293
294After this statement has executed, the file object in *f* will have been
295automatically closed, even if the :keyword:`for` loop raised an exception part-
296way through the block.
297
298.. note::
299
300 In this case, *f* is the same object created by :func:`open`, because
301 :meth:`file.__enter__` returns *self*.
302
303The :mod:`threading` module's locks and condition variables also support the
304':keyword:`with`' statement::
305
306 lock = threading.Lock()
307 with lock:
308 # Critical section of code
309 ...
310
311The lock is acquired before the block is executed and always released once the
312block is complete.
313
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000314The :func:`localcontext` function in the :mod:`decimal` module makes it easy
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000315to save and restore the current decimal context, which encapsulates the desired
316precision and rounding characteristics for computations::
317
318 from decimal import Decimal, Context, localcontext
319
320 # Displays with default precision of 28 digits
321 v = Decimal('578')
322 print v.sqrt()
323
324 with localcontext(Context(prec=16)):
325 # All code in this block uses a precision of 16 digits.
326 # The original context is restored on exiting the block.
327 print v.sqrt()
328
329
330.. _new-26-context-managers:
331
332Writing Context Managers
333------------------------
334
335Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
336people will only use ':keyword:`with`' in company with existing objects and
337don't need to know these details, so you can skip the rest of this section if
338you like. Authors of new objects will need to understand the details of the
339underlying implementation and should keep reading.
340
341A high-level explanation of the context management protocol is:
342
343* The expression is evaluated and should result in an object called a "context
344 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
345 methods.
346
347* The context manager's :meth:`__enter__` method is called. The value returned
Christian Heimes2c181612007-12-17 20:04:13 +0000348 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000349 discarded.
350
351* The code in *BLOCK* is executed.
352
Georg Brandlc0e22b72010-03-14 10:51:01 +0000353* If *BLOCK* raises an exception, the context manager's :meth:`__exit__` method
354 is called with three arguments, the exception details (``type, value, traceback``,
355 the same values returned by :func:`sys.exc_info`, which can also be ``None``
356 if no exception occurred). The method's return value controls whether an exception
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000357 is re-raised: any false value re-raises the exception, and ``True`` will result
358 in suppressing it. You'll only rarely want to suppress the exception, because
359 if you do the author of the code containing the ':keyword:`with`' statement will
360 never realize anything went wrong.
361
362* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
363 called, but *type*, *value*, and *traceback* are all ``None``.
364
365Let's think through an example. I won't present detailed code but will only
366sketch the methods necessary for a database that supports transactions.
367
368(For people unfamiliar with database terminology: a set of changes to the
369database are grouped into a transaction. Transactions can be either committed,
370meaning that all the changes are written into the database, or rolled back,
371meaning that the changes are all discarded and the database is unchanged. See
372any database textbook for more information.)
373
374Let's assume there's an object representing a database connection. Our goal will
375be to let the user write code like this::
376
377 db_connection = DatabaseConnection()
378 with db_connection as cursor:
379 cursor.execute('insert into ...')
380 cursor.execute('delete from ...')
381 # ... more operations ...
382
383The transaction should be committed if the code in the block runs flawlessly or
384rolled back if there's an exception. Here's the basic interface for
385:class:`DatabaseConnection` that I'll assume::
386
387 class DatabaseConnection:
388 # Database interface
Christian Heimes2c181612007-12-17 20:04:13 +0000389 def cursor(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000390 "Returns a cursor object and starts a new transaction"
Christian Heimes2c181612007-12-17 20:04:13 +0000391 def commit(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000392 "Commits current transaction"
Christian Heimes2c181612007-12-17 20:04:13 +0000393 def rollback(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394 "Rolls back current transaction"
395
396The :meth:`__enter__` method is pretty easy, having only to start a new
397transaction. For this application the resulting cursor object would be a useful
398result, so the method will return it. The user can then add ``as cursor`` to
399their ':keyword:`with`' statement to bind the cursor to a variable name. ::
400
401 class DatabaseConnection:
402 ...
Christian Heimes2c181612007-12-17 20:04:13 +0000403 def __enter__(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404 # Code to start a new transaction
405 cursor = self.cursor()
406 return cursor
407
408The :meth:`__exit__` method is the most complicated because it's where most of
409the work has to be done. The method has to check if an exception occurred. If
410there was no exception, the transaction is committed. The transaction is rolled
411back if there was an exception.
412
413In the code below, execution will just fall off the end of the function,
414returning the default value of ``None``. ``None`` is false, so the exception
415will be re-raised automatically. If you wished, you could be more explicit and
416add a :keyword:`return` statement at the marked location. ::
417
418 class DatabaseConnection:
419 ...
Christian Heimes2c181612007-12-17 20:04:13 +0000420 def __exit__(self, type, value, tb):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421 if tb is None:
422 # No exception, so commit
423 self.commit()
424 else:
425 # Exception occurred, so rollback.
426 self.rollback()
427 # return False
428
429
Guido van Rossum715287f2008-12-02 22:34:15 +0000430.. _new-module-contextlib:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431
432The contextlib module
433---------------------
434
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000435The :mod:`contextlib` module provides some functions and a decorator that
436are useful when writing objects for use with the ':keyword:`with`' statement.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437
438The decorator is called :func:`contextmanager`, and lets you write a single
439generator function instead of defining a new class. The generator should yield
440exactly one value. The code up to the :keyword:`yield` will be executed as the
441:meth:`__enter__` method, and the value yielded will be the method's return
442value that will get bound to the variable in the ':keyword:`with`' statement's
443:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
444executed in the :meth:`__exit__` method. Any exception raised in the block will
445be raised by the :keyword:`yield` statement.
446
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000447Using this decorator, our database example from the previous section
448could be written as::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
450 from contextlib import contextmanager
451
452 @contextmanager
Christian Heimes2c181612007-12-17 20:04:13 +0000453 def db_transaction(connection):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454 cursor = connection.cursor()
455 try:
456 yield cursor
457 except:
458 connection.rollback()
459 raise
460 else:
461 connection.commit()
462
463 db = DatabaseConnection()
464 with db_transaction(db) as cursor:
465 ...
466
Georg Brandlc0e22b72010-03-14 10:51:01 +0000467The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468that combines a number of context managers so you don't need to write nested
469':keyword:`with`' statements. In this example, the single ':keyword:`with`'
470statement both starts a database transaction and acquires a thread lock::
471
472 lock = threading.Lock()
473 with nested (db_transaction(db), lock) as (cursor, locked):
474 ...
475
Georg Brandlc0e22b72010-03-14 10:51:01 +0000476Finally, the :func:`closing` function returns its argument so that it can be
477bound to a variable, and calls the argument's ``.close()`` method at the end
478of the block. ::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
480 import urllib, sys
481 from contextlib import closing
482
483 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
484 for line in f:
485 sys.stdout.write(line)
486
487
488.. seealso::
489
490 :pep:`343` - The "with" statement
491 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
492 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
493 ':keyword:`with`' statement, which can be helpful in learning how the statement
494 works.
495
496 The documentation for the :mod:`contextlib` module.
497
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000498.. ======================================================================
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499
Christian Heimes90aa7642007-12-19 02:45:37 +0000500.. _pep-0366:
501
502PEP 366: Explicit Relative Imports From a Main Module
503============================================================
504
505Python's :option:`-m` switch allows running a module as a script.
506When you ran a module that was located inside a package, relative
507imports didn't work correctly.
508
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000509The fix for Python 2.6 adds a :attr:`__package__` attribute to
510modules. When this attribute is present, relative imports will be
511relative to the value of this attribute instead of the
512:attr:`__name__` attribute.
513
514PEP 302-style importers can then set :attr:`__package__` as necessary.
515The :mod:`runpy` module that implements the :option:`-m` switch now
516does this, so relative imports will now work correctly in scripts
517running from inside a package.
Christian Heimes90aa7642007-12-19 02:45:37 +0000518
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000519.. ======================================================================
Christian Heimes90aa7642007-12-19 02:45:37 +0000520
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000521.. _pep-0370:
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000522
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000523PEP 370: Per-user ``site-packages`` Directory
524=====================================================
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000525
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000526When you run Python, the module search path ``sys.path`` usually
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000527includes a directory whose path ends in ``"site-packages"``. This
528directory is intended to hold locally-installed packages available to
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000529all users using a machine or a particular site installation.
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000530
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000531Python 2.6 introduces a convention for user-specific site directories.
532The directory varies depending on the platform:
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000533
Georg Brandlc575c902008-09-13 17:46:05 +0000534* Unix and Mac OS X: :file:`~/.local/`
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000535* Windows: :file:`%APPDATA%/Python`
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000536
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000537Within this directory, there will be version-specific subdirectories,
Georg Brandlc575c902008-09-13 17:46:05 +0000538such as :file:`lib/python2.6/site-packages` on Unix/Mac OS and
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000539:file:`Python26/site-packages` on Windows.
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000540
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000541If you don't like the default directory, it can be overridden by an
542environment variable. :envvar:`PYTHONUSERBASE` sets the root
543directory used for all Python versions supporting this feature. On
544Windows, the directory for application-specific data can be changed by
545setting the :envvar:`APPDATA` environment variable. You can also
546modify the :file:`site.py` file for your Python installation.
547
548The feature can be disabled entirely by running Python with the
549:option:`-s` option or setting the :envvar:`PYTHONNOUSERSITE`
550environment variable.
551
552.. seealso::
553
554 :pep:`370` - Per-user ``site-packages`` Directory
555 PEP written and implemented by Christian Heimes.
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000556
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000557
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000558.. ======================================================================
559
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000560.. _pep-0371:
561
562PEP 371: The ``multiprocessing`` Package
563=====================================================
564
Georg Brandl2ee470f2008-07-16 12:55:28 +0000565The new :mod:`multiprocessing` package lets Python programs create new
566processes that will perform a computation and return a result to the
567parent. The parent and child processes can communicate using queues
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000568and pipes, synchronize their operations using locks and semaphores,
569and can share simple arrays of data.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000570
Georg Brandl2ee470f2008-07-16 12:55:28 +0000571The :mod:`multiprocessing` module started out as an exact emulation of
572the :mod:`threading` module using processes instead of threads. That
573goal was discarded along the path to Python 2.6, but the general
574approach of the module is still similar. The fundamental class
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000575is the :class:`Process`, which is passed a callable object and
576a collection of arguments. The :meth:`start` method
Georg Brandl2ee470f2008-07-16 12:55:28 +0000577sets the callable running in a subprocess, after which you can call
578the :meth:`is_alive` method to check whether the subprocess is still running
579and the :meth:`join` method to wait for the process to exit.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000580
Georg Brandl2ee470f2008-07-16 12:55:28 +0000581Here's a simple example where the subprocess will calculate a
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000582factorial. The function doing the calculation is written strangely so
583that it takes significantly longer when the input argument is a
Georg Brandl2ee470f2008-07-16 12:55:28 +0000584multiple of 4.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000585
Georg Brandl2ee470f2008-07-16 12:55:28 +0000586::
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000587
Georg Brandl2ee470f2008-07-16 12:55:28 +0000588 import time
589 from multiprocessing import Process, Queue
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000590
Georg Brandl2ee470f2008-07-16 12:55:28 +0000591
592 def factorial(queue, N):
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000593 "Compute a factorial."
594 # If N is a multiple of 4, this function will take much longer.
595 if (N % 4) == 0:
596 time.sleep(.05 * N/4)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000597
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000598 # Calculate the result
599 fact = 1L
600 for i in range(1, N+1):
601 fact = fact * i
Georg Brandl2ee470f2008-07-16 12:55:28 +0000602
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000603 # Put the result on the queue
604 queue.put(fact)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000605
606 if __name__ == '__main__':
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000607 queue = Queue()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000608
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000609 N = 5
Georg Brandl2ee470f2008-07-16 12:55:28 +0000610
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000611 p = Process(target=factorial, args=(queue, N))
612 p.start()
613 p.join()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000614
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000615 result = queue.get()
616 print 'Factorial', N, '=', result
Georg Brandl2ee470f2008-07-16 12:55:28 +0000617
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000618A :class:`Queue` is used to communicate the input parameter *N* and
619the result. The :class:`Queue` object is stored in a global variable.
620The child process will use the value of the variable when the child
621was created; because it's a :class:`Queue`, parent and child can use
622the object to communicate. (If the parent were to change the value of
623the global variable, the child's value would be unaffected, and vice
624versa.)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000625
626Two other classes, :class:`Pool` and :class:`Manager`, provide
627higher-level interfaces. :class:`Pool` will create a fixed number of
628worker processes, and requests can then be distributed to the workers
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000629by calling :meth:`apply` or :meth:`apply_async` to add a single request,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000630and :meth:`map` or :meth:`map_async` to add a number of
Georg Brandl2ee470f2008-07-16 12:55:28 +0000631requests. The following code uses a :class:`Pool` to spread requests
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000632across 5 worker processes and retrieve a list of results::
Georg Brandl2ee470f2008-07-16 12:55:28 +0000633
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000634 from multiprocessing import Pool
Georg Brandl2ee470f2008-07-16 12:55:28 +0000635
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000636 def factorial(N, dictionary):
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000637 "Compute a factorial."
638 ...
Georg Brandl2ee470f2008-07-16 12:55:28 +0000639 p = Pool(5)
640 result = p.map(factorial, range(1, 1000, 10))
641 for v in result:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000642 print v
Georg Brandl2ee470f2008-07-16 12:55:28 +0000643
644This produces the following output::
645
646 1
647 39916800
648 51090942171709440000
649 8222838654177922817725562880000000
650 33452526613163807108170062053440751665152000000000
651 ...
652
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000653The other high-level interface, the :class:`Manager` class, creates a
654separate server process that can hold master copies of Python data
655structures. Other processes can then access and modify these data
656structures using proxy objects. The following example creates a
657shared dictionary by calling the :meth:`dict` method; the worker
658processes then insert values into the dictionary. (Locking is not
659done for you automatically, which doesn't matter in this example.
660:class:`Manager`'s methods also include :meth:`Lock`, :meth:`RLock`,
661and :meth:`Semaphore` to create shared locks.)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000662
663::
664
665 import time
666 from multiprocessing import Pool, Manager
667
668 def factorial(N, dictionary):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000669 "Compute a factorial."
670 # Calculate the result
671 fact = 1L
672 for i in range(1, N+1):
673 fact = fact * i
Georg Brandl2ee470f2008-07-16 12:55:28 +0000674
675 # Store result in dictionary
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000676 dictionary[N] = fact
Georg Brandl2ee470f2008-07-16 12:55:28 +0000677
678 if __name__ == '__main__':
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000679 p = Pool(5)
680 mgr = Manager()
681 d = mgr.dict() # Create shared dictionary
Georg Brandl2ee470f2008-07-16 12:55:28 +0000682
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000683 # Run tasks using the pool
684 for N in range(1, 1000, 10):
685 p.apply_async(factorial, (N, d))
Georg Brandl2ee470f2008-07-16 12:55:28 +0000686
Georg Brandl3cfdd9c2009-06-04 10:21:10 +0000687 # Mark pool as closed -- no more tasks can be added.
688 p.close()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000689
Georg Brandl3cfdd9c2009-06-04 10:21:10 +0000690 # Wait for tasks to exit
691 p.join()
Georg Brandl2ee470f2008-07-16 12:55:28 +0000692
Georg Brandl3cfdd9c2009-06-04 10:21:10 +0000693 # Output results
694 for k, v in sorted(d.items()):
695 print k, v
Georg Brandl2ee470f2008-07-16 12:55:28 +0000696
697This will produce the output::
698
699 1 1
700 11 39916800
701 21 51090942171709440000
702 31 8222838654177922817725562880000000
703 41 33452526613163807108170062053440751665152000000000
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000704 51 15511187532873822802242430164693032110632597200169861120000...
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000705
706.. seealso::
707
Georg Brandl2ee470f2008-07-16 12:55:28 +0000708 The documentation for the :mod:`multiprocessing` module.
709
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000710 :pep:`371` - Addition of the multiprocessing package
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000711 PEP written by Jesse Noller and Richard Oudkerk;
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000712 implemented by Richard Oudkerk and Jesse Noller.
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000713
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000714
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000715.. ======================================================================
716
Christian Heimes78644762008-03-04 23:39:23 +0000717.. _pep-3101:
718
719PEP 3101: Advanced String Formatting
720=====================================================
721
Benjamin Peterson1e2f0502008-05-26 12:52:02 +0000722In Python 3.0, the `%` operator is supplemented by a more powerful string
723formatting method, :meth:`format`. Support for the :meth:`str.format` method
724has been backported to Python 2.6.
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000725
Christian Heimes02781dc2008-03-21 01:11:52 +0000726In 2.6, both 8-bit and Unicode strings have a `.format()` method that
727treats the string as a template and takes the arguments to be formatted.
728The formatting template uses curly brackets (`{`, `}`) as special characters::
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000729
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000730 >>> # Substitute positional argument 0 into the string.
731 >>> "User ID: {0}".format("root")
732 'User ID: root'
733 >>> # Use the named keyword arguments
734 >>> "User ID: {uid} Last seen: {last_login}".format(
735 ... uid="root",
736 ... last_login = "5 Mar 2008 07:20")
737 'User ID: root Last seen: 5 Mar 2008 07:20'
Christian Heimes02781dc2008-03-21 01:11:52 +0000738
739Curly brackets can be escaped by doubling them::
740
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000741 >>> "Empty dict: {{}}".format()
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000742 "Empty dict: {}"
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000743
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000744Field names can be integers indicating positional arguments, such as
745``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
Christian Heimes02781dc2008-03-21 01:11:52 +0000746supply compound field names that read attributes or access dictionary keys::
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000747
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000748 >>> import sys
749 >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
750 Platform: darwin
Georg Brandl48310cd2009-01-03 21:18:54 +0000751 Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000752 [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
Christian Heimes02781dc2008-03-21 01:11:52 +0000753
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000754 >>> import mimetypes
755 >>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
756 'Content-type: video/mp4'
Christian Heimes02781dc2008-03-21 01:11:52 +0000757
758Note that when using dictionary-style notation such as ``[.mp4]``, you
759don't need to put any quotation marks around the string; it will look
760up the value using ``.mp4`` as the key. Strings beginning with a
761number will be converted to an integer. You can't write more
762complicated expressions inside a format string.
763
764So far we've shown how to specify which field to substitute into the
765resulting string. The precise formatting used is also controllable by
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000766adding a colon followed by a format specifier. For example::
Christian Heimes02781dc2008-03-21 01:11:52 +0000767
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000768 >>> # Field 0: left justify, pad to 15 characters
769 >>> # Field 1: right justify, pad to 6 characters
770 >>> fmt = '{0:15} ${1:>6}'
771 >>> fmt.format('Registration', 35)
772 'Registration $ 35'
773 >>> fmt.format('Tutorial', 50)
774 'Tutorial $ 50'
775 >>> fmt.format('Banquet', 125)
776 'Banquet $ 125'
Christian Heimes02781dc2008-03-21 01:11:52 +0000777
Christian Heimes4fbc72b2008-03-22 00:47:35 +0000778Format specifiers can reference other fields through nesting::
Christian Heimes02781dc2008-03-21 01:11:52 +0000779
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000780 >>> fmt = '{0:{1}}'
781 >>> width = 15
782 >>> fmt.format('Invoice #1234', width)
783 'Invoice #1234 '
784 >>> width = 35
785 >>> fmt.format('Invoice #1234', width)
786 'Invoice #1234 '
Christian Heimes02781dc2008-03-21 01:11:52 +0000787
788The alignment of a field within the desired width can be specified:
789
790================ ============================================
791Character Effect
792================ ============================================
793< (default) Left-align
794> Right-align
795^ Center
796= (For numeric types only) Pad after the sign.
797================ ============================================
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000798
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000799Format specifiers can also include a presentation type, which
Christian Heimesf6cd9672008-03-26 13:45:42 +0000800controls how the value is formatted. For example, floating-point numbers
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000801can be formatted as a general number or in exponential notation::
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000802
Christian Heimesf6cd9672008-03-26 13:45:42 +0000803 >>> '{0:g}'.format(3.75)
804 '3.75'
805 >>> '{0:e}'.format(3.75)
806 '3.750000e+00'
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000807
Christian Heimesf6cd9672008-03-26 13:45:42 +0000808A variety of presentation types are available. Consult the 2.6
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000809documentation for a :ref:`complete list <formatstrings>`; here's a sample:
Christian Heimesf6cd9672008-03-26 13:45:42 +0000810
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000811===== ========================================================================
812``b`` Binary. Outputs the number in base 2.
813``c`` Character. Converts the integer to the corresponding Unicode character
814 before printing.
815``d`` Decimal Integer. Outputs the number in base 10.
816``o`` Octal format. Outputs the number in base 8.
817``x`` Hex format. Outputs the number in base 16, using lower-case letters for
818 the digits above 9.
819``e`` Exponent notation. Prints the number in scientific notation using the
820 letter 'e' to indicate the exponent.
821``g`` General format. This prints the number as a fixed-point number, unless
822 the number is too large, in which case it switches to 'e' exponent
823 notation.
824``n`` Number. This is the same as 'g' (for floats) or 'd' (for integers),
825 except that it uses the current locale setting to insert the appropriate
826 number separator characters.
827``%`` Percentage. Multiplies the number by 100 and displays in fixed ('f')
828 format, followed by a percent sign.
829===== ========================================================================
Christian Heimesf6cd9672008-03-26 13:45:42 +0000830
Georg Brandl734e2682008-08-12 08:18:18 +0000831Classes and types can define a :meth:`__format__` method to control how they're
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000832formatted. It receives a single argument, the format specifier::
833
834 def __format__(self, format_spec):
835 if isinstance(format_spec, unicode):
836 return unicode(str(self))
837 else:
838 return str(self)
839
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000840There's also a :func:`format` builtin that will format a single
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000841value. It calls the type's :meth:`__format__` method with the
842provided specifier::
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000843
844 >>> format(75.6564, '.2f')
845 '75.66'
846
Georg Brandl0c77a822008-06-10 16:37:50 +0000847
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000848.. seealso::
849
Benjamin Peterson1e2f0502008-05-26 12:52:02 +0000850 :ref:`formatstrings`
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000851 The reference documentation for format fields.
Benjamin Peterson1e2f0502008-05-26 12:52:02 +0000852
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000853 :pep:`3101` - Advanced String Formatting
Benjamin Peterson1e2f0502008-05-26 12:52:02 +0000854 PEP written by Talin. Implemented by Eric Smith.
Christian Heimes78644762008-03-04 23:39:23 +0000855
856.. ======================================================================
857
Christian Heimes02781dc2008-03-21 01:11:52 +0000858.. _pep-3105:
859
860PEP 3105: ``print`` As a Function
861=====================================================
862
863The ``print`` statement becomes the :func:`print` function in Python 3.0.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000864Making :func:`print` a function makes it possible to replace the function
865by doing ``def print(...)`` or importing a new function from somewhere else.
Christian Heimes02781dc2008-03-21 01:11:52 +0000866
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000867Python 2.6 has a ``__future__`` import that removes ``print`` as language
Christian Heimes02781dc2008-03-21 01:11:52 +0000868syntax, letting you use the functional form instead. For example::
869
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000870 >>> from __future__ import print_function
871 >>> print('# of entries', len(dictionary), file=sys.stderr)
Christian Heimes02781dc2008-03-21 01:11:52 +0000872
873The signature of the new function is::
874
875 def print(*args, sep=' ', end='\n', file=None)
876
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000877
Christian Heimes02781dc2008-03-21 01:11:52 +0000878The parameters are:
879
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000880 * *args*: positional arguments whose values will be printed out.
881 * *sep*: the separator, which will be printed between arguments.
882 * *end*: the ending text, which will be printed after all of the
Christian Heimes02781dc2008-03-21 01:11:52 +0000883 arguments have been output.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000884 * *file*: the file object to which the output will be sent.
Christian Heimes02781dc2008-03-21 01:11:52 +0000885
886.. seealso::
887
888 :pep:`3105` - Make print a function
889 PEP written by Georg Brandl.
890
891.. ======================================================================
892
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893.. _pep-3110:
894
895PEP 3110: Exception-Handling Changes
896=====================================================
897
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000898One error that Python programmers occasionally make
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000899is writing the following code::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000900
901 try:
902 ...
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000903 except TypeError, ValueError: # Wrong!
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904 ...
905
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000906The author is probably trying to catch both :exc:`TypeError` and
907:exc:`ValueError` exceptions, but this code actually does something
908different: it will catch :exc:`TypeError` and bind the resulting
909exception object to the local name ``"ValueError"``. The
910:exc:`ValueError` exception will not be caught at all. The correct
911code specifies a tuple of exceptions::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912
913 try:
914 ...
915 except (TypeError, ValueError):
916 ...
917
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000918This error happens because the use of the comma here is ambiguous:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919does it indicate two different nodes in the parse tree, or a single
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000920node that's a tuple?
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000921
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000922Python 3.0 makes this unambiguous by replacing the comma with the word
923"as". To catch an exception and store the exception object in the
924variable ``exc``, you must write::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
926 try:
927 ...
928 except TypeError as exc:
929 ...
930
931Python 3.0 will only support the use of "as", and therefore interprets
932the first example as catching two different exceptions. Python 2.6
933supports both the comma and "as", so existing code will continue to
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000934work. We therefore suggest using "as" when writing new Python code
935that will only be executed with 2.6.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
937.. seealso::
938
939 :pep:`3110` - Catching Exceptions in Python 3000
940 PEP written and implemented by Collin Winter.
941
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000942.. ======================================================================
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000944.. _pep-3112:
945
946PEP 3112: Byte Literals
947=====================================================
948
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000949Python 3.0 adopts Unicode as the language's fundamental string type and
950denotes 8-bit literals differently, either as ``b'string'``
951or using a :class:`bytes` constructor. For future compatibility,
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000952Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
953and it also supports the ``b''`` notation.
954
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000955
956The 2.6 :class:`str` differs from 3.0's :class:`bytes` type in various
957ways; most notably, the constructor is completely different. In 3.0,
958``bytes([65, 66, 67])`` is 3 elements long, containing the bytes
959representing ``ABC``; in 2.6, ``bytes([65, 66, 67])`` returns the
96012-byte string representing the :func:`str` of the list.
961
962The primary use of :class:`bytes` in 2.6 will be to write tests of
963object type such as ``isinstance(x, bytes)``. This will help the 2to3
964converter, which can't tell whether 2.x code intends strings to
Georg Brandl48310cd2009-01-03 21:18:54 +0000965contain either characters or 8-bit bytes; you can now
966use either :class:`bytes` or :class:`str` to represent your intention
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000967exactly, and the resulting code will also be correct in Python 3.0.
968
Christian Heimes5e696852008-04-09 08:37:03 +0000969There's also a ``__future__`` import that causes all string literals
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000970to become Unicode strings. This means that ``\u`` escape sequences
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000971can be used to include Unicode characters::
972
Christian Heimes5e696852008-04-09 08:37:03 +0000973
Neal Norwitz32dde222008-04-15 06:43:13 +0000974 from __future__ import unicode_literals
975
976 s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
977 '\u3081\u3000\u751f\u305f\u307e\u3054')
978
979 print len(s) # 12 Unicode characters
980
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000981At the C level, Python 3.0 will rename the existing 8-bit
982string type, called :ctype:`PyStringObject` in Python 2.x,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000983to :ctype:`PyBytesObject`. Python 2.6 uses ``#define``
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000984to support using the names :cfunc:`PyBytesObject`,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000985:cfunc:`PyBytes_Check`, :cfunc:`PyBytes_FromStringAndSize`,
986and all the other functions and macros used with strings.
Christian Heimes5e696852008-04-09 08:37:03 +0000987
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000988Instances of the :class:`bytes` type are immutable just
989as strings are. A new :class:`bytearray` type stores a mutable
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000990sequence of bytes::
991
992 >>> bytearray([65, 66, 67])
993 bytearray(b'ABC')
994 >>> b = bytearray(u'\u21ef\u3244', 'utf-8')
995 >>> b
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000996 bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
Benjamin Petersonf9c98b42008-07-02 16:19:28 +0000997 >>> b[0] = '\xe3'
998 >>> b
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000999 bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001000 >>> unicode(str(b), 'utf-8')
1001 u'\u31ef \u3244'
1002
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001003Byte arrays support most of the methods of string types, such as
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001004:meth:`startswith`/:meth:`endswith`, :meth:`find`/:meth:`rfind`,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001005and some of the methods of lists, such as :meth:`append`,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001006:meth:`pop`, and :meth:`reverse`.
1007
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001008::
1009
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001010 >>> b = bytearray('ABC')
1011 >>> b.append('d')
1012 >>> b.append(ord('e'))
1013 >>> b
1014 bytearray(b'ABCde')
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001015
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001016There's also a corresponding C API, with
1017:cfunc:`PyByteArray_FromObject`,
1018:cfunc:`PyByteArray_FromStringAndSize`,
1019and various other functions.
1020
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001021.. seealso::
1022
1023 :pep:`3112` - Bytes literals in Python 3000
1024 PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
1025
1026.. ======================================================================
1027
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001028.. _pep-3116:
1029
1030PEP 3116: New I/O Library
1031=====================================================
1032
Christian Heimes5e696852008-04-09 08:37:03 +00001033Python's built-in file objects support a number of methods, but
1034file-like objects don't necessarily support all of them. Objects that
1035imitate files usually support :meth:`read` and :meth:`write`, but they
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001036may not support :meth:`readline`, for example. Python 3.0 introduces
1037a layered I/O library in the :mod:`io` module that separates buffering
1038and text-handling features from the fundamental read and write
1039operations.
Christian Heimes5e696852008-04-09 08:37:03 +00001040
1041There are three levels of abstract base classes provided by
1042the :mod:`io` module:
1043
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001044* :class:`RawIOBase` defines raw I/O operations: :meth:`read`,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001045 :meth:`readinto`,
Christian Heimes5e696852008-04-09 08:37:03 +00001046 :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
1047 and :meth:`close`.
1048 Most of the methods of this class will often map to a single system call.
1049 There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable`
1050 methods for determining what operations a given object will allow.
1051
1052 Python 3.0 has concrete implementations of this class for files and
1053 sockets, but Python 2.6 hasn't restructured its file and socket objects
1054 in this way.
1055
1056 .. XXX should 2.6 register them in io.py?
1057
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001058* :class:`BufferedIOBase` is an abstract base class that
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001059 buffers data in memory to reduce the number of
Christian Heimes5e696852008-04-09 08:37:03 +00001060 system calls used, making I/O processing more efficient.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001061 It supports all of the methods of :class:`RawIOBase`,
Christian Heimes5e696852008-04-09 08:37:03 +00001062 and adds a :attr:`raw` attribute holding the underlying raw object.
1063
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001064 There are five concrete classes implementing this ABC.
1065 :class:`BufferedWriter` and :class:`BufferedReader` are for objects
1066 that support write-only or read-only usage that have a :meth:`seek`
1067 method for random access. :class:`BufferedRandom` objects support
1068 read and write access upon the same underlying stream, and
1069 :class:`BufferedRWPair` is for objects such as TTYs that have both
1070 read and write operations acting upon unconnected streams of data.
1071 The :class:`BytesIO` class supports reading, writing, and seeking
1072 over an in-memory buffer.
Christian Heimes5e696852008-04-09 08:37:03 +00001073
1074* :class:`TextIOBase`: Provides functions for reading and writing
1075 strings (remember, strings will be Unicode in Python 3.0),
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001076 and supporting universal newlines. :class:`TextIOBase` defines
1077 the :meth:`readline` method and supports iteration upon
1078 objects.
Christian Heimes5e696852008-04-09 08:37:03 +00001079
1080 There are two concrete implementations. :class:`TextIOWrapper`
1081 wraps a buffered I/O object, supporting all of the methods for
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001082 text I/O and adding a :attr:`buffer` attribute for access
Christian Heimes5e696852008-04-09 08:37:03 +00001083 to the underlying object. :class:`StringIO` simply buffers
1084 everything in memory without ever writing anything to disk.
1085
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001086 (In Python 2.6, :class:`io.StringIO` is implemented in
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001087 pure Python, so it's pretty slow. You should therefore stick with the
1088 existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some
Christian Heimes5e696852008-04-09 08:37:03 +00001089 point Python 3.0's :mod:`io` module will be rewritten into C for speed,
1090 and perhaps the C implementation will be backported to the 2.x releases.)
1091
Christian Heimes5e696852008-04-09 08:37:03 +00001092In Python 2.6, the underlying implementations haven't been
1093restructured to build on top of the :mod:`io` module's classes. The
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001094module is being provided to make it easier to write code that's
Christian Heimes5e696852008-04-09 08:37:03 +00001095forward-compatible with 3.0, and to save developers the effort of writing
1096their own implementations of buffering and text I/O.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001097
1098.. seealso::
1099
1100 :pep:`3116` - New I/O
1101 PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
Neal Norwitz32dde222008-04-15 06:43:13 +00001102 Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
1103 Jeremy Hylton, Martin von Loewis, Tony Lownds, and others.
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001104
1105.. ======================================================================
1106
Christian Heimesf6cd9672008-03-26 13:45:42 +00001107.. _pep-3118:
1108
1109PEP 3118: Revised Buffer Protocol
1110=====================================================
1111
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001112The buffer protocol is a C-level API that lets Python types
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001113exchange pointers into their internal representations. A
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001114memory-mapped file can be viewed as a buffer of characters, for
1115example, and this lets another module such as :mod:`re`
1116treat memory-mapped files as a string of characters to be searched.
1117
1118The primary users of the buffer protocol are numeric-processing
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001119packages such as NumPy, which expose the internal representation
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001120of arrays so that callers can write data directly into an array instead
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001121of going through a slower API. This PEP updates the buffer protocol in light of experience
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001122from NumPy development, adding a number of new features
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001123such as indicating the shape of an array or locking a memory region.
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001124
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001125The most important new C API function is
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001126``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which
1127takes an object and a set of flags, and fills in the
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001128``Py_buffer`` structure with information
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001129about the object's memory representation. Objects
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001130can use this operation to lock memory in place
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001131while an external caller could be modifying the contents,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001132so there's a corresponding ``PyBuffer_Release(Py_buffer *view)`` to
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001133indicate that the external caller is done.
1134
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001135.. XXX PyObject_GetBuffer not documented in c-api
1136
1137The *flags* argument to :cfunc:`PyObject_GetBuffer` specifies
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001138constraints upon the memory returned. Some examples are:
1139
1140 * :const:`PyBUF_WRITABLE` indicates that the memory must be writable.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001141
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001142 * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory.
1143
1144 * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS`
1145 requests a C-contiguous (last dimension varies the fastest) or
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001146 Fortran-contiguous (first dimension varies the fastest) array layout.
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001147
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001148Two new argument codes for :cfunc:`PyArg_ParseTuple`,
1149``s*`` and ``z*``, return locked buffer objects for a parameter.
Christian Heimesf6cd9672008-03-26 13:45:42 +00001150
1151.. seealso::
1152
1153 :pep:`3118` - Revising the buffer protocol
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001154 PEP written by Travis Oliphant and Carl Banks; implemented by
1155 Travis Oliphant.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001156
Christian Heimesf6cd9672008-03-26 13:45:42 +00001157
1158.. ======================================================================
1159
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160.. _pep-3119:
1161
1162PEP 3119: Abstract Base Classes
1163=====================================================
1164
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001165Some object-oriented languages such as Java support interfaces,
1166declaring that a class has a given set of methods or supports a given
1167access protocol. Abstract Base Classes (or ABCs) are an equivalent
1168feature for Python. The ABC support consists of an :mod:`abc` module
1169containing a metaclass called :class:`ABCMeta`, special handling of
1170this metaclass by the :func:`isinstance` and :func:`issubclass`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001171builtins, and a collection of basic ABCs that the Python developers
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001172think will be widely useful. Future versions of Python will probably
1173add more ABCs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001175Let's say you have a particular class and wish to know whether it supports
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001176dictionary-style access. The phrase "dictionary-style" is vague, however.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001177It probably means that accessing items with ``obj[1]`` works.
1178Does it imply that setting items with ``obj[2] = value`` works?
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001179Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items`
1180methods? What about the iterative variants such as :meth:`iterkeys`? :meth:`copy`
1181and :meth:`update`? Iterating over the object with :func:`iter`?
Christian Heimes3f419af2008-01-04 03:08:33 +00001182
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001183The Python 2.6 :mod:`collections` module includes a number of
1184different ABCs that represent these distinctions. :class:`Iterable`
1185indicates that a class defines :meth:`__iter__`, and
1186:class:`Container` means the class defines a :meth:`__contains__`
1187method and therefore supports ``x in y`` expressions. The basic
1188dictionary interface of getting items, setting items, and
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001189:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
1190:class:`MutableMapping` ABC.
Christian Heimes3f419af2008-01-04 03:08:33 +00001191
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001192You can derive your own classes from a particular ABC
1193to indicate they support that ABC's interface::
Christian Heimes3f419af2008-01-04 03:08:33 +00001194
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001195 import collections
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001196
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001197 class Storage(collections.MutableMapping):
1198 ...
Christian Heimes3f419af2008-01-04 03:08:33 +00001199
Christian Heimes3f419af2008-01-04 03:08:33 +00001200
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001201Alternatively, you could write the class without deriving from
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001202the desired ABC and instead register the class by
1203calling the ABC's :meth:`register` method::
Christian Heimes3f419af2008-01-04 03:08:33 +00001204
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001205 import collections
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001206
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001207 class Storage:
1208 ...
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001209
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001210 collections.MutableMapping.register(Storage)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001211
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001212For classes that you write, deriving from the ABC is probably clearer.
1213The :meth:`register` method is useful when you've written a new
1214ABC that can describe an existing type or class, or if you want
1215to declare that some third-party class implements an ABC.
1216For example, if you defined a :class:`PrintableType` ABC,
Benjamin Petersond6313712008-07-31 16:23:04 +00001217it's legal to do::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001218
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001219 # Register Python's types
1220 PrintableType.register(int)
1221 PrintableType.register(float)
1222 PrintableType.register(str)
1223
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001224Classes should obey the semantics specified by an ABC, but
1225Python can't check this; it's up to the class author to
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001226understand the ABC's requirements and to implement the code accordingly.
1227
1228To check whether an object supports a particular interface, you can
1229now write::
1230
1231 def func(d):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001232 if not isinstance(d, collections.MutableMapping):
1233 raise ValueError("Mapping object expected, not %r" % d)
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001234
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001235Don't feel that you must now begin writing lots of checks as in the
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001236above example. Python has a strong tradition of duck-typing, where
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001237explicit type-checking is never done and code simply calls methods on
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001238an object, trusting that those methods will be there and raising an
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001239exception if they aren't. Be judicious in checking for ABCs and only
1240do it where it's absolutely necessary.
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001241
1242You can write your own ABCs by using ``abc.ABCMeta`` as the
1243metaclass in a class definition::
1244
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001245 from abc import ABCMeta, abstractmethod
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001246
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001247 class Drawable():
1248 __metaclass__ = ABCMeta
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001249
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001250 @abstractmethod
1251 def draw(self, x, y, scale=1.0):
1252 pass
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001253
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001254 def draw_doubled(self, x, y):
1255 self.draw(x, y, scale=2.0)
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001256
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001257
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001258 class Square(Drawable):
1259 def draw(self, x, y, scale):
1260 ...
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001261
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001262
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001263In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
1264renders the object at twice its size and can be implemented in terms
1265of other methods described in :class:`Drawable`. Classes implementing
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001266this ABC therefore don't need to provide their own implementation
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001267of :meth:`draw_doubled`, though they can do so. An implementation
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001268of :meth:`draw` is necessary, though; the ABC can't provide
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001269a useful generic implementation.
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001270
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001271You can apply the ``@abstractmethod`` decorator to methods such as
1272:meth:`draw` that must be implemented; Python will then raise an
1273exception for classes that don't define the method.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001274Note that the exception is only raised when you actually
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001275try to create an instance of a subclass lacking the method::
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001276
Benjamin Petersondcc1e112008-09-03 22:22:18 +00001277 >>> class Circle(Drawable):
1278 ... pass
1279 ...
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001280 >>> c = Circle()
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001281 Traceback (most recent call last):
1282 File "<stdin>", line 1, in <module>
Benjamin Petersondcc1e112008-09-03 22:22:18 +00001283 TypeError: Can't instantiate abstract class Circle with abstract methods draw
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001284 >>>
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001285
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001286Abstract data attributes can be declared using the
1287``@abstractproperty`` decorator::
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001288
Benjamin Petersondcc1e112008-09-03 22:22:18 +00001289 from abc import abstractproperty
1290 ...
1291
Christian Heimesfaf2f632008-01-06 16:59:19 +00001292 @abstractproperty
1293 def readonly(self):
1294 return self._x
Christian Heimes3f419af2008-01-04 03:08:33 +00001295
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001296Subclasses must then define a :meth:`readonly` property.
Christian Heimes3f419af2008-01-04 03:08:33 +00001297
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298.. seealso::
1299
1300 :pep:`3119` - Introducing Abstract Base Classes
1301 PEP written by Guido van Rossum and Talin.
Martin v. Löwis2a241ca2008-04-05 18:58:09 +00001302 Implemented by Guido van Rossum.
Christian Heimes90aa7642007-12-19 02:45:37 +00001303 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl116aa622007-08-15 14:28:22 +00001304
Christian Heimes679db4a2008-01-18 09:56:22 +00001305.. ======================================================================
1306
Christian Heimes78644762008-03-04 23:39:23 +00001307.. _pep-3127:
1308
1309PEP 3127: Integer Literal Support and Syntax
1310=====================================================
1311
Christian Heimes5e696852008-04-09 08:37:03 +00001312Python 3.0 changes the syntax for octal (base-8) integer literals,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001313prefixing them with "0o" or "0O" instead of a leading zero, and adds
1314support for binary (base-2) integer literals, signalled by a "0b" or
1315"0B" prefix.
Christian Heimes78644762008-03-04 23:39:23 +00001316
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001317Python 2.6 doesn't drop support for a leading 0 signalling
Christian Heimes5e696852008-04-09 08:37:03 +00001318an octal number, but it does add support for "0o" and "0b"::
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001319
Christian Heimes5e696852008-04-09 08:37:03 +00001320 >>> 0o21, 2*8 + 1
1321 (17, 17)
1322 >>> 0b101111
1323 47
Christian Heimes78644762008-03-04 23:39:23 +00001324
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001325The :func:`oct` builtin still returns numbers
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001326prefixed with a leading zero, and a new :func:`bin`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001327builtin returns the binary representation for a number::
Christian Heimes78644762008-03-04 23:39:23 +00001328
Christian Heimes5e696852008-04-09 08:37:03 +00001329 >>> oct(42)
1330 '052'
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001331 >>> future_builtins.oct(42)
1332 '0o52'
Christian Heimes5e696852008-04-09 08:37:03 +00001333 >>> bin(173)
1334 '0b10101101'
1335
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001336The :func:`int` and :func:`long` builtins will now accept the "0o"
Christian Heimes5e696852008-04-09 08:37:03 +00001337and "0b" prefixes when base-8 or base-2 are requested, or when the
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001338*base* argument is zero (signalling that the base used should be
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001339determined from the string)::
Christian Heimes5e696852008-04-09 08:37:03 +00001340
1341 >>> int ('0o52', 0)
1342 42
1343 >>> int('1101', 2)
1344 13
1345 >>> int('0b1101', 2)
1346 13
1347 >>> int('0b1101', 0)
1348 13
1349
Christian Heimes78644762008-03-04 23:39:23 +00001350
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001351.. seealso::
1352
1353 :pep:`3127` - Integer Literal Support and Syntax
Christian Heimes5e696852008-04-09 08:37:03 +00001354 PEP written by Patrick Maupin; backported to 2.6 by
1355 Eric Smith.
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001356
Christian Heimes78644762008-03-04 23:39:23 +00001357.. ======================================================================
1358
1359.. _pep-3129:
1360
1361PEP 3129: Class Decorators
1362=====================================================
1363
Christian Heimes02781dc2008-03-21 01:11:52 +00001364Decorators have been extended from functions to classes. It's now legal to
1365write::
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001366
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001367 @foo
1368 @bar
1369 class A:
1370 pass
1371
Christian Heimes02781dc2008-03-21 01:11:52 +00001372This is equivalent to::
1373
1374 class A:
1375 pass
1376
1377 A = foo(bar(A))
1378
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001379.. seealso::
1380
1381 :pep:`3129` - Class Decorators
1382 PEP written by Collin Winter.
Christian Heimes78644762008-03-04 23:39:23 +00001383
1384.. ======================================================================
1385
Christian Heimes679db4a2008-01-18 09:56:22 +00001386.. _pep-3141:
1387
1388PEP 3141: A Type Hierarchy for Numbers
1389=====================================================
1390
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001391Python 3.0 adds several abstract base classes for numeric types
1392inspired by Scheme's numeric tower. These classes were backported to
13932.6 as the :mod:`numbers` module.
Christian Heimes679db4a2008-01-18 09:56:22 +00001394
1395The most general ABC is :class:`Number`. It defines no operations at
1396all, and only exists to allow checking if an object is a number by
1397doing ``isinstance(obj, Number)``.
1398
Christian Heimes679db4a2008-01-18 09:56:22 +00001399:class:`Complex` is a subclass of :class:`Number`. Complex numbers
1400can undergo the basic operations of addition, subtraction,
1401multiplication, division, and exponentiation, and you can retrieve the
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001402real and imaginary parts and obtain a number's conjugate. Python's built-in
Christian Heimes679db4a2008-01-18 09:56:22 +00001403complex type is an implementation of :class:`Complex`.
1404
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001405:class:`Real` further derives from :class:`Complex`, and adds
1406operations that only work on real numbers: :func:`floor`, :func:`trunc`,
1407rounding, taking the remainder mod N, floor division,
1408and comparisons.
Christian Heimes679db4a2008-01-18 09:56:22 +00001409
1410:class:`Rational` numbers derive from :class:`Real`, have
1411:attr:`numerator` and :attr:`denominator` properties, and can be
Christian Heimes3feef612008-02-11 06:19:17 +00001412converted to floats. Python 2.6 adds a simple rational-number class,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001413:class:`Fraction`, in the :mod:`fractions` module. (It's called
1414:class:`Fraction` instead of :class:`Rational` to avoid
Christian Heimes78644762008-03-04 23:39:23 +00001415a name clash with :class:`numbers.Rational`.)
Christian Heimes679db4a2008-01-18 09:56:22 +00001416
1417:class:`Integral` numbers derive from :class:`Rational`, and
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001418can be shifted left and right with ``<<`` and ``>>``,
1419combined using bitwise operations such as ``&`` and ``|``,
Christian Heimes679db4a2008-01-18 09:56:22 +00001420and can be used as array indexes and slice boundaries.
1421
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001422In Python 3.0, the PEP slightly redefines the existing builtins
Christian Heimes78644762008-03-04 23:39:23 +00001423:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001424one, :func:`math.trunc`, that's been backported to Python 2.6.
1425:func:`math.trunc` rounds toward zero, returning the closest
Christian Heimes679db4a2008-01-18 09:56:22 +00001426:class:`Integral` that's between the function's argument and zero.
1427
1428.. seealso::
1429
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001430 :pep:`3141` - A Type Hierarchy for Numbers
1431 PEP written by Jeffrey Yasskin.
1432
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001433 `Scheme's numerical tower <http://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
Christian Heimes679db4a2008-01-18 09:56:22 +00001434
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00001435 `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001436
Christian Heimes679db4a2008-01-18 09:56:22 +00001437
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001438The :mod:`fractions` Module
Christian Heimes679db4a2008-01-18 09:56:22 +00001439--------------------------------------------------
1440
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001441To fill out the hierarchy of numeric types, the :mod:`fractions`
1442module provides a rational-number class. Rational numbers store their
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001443values as a numerator and denominator forming a fraction, and can
1444exactly represent numbers such as ``2/3`` that floating-point numbers
1445can only approximate.
Christian Heimes679db4a2008-01-18 09:56:22 +00001446
Christian Heimes3feef612008-02-11 06:19:17 +00001447The :class:`Fraction` constructor takes two :class:`Integral` values
Christian Heimes679db4a2008-01-18 09:56:22 +00001448that will be the numerator and denominator of the resulting fraction. ::
1449
Christian Heimes3feef612008-02-11 06:19:17 +00001450 >>> from fractions import Fraction
1451 >>> a = Fraction(2, 3)
1452 >>> b = Fraction(2, 5)
Christian Heimes679db4a2008-01-18 09:56:22 +00001453 >>> float(a), float(b)
1454 (0.66666666666666663, 0.40000000000000002)
1455 >>> a+b
Christian Heimes3feef612008-02-11 06:19:17 +00001456 Fraction(16, 15)
Christian Heimes679db4a2008-01-18 09:56:22 +00001457 >>> a/b
Christian Heimes3feef612008-02-11 06:19:17 +00001458 Fraction(5, 3)
Christian Heimes679db4a2008-01-18 09:56:22 +00001459
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001460For converting floating-point numbers to rationals,
1461the float type now has an :meth:`as_integer_ratio()` method that returns
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001462the numerator and denominator for a fraction that evaluates to the same
1463floating-point value::
1464
1465 >>> (2.5) .as_integer_ratio()
1466 (5, 2)
1467 >>> (3.1415) .as_integer_ratio()
1468 (7074029114692207L, 2251799813685248L)
1469 >>> (1./3) .as_integer_ratio()
1470 (6004799503160661L, 18014398509481984L)
1471
1472Note that values that can only be approximated by floating-point
1473numbers, such as 1./3, are not simplified to the number being
1474approximated; the fraction attempts to match the floating-point value
1475**exactly**.
1476
Christian Heimes3feef612008-02-11 06:19:17 +00001477The :mod:`fractions` module is based upon an implementation by Sjoerd
Christian Heimes679db4a2008-01-18 09:56:22 +00001478Mullender that was in Python's :file:`Demo/classes/` directory for a
1479long time. This implementation was significantly updated by Jeffrey
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001480Yasskin.
Christian Heimes679db4a2008-01-18 09:56:22 +00001481
Christian Heimes90540002008-05-08 14:29:10 +00001482
Georg Brandl116aa622007-08-15 14:28:22 +00001483Other Language Changes
1484======================
1485
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001486Some smaller changes made to the core Python language are:
Georg Brandl116aa622007-08-15 14:28:22 +00001487
Andrew M. Kuchling9d2d3272010-02-22 14:57:30 +00001488* Directories and zip archives containing a :file:`__main__.py` file
1489 can now be executed directly by passing their name to the
1490 interpreter. The directory or zip archive is automatically inserted
1491 as the first entry in sys.path. (Suggestion and initial patch by
1492 Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;
1493 :issue:`1739468`.)
1494
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001495* The :func:`hasattr` function was catching and ignoring all errors,
1496 under the assumption that they meant a :meth:`__getattr__` method
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001497 was failing somehow and the return value of :func:`hasattr` would
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001498 therefore be ``False``. This logic shouldn't be applied to
1499 :exc:`KeyboardInterrupt` and :exc:`SystemExit`, however; Python 2.6
1500 will no longer discard such exceptions when :func:`hasattr`
1501 encounters them. (Fixed by Benjamin Peterson; :issue:`2196`.)
1502
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001503* When calling a function using the ``**`` syntax to provide keyword
1504 arguments, you are no longer required to use a Python dictionary;
1505 any mapping will now work::
1506
1507 >>> def f(**kw):
1508 ... print sorted(kw)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001509 ...
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001510 >>> ud=UserDict.UserDict()
1511 >>> ud['a'] = 1
1512 >>> ud['b'] = 'string'
1513 >>> f(**ud)
1514 ['a', 'b']
1515
Martin v. Löwis5680d0c2008-04-10 03:06:53 +00001516 (Contributed by Alexander Belopolsky; :issue:`1686487`.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001517
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001518 It's also become legal to provide keyword arguments after a ``*args`` argument
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001519 to a function call. ::
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001520
1521 >>> def f(*args, **kw):
1522 ... print args, kw
1523 ...
1524 >>> f(1,2,3, *(4,5,6), keyword=13)
1525 (1, 2, 3, 4, 5, 6) {'keyword': 13}
1526
1527 Previously this would have been a syntax error.
1528 (Contributed by Amaury Forgeot d'Arc; :issue:`3473`.)
1529
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001530* A new builtin, ``next(iterator, [default])`` returns the next item
Georg Brandl0c77a822008-06-10 16:37:50 +00001531 from the specified iterator. If the *default* argument is supplied,
1532 it will be returned if *iterator* has been exhausted; otherwise,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001533 the :exc:`StopIteration` exception will be raised. (Backported
1534 in :issue:`2719`.)
Georg Brandl0c77a822008-06-10 16:37:50 +00001535
Georg Brandl3dbca812008-07-23 16:10:53 +00001536* Tuples now have :meth:`index` and :meth:`count` methods matching the
1537 list type's :meth:`index` and :meth:`count` methods::
Christian Heimes5e696852008-04-09 08:37:03 +00001538
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001539 >>> t = (0,1,2,3,4,0,1,2)
Christian Heimes5e696852008-04-09 08:37:03 +00001540 >>> t.index(3)
1541 3
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001542 >>> t.count(0)
1543 2
Christian Heimes5e696852008-04-09 08:37:03 +00001544
Georg Brandl3dbca812008-07-23 16:10:53 +00001545 (Contributed by Raymond Hettinger)
1546
Georg Brandl9afde1c2007-11-01 20:32:30 +00001547* The built-in types now have improved support for extended slicing syntax,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001548 accepting various combinations of ``(start, stop, step)``.
Georg Brandl9afde1c2007-11-01 20:32:30 +00001549 Previously, the support was partial and certain corner cases wouldn't work.
1550 (Implemented by Thomas Wouters.)
1551
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001552 .. Revision 57619
Georg Brandl9afde1c2007-11-01 20:32:30 +00001553
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001554* Properties now have three attributes, :attr:`getter`, :attr:`setter`
1555 and :attr:`deleter`, that are decorators providing useful shortcuts
1556 for adding a getter, setter or deleter function to an existing
1557 property. You would use them like this::
Christian Heimes90aa7642007-12-19 02:45:37 +00001558
1559 class C(object):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001560 @property
1561 def x(self):
1562 return self._x
Christian Heimes90aa7642007-12-19 02:45:37 +00001563
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001564 @x.setter
1565 def x(self, value):
1566 self._x = value
Christian Heimes90aa7642007-12-19 02:45:37 +00001567
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001568 @x.deleter
1569 def x(self):
1570 del self._x
Christian Heimes90aa7642007-12-19 02:45:37 +00001571
Christian Heimes679db4a2008-01-18 09:56:22 +00001572 class D(C):
1573 @C.x.getter
1574 def x(self):
1575 return self._x * 2
1576
1577 @x.setter
1578 def x(self, value):
1579 self._x = value / 2
1580
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001581* Several methods of the built-in set types now accept multiple iterables:
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001582 :meth:`intersection`,
1583 :meth:`intersection_update`,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001584 :meth:`union`, :meth:`update`,
1585 :meth:`difference` and :meth:`difference_update`.
Christian Heimes90aa7642007-12-19 02:45:37 +00001586
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001587 ::
Georg Brandl9afde1c2007-11-01 20:32:30 +00001588
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001589 >>> s=set('1234567890')
1590 >>> s.intersection('abc123', 'cdf246') # Intersection between all inputs
1591 set(['2'])
1592 >>> s.difference('246', '789')
1593 set(['1', '0', '3', '5'])
1594
1595 (Contributed by Raymond Hettinger.)
1596
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001597* Many floating-point features were added. The :func:`float` function
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001598 will now turn the string ``nan`` into an
1599 IEEE 754 Not A Number value, and ``+inf`` and ``-inf`` into
1600 positive or negative infinity. This works on any platform with
Christian Heimes33fe8092008-04-13 13:53:33 +00001601 IEEE 754 semantics. (Contributed by Christian Heimes; :issue:`1635`.)
Christian Heimesa34706f2008-01-04 03:06:10 +00001602
Christian Heimes3f419af2008-01-04 03:08:33 +00001603 Other functions in the :mod:`math` module, :func:`isinf` and
1604 :func:`isnan`, return true if their floating-point argument is
Christian Heimes33fe8092008-04-13 13:53:33 +00001605 infinite or Not A Number. (:issue:`1640`)
Christian Heimesc3f30c42008-02-22 16:37:40 +00001606
Georg Brandl734e2682008-08-12 08:18:18 +00001607 Conversion functions were added to convert floating-point numbers
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001608 into hexadecimal strings (:issue:`3008`). These functions
Georg Brandl734e2682008-08-12 08:18:18 +00001609 convert floats to and from a string representation without
1610 introducing rounding errors from the conversion between decimal and
1611 binary. Floats have a :meth:`hex` method that returns a string
1612 representation, and the ``float.fromhex()`` method converts a string
1613 back into a number::
1614
1615 >>> a = 3.75
1616 >>> a.hex()
1617 '0x1.e000000000000p+1'
1618 >>> float.fromhex('0x1.e000000000000p+1')
1619 3.75
1620 >>> b=1./3
1621 >>> b.hex()
1622 '0x1.5555555555555p-2'
Mark Dickinson65fe25e2008-07-16 11:30:51 +00001623
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001624* A numerical nicety: when creating a complex number from two floats
1625 on systems that support signed zeros (-0 and +0), the
1626 :func:`complex` constructor will now preserve the sign
1627 of the zero. (Fixed by Mark T. Dickinson; :issue:`1507`.)
Christian Heimes3f419af2008-01-04 03:08:33 +00001628
Benjamin Petersondcc1e112008-09-03 22:22:18 +00001629* Classes that inherit a :meth:`__hash__` method from a parent class
1630 can set ``__hash__ = None`` to indicate that the class isn't
1631 hashable. This will make ``hash(obj)`` raise a :exc:`TypeError`
1632 and the class will not be indicated as implementing the
1633 :class:`Hashable` ABC.
1634
1635 You should do this when you've defined a :meth:`__cmp__` or
1636 :meth:`__eq__` method that compares objects by their value rather
1637 than by identity. All objects have a default hash method that uses
1638 ``id(obj)`` as the hash value. There's no tidy way to remove the
1639 :meth:`__hash__` method inherited from a parent class, so
1640 assigning ``None`` was implemented as an override. At the
1641 C level, extensions can set ``tp_hash`` to
1642 :cfunc:`PyObject_HashNotImplemented`.
1643 (Fixed by Nick Coghlan and Amaury Forgeot d'Arc; :issue:`2235`.)
1644
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001645* The :exc:`GeneratorExit` exception now subclasses
1646 :exc:`BaseException` instead of :exc:`Exception`. This means
Christian Heimes90aa7642007-12-19 02:45:37 +00001647 that an exception handler that does ``except Exception:``
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001648 will not inadvertently catch :exc:`GeneratorExit`.
Christian Heimes33fe8092008-04-13 13:53:33 +00001649 (Contributed by Chad Austin; :issue:`1537`.)
Christian Heimes90aa7642007-12-19 02:45:37 +00001650
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001651* Generator objects now have a :attr:`gi_code` attribute that refers to
1652 the original code object backing the generator.
Christian Heimes33fe8092008-04-13 13:53:33 +00001653 (Contributed by Collin Winter; :issue:`1473257`.)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001654
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655* The :func:`compile` built-in function now accepts keyword arguments
Christian Heimes33fe8092008-04-13 13:53:33 +00001656 as well as positional parameters. (Contributed by Thomas Wouters;
1657 :issue:`1444529`.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001659* The :func:`complex` constructor now accepts strings containing
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001660 parenthesized complex numbers, meaning that ``complex(repr(cplx))``
Thomas Wouters89d996e2007-09-08 17:39:28 +00001661 will now round-trip values. For example, ``complex('(3+4j)')``
Christian Heimes33fe8092008-04-13 13:53:33 +00001662 now returns the value (3+4j). (:issue:`1491866`)
Thomas Wouters89d996e2007-09-08 17:39:28 +00001663
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001664* The string :meth:`translate` method now accepts ``None`` as the
1665 translation table parameter, which is treated as the identity
Thomas Wouters89d996e2007-09-08 17:39:28 +00001666 transformation. This makes it easier to carry out operations
Georg Brandl3dbca812008-07-23 16:10:53 +00001667 that only delete characters. (Contributed by Bengt Richter and
1668 implemented by Raymond Hettinger; :issue:`1193128`.)
Thomas Wouters89d996e2007-09-08 17:39:28 +00001669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670* The built-in :func:`dir` function now checks for a :meth:`__dir__`
1671 method on the objects it receives. This method must return a list
1672 of strings containing the names of valid attributes for the object,
1673 and lets the object control the value that :func:`dir` produces.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001674 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Christian Heimescbf3b5c2007-12-03 21:02:03 +00001675 methods can use this to advertise pseudo-attributes they will honor.
Christian Heimes33fe8092008-04-13 13:53:33 +00001676 (:issue:`1591665`)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677
Christian Heimes02781dc2008-03-21 01:11:52 +00001678* Instance method objects have new attributes for the object and function
1679 comprising the method; the new synonym for :attr:`im_self` is
1680 :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001681 The old names are still supported in Python 2.6, but are gone in 3.0.
Christian Heimes02781dc2008-03-21 01:11:52 +00001682
Benjamin Petersond23f8222009-04-05 19:13:16 +00001683* An obscure change: when you use the :func:`locals` function inside a
Georg Brandl116aa622007-08-15 14:28:22 +00001684 :keyword:`class` statement, the resulting dictionary no longer returns free
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001685 variables. (Free variables, in this case, are variables referenced in the
Georg Brandl116aa622007-08-15 14:28:22 +00001686 :keyword:`class` statement that aren't attributes of the class.)
1687
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001688.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00001689
1690
1691Optimizations
1692-------------
1693
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001694* The :mod:`warnings` module has been rewritten in C. This makes
1695 it possible to invoke warnings from the parser, and may also
1696 make the interpreter's startup faster.
1697 (Contributed by Neal Norwitz and Brett Cannon; :issue:`1631171`.)
1698
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001699* Type objects now have a cache of methods that can reduce
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001700 the work required to find the correct method implementation
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001701 for a particular class; once cached, the interpreter doesn't need to
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001702 traverse base classes to figure out the right method to call.
1703 The cache is cleared if a base class or the class itself is modified,
1704 so the cache should remain correct even in the face of Python's dynamic
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001705 nature.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001706 (Original optimization implemented by Armin Rigo, updated for
1707 Python 2.6 by Kevin Jacobs; :issue:`1700288`.)
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001708
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001709 By default, this change is only applied to types that are included with
1710 the Python core. Extension modules may not necessarily be compatible with
1711 this cache,
1712 so they must explicitly add :cmacro:`Py_TPFLAGS_HAVE_VERSION_TAG`
1713 to the module's ``tp_flags`` field to enable the method cache.
1714 (To be compatible with the method cache, the extension module's code
1715 must not directly access and modify the ``tp_dict`` member of
1716 any of the types it implements. Most modules don't do this,
1717 but it's impossible for the Python interpreter to determine that.
1718 See :issue:`1878` for some discussion.)
1719
1720* Function calls that use keyword arguments are significantly faster
1721 by doing a quick pointer comparison, usually saving the time of a
1722 full string comparison. (Contributed by Raymond Hettinger, after an
1723 initial implementation by Antoine Pitrou; :issue:`1819`.)
Georg Brandl734e2682008-08-12 08:18:18 +00001724
Christian Heimes3f419af2008-01-04 03:08:33 +00001725* All of the functions in the :mod:`struct` module have been rewritten in
1726 C, thanks to work at the Need For Speed sprint.
1727 (Contributed by Raymond Hettinger.)
1728
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001729* Some of the standard built-in types now set a bit in their type
1730 objects. This speeds up checking whether an object is a subclass of
1731 one of these types. (Contributed by Neal Norwitz.)
Georg Brandl116aa622007-08-15 14:28:22 +00001732
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001733* Unicode strings now use faster code for detecting
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001734 whitespace and line breaks; this speeds up the :meth:`split` method
Christian Heimes78644762008-03-04 23:39:23 +00001735 by about 25% and :meth:`splitlines` by 35%.
Christian Heimes02781dc2008-03-21 01:11:52 +00001736 (Contributed by Antoine Pitrou.) Memory usage is reduced
1737 by using pymalloc for the Unicode string's data.
1738
1739* The ``with`` statement now stores the :meth:`__exit__` method on the stack,
Christian Heimesf6cd9672008-03-26 13:45:42 +00001740 producing a small speedup. (Implemented by Jeffrey Yasskin.)
Christian Heimes78644762008-03-04 23:39:23 +00001741
1742* To reduce memory usage, the garbage collector will now clear internal
1743 free lists when garbage-collecting the highest generation of objects.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001744 This may return memory to the operating system sooner.
Christian Heimes78644762008-03-04 23:39:23 +00001745
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001746.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00001747
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001748.. _new-26-interpreter:
Christian Heimes33fe8092008-04-13 13:53:33 +00001749
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001750Interpreter Changes
Christian Heimes33fe8092008-04-13 13:53:33 +00001751-------------------------------
1752
1753Two command-line options have been reserved for use by other Python
1754implementations. The :option:`-J` switch has been reserved for use by
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001755Jython for Jython-specific options, such as switches that are passed to
Christian Heimes33fe8092008-04-13 13:53:33 +00001756the underlying JVM. :option:`-X` has been reserved for options
1757specific to a particular implementation of Python such as CPython,
1758Jython, or IronPython. If either option is used with Python 2.6, the
1759interpreter will report that the option isn't currently used.
1760
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001761Python can now be prevented from writing :file:`.pyc` or :file:`.pyo`
1762files by supplying the :option:`-B` switch to the Python interpreter,
1763or by setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment
1764variable before running the interpreter. This setting is available to
1765Python programs as the ``sys.dont_write_bytecode`` variable, and
1766Python code can change the value to modify the interpreter's
1767behaviour. (Contributed by Neal Norwitz and Georg Brandl.)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001768
1769The encoding used for standard input, output, and standard error can
1770be specified by setting the :envvar:`PYTHONIOENCODING` environment
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001771variable before running the interpreter. The value should be a string
1772in the form ``<encoding>`` or ``<encoding>:<errorhandler>``.
1773The *encoding* part specifies the encoding's name, e.g. ``utf-8`` or
1774``latin-1``; the optional *errorhandler* part specifies
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001775what to do with characters that can't be handled by the encoding,
1776and should be one of "error", "ignore", or "replace". (Contributed
1777by Martin von Loewis.)
1778
Christian Heimes33fe8092008-04-13 13:53:33 +00001779.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00001780
Georg Brandl8bd05462009-11-18 18:53:54 +00001781New and Improved Modules
1782========================
Georg Brandl116aa622007-08-15 14:28:22 +00001783
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001784As in every release, Python's standard library received a number of
1785enhancements and bug fixes. Here's a partial list of the most notable
1786changes, sorted alphabetically by module name. Consult the
1787:file:`Misc/NEWS` file in the source tree for a more complete list of
1788changes, or look through the Subversion logs for all the details.
Georg Brandl116aa622007-08-15 14:28:22 +00001789
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001790* The :mod:`asyncore` and :mod:`asynchat` modules are
1791 being actively maintained again, and a number of patches and bugfixes
1792 were applied. (Maintained by Josiah Carlson; see :issue:`1736190` for
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001793 one patch.)
1794
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00001795* The :mod:`bsddb` module also has a new maintainer, Jesús Cea Avion, and the package
Benjamin Peterson5478b472008-09-17 22:25:09 +00001796 is now available as a standalone package. The web page for the package is
1797 `www.jcea.es/programacion/pybsddb.htm
1798 <http://www.jcea.es/programacion/pybsddb.htm>`__.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001799 The plan is to remove the package from the standard library
1800 in Python 3.0, because its pace of releases is much more frequent than
1801 Python's.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001802
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001803 The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
Georg Brandl9afde1c2007-11-01 20:32:30 +00001804 available, instead of restricting itself to protocol 1.
Georg Brandl495f7b52009-10-27 15:28:25 +00001805 (Contributed by W. Barnes.)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001806
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001807* The :mod:`cgi` module will now read variables from the query string
1808 of an HTTP POST request. This makes it possible to use form actions
1809 with URLs that include query strings such as
1810 "/cgi-bin/add.py?category=1". (Contributed by Alexandre Fiori and
1811 Nubis; :issue:`1817`.)
Georg Brandl86b2fb92008-07-16 03:43:04 +00001812
Georg Brandl48310cd2009-01-03 21:18:54 +00001813 The :func:`parse_qs` and :func:`parse_qsl` functions have been
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001814 relocated from the :mod:`cgi` module to the :mod:`urlparse` module.
Georg Brandl48310cd2009-01-03 21:18:54 +00001815 The versions still available in the :mod:`cgi` module will
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001816 trigger :exc:`PendingDeprecationWarning` messages in 2.6
1817 (:issue:`600362`).
1818
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001819* The :mod:`cmath` module underwent extensive revision,
1820 contributed by Mark Dickinson and Christian Heimes.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001821 Five new functions were added:
Christian Heimesa342c012008-04-20 21:01:16 +00001822
1823 * :func:`polar` converts a complex number to polar form, returning
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001824 the modulus and argument of the complex number.
Christian Heimesa342c012008-04-20 21:01:16 +00001825
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001826 * :func:`rect` does the opposite, turning a modulus, argument pair
Christian Heimesa342c012008-04-20 21:01:16 +00001827 back into the corresponding complex number.
1828
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001829 * :func:`phase` returns the argument (also called the angle) of a complex
1830 number.
Christian Heimesa342c012008-04-20 21:01:16 +00001831
1832 * :func:`isnan` returns True if either
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001833 the real or imaginary part of its argument is a NaN.
Christian Heimesa342c012008-04-20 21:01:16 +00001834
1835 * :func:`isinf` returns True if either the real or imaginary part of
1836 its argument is infinite.
1837
1838 The revisions also improved the numerical soundness of the
1839 :mod:`cmath` module. For all functions, the real and imaginary
1840 parts of the results are accurate to within a few units of least
1841 precision (ulps) whenever possible. See :issue:`1381` for the
1842 details. The branch cuts for :func:`asinh`, :func:`atanh`: and
1843 :func:`atan` have also been corrected.
1844
1845 The tests for the module have been greatly expanded; nearly 2000 new
1846 test cases exercise the algebraic functions.
1847
1848 On IEEE 754 platforms, the :mod:`cmath` module now handles IEEE 754
1849 special values and floating-point exceptions in a manner consistent
1850 with Annex 'G' of the C99 standard.
1851
Georg Brandl9afde1c2007-11-01 20:32:30 +00001852* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl116aa622007-08-15 14:28:22 +00001853 fieldnames)` is a factory function that creates subclasses of the standard tuple
1854 whose fields are accessible by name as well as index. For example::
1855
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001856 >>> var_type = collections.namedtuple('variable',
Georg Brandl9afde1c2007-11-01 20:32:30 +00001857 ... 'id name type size')
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001858 >>> # Names are separated by spaces or commas.
1859 >>> # 'id, name, type, size' would also work.
Christian Heimes0449f632007-12-15 01:27:15 +00001860 >>> var_type._fields
Georg Brandl9afde1c2007-11-01 20:32:30 +00001861 ('id', 'name', 'type', 'size')
Georg Brandl116aa622007-08-15 14:28:22 +00001862
Georg Brandl9afde1c2007-11-01 20:32:30 +00001863 >>> var = var_type(1, 'frequency', 'int', 4)
Georg Brandla1c6a1c2009-01-03 21:26:05 +00001864 >>> print var[0], var.id # Equivalent
Georg Brandl9afde1c2007-11-01 20:32:30 +00001865 1 1
Georg Brandla1c6a1c2009-01-03 21:26:05 +00001866 >>> print var[2], var.type # Equivalent
Georg Brandl9afde1c2007-11-01 20:32:30 +00001867 int int
Christian Heimes0449f632007-12-15 01:27:15 +00001868 >>> var._asdict()
Georg Brandl9afde1c2007-11-01 20:32:30 +00001869 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Christian Heimesa156e092008-02-16 07:38:31 +00001870 >>> v2 = var._replace(name='amplitude')
Georg Brandl9afde1c2007-11-01 20:32:30 +00001871 >>> v2
1872 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl116aa622007-08-15 14:28:22 +00001873
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001874 Several places in the standard library that returned tuples have
1875 been modified to return :class:`namedtuple` instances. For example,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001876 the :meth:`Decimal.as_tuple` method now returns a named tuple with
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001877 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1878
Georg Brandl116aa622007-08-15 14:28:22 +00001879 (Contributed by Raymond Hettinger.)
1880
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001881* Another change to the :mod:`collections` module is that the
Christian Heimes895627f2007-12-08 17:28:33 +00001882 :class:`deque` type now supports an optional *maxlen* parameter;
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001883 if supplied, the deque's size will be restricted to no more
Christian Heimes895627f2007-12-08 17:28:33 +00001884 than *maxlen* items. Adding more items to a full deque causes
Georg Brandl9afde1c2007-11-01 20:32:30 +00001885 old items to be discarded.
1886
1887 ::
1888
1889 >>> from collections import deque
1890 >>> dq=deque(maxlen=3)
1891 >>> dq
1892 deque([], maxlen=3)
1893 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
1894 >>> dq
1895 deque([1, 2, 3], maxlen=3)
1896 >>> dq.append(4)
1897 >>> dq
1898 deque([2, 3, 4], maxlen=3)
1899
1900 (Contributed by Raymond Hettinger.)
1901
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001902* The :mod:`Cookie` module's :class:`Morsel` objects now support an
1903 :attr:`httponly` attribute. In some browsers. cookies with this attribute
1904 set cannot be accessed or manipulated by JavaScript code.
1905 (Contributed by Arvin Schnell; :issue:`1638033`.)
1906
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001907* A new window method in the :mod:`curses` module,
1908 :meth:`chgat`, changes the display attributes for a certain number of
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001909 characters on a single line. (Contributed by Fabian Kreutz.)
Georg Brandl48310cd2009-01-03 21:18:54 +00001910
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001911 ::
Georg Brandl116aa622007-08-15 14:28:22 +00001912
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001913 # Boldface text starting at y=0,x=21
Georg Brandl116aa622007-08-15 14:28:22 +00001914 # and affecting the rest of the line.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001915 stdscr.chgat(0, 21, curses.A_BOLD)
Georg Brandl116aa622007-08-15 14:28:22 +00001916
Christian Heimesfdab48e2008-01-20 09:06:41 +00001917 The :class:`Textbox` class in the :mod:`curses.textpad` module
1918 now supports editing in insert mode as well as overwrite mode.
1919 Insert mode is enabled by supplying a true value for the *insert_mode*
1920 parameter when creating the :class:`Textbox` instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001921
Christian Heimes02781dc2008-03-21 01:11:52 +00001922* The :mod:`datetime` module's :meth:`strftime` methods now support a
1923 ``%f`` format code that expands to the number of microseconds in the
1924 object, zero-padded on
Christian Heimes33fe8092008-04-13 13:53:33 +00001925 the left to six places. (Contributed by Skip Montanaro; :issue:`1158`.)
Christian Heimes02781dc2008-03-21 01:11:52 +00001926
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001927* The :mod:`decimal` module was updated to version 1.66 of
Georg Brandl9afde1c2007-11-01 20:32:30 +00001928 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
1929 include some methods for some basic mathematical functions such as
1930 :meth:`exp` and :meth:`log10`::
1931
1932 >>> Decimal(1).exp()
1933 Decimal("2.718281828459045235360287471")
1934 >>> Decimal("2.7182818").ln()
1935 Decimal("0.9999999895305022877376682436")
1936 >>> Decimal(1000).log10()
1937 Decimal("3")
1938
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001939 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001940 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001941
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001942 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
1943 support added by Raymond Hettinger.)
1944
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001945* The :mod:`difflib` module's :class:`SequenceMatcher` class
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001946 now returns named tuples representing matches,
1947 with :attr:`a`, :attr:`b`, and :attr:`size` attributes.
Guido van Rossum7736b5b2008-01-15 21:44:53 +00001948 (Contributed by Raymond Hettinger.)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001949
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001950* An optional ``timeout`` parameter, specifying a timeout measured in
1951 seconds, was added to the :class:`ftplib.FTP` class constructor as
1952 well as the :meth:`connect` method. (Added by Facundo Batista.)
1953 Also, the :class:`FTP` class's :meth:`storbinary` and
1954 :meth:`storlines` now take an optional *callback* parameter that
1955 will be called with each block of data after the data has been sent.
Christian Heimes33fe8092008-04-13 13:53:33 +00001956 (Contributed by Phil Schwartz; :issue:`1221598`.)
Thomas Wouters89d996e2007-09-08 17:39:28 +00001957
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001958* The :func:`reduce` built-in function is also available in the
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001959 :mod:`functools` module. In Python 3.0, the builtin has been
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001960 dropped and :func:`reduce` is only available from :mod:`functools`;
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001961 currently there are no plans to drop the builtin in the 2.x series.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001962 (Patched by Christian Heimes; :issue:`1739906`.)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001963
Georg Brandl0c77a822008-06-10 16:37:50 +00001964* When possible, the :mod:`getpass` module will now use
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001965 :file:`/dev/tty` to print a prompt message and read the password,
1966 falling back to standard error and standard input. If the
1967 password may be echoed to the terminal, a warning is printed before
1968 the prompt is displayed. (Contributed by Gregory P. Smith.)
Georg Brandl0c77a822008-06-10 16:37:50 +00001969
1970* The :func:`glob.glob` function can now return Unicode filenames if
Christian Heimes33fe8092008-04-13 13:53:33 +00001971 a Unicode path was used and Unicode filenames are matched within the
1972 directory. (:issue:`1001604`)
Georg Brandl116aa622007-08-15 14:28:22 +00001973
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001974* A new function in the :mod:`heapq` module, ``merge(iter1, iter2, ...)``,
1975 takes any number of iterables returning data in sorted
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001976 order, and returns a new generator that returns the contents of all
Christian Heimes02781dc2008-03-21 01:11:52 +00001977 the iterators, also in sorted order. For example::
Georg Brandl116aa622007-08-15 14:28:22 +00001978
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001979 >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
1980 [1, 2, 3, 5, 8, 9, 16]
Georg Brandl116aa622007-08-15 14:28:22 +00001981
Christian Heimes02781dc2008-03-21 01:11:52 +00001982 Another new function, ``heappushpop(heap, item)``,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001983 pushes *item* onto *heap*, then pops off and returns the smallest item.
Christian Heimes02781dc2008-03-21 01:11:52 +00001984 This is more efficient than making a call to :func:`heappush` and then
1985 :func:`heappop`.
1986
Georg Brandl0c77a822008-06-10 16:37:50 +00001987 :mod:`heapq` is now implemented to only use less-than comparison,
1988 instead of the less-than-or-equal comparison it previously used.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001989 This makes :mod:`heapq`'s usage of a type match the
Georg Brandl0c77a822008-06-10 16:37:50 +00001990 :meth:`list.sort` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001991 (Contributed by Raymond Hettinger.)
1992
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001993* An optional ``timeout`` parameter, specifying a timeout measured in
1994 seconds, was added to the :class:`httplib.HTTPConnection` and
1995 :class:`HTTPSConnection` class constructors. (Added by Facundo
1996 Batista.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001997
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00001998* Most of the :mod:`inspect` module's functions, such as
1999 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002000 In addition to behaving like tuples, the elements of the return value
2001 can also be accessed as attributes.
2002 (Contributed by Raymond Hettinger.)
2003
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002004 Some new functions in the module include
2005 :func:`isgenerator`, :func:`isgeneratorfunction`,
Christian Heimes78644762008-03-04 23:39:23 +00002006 and :func:`isabstract`.
2007
2008* The :mod:`itertools` module gained several new functions.
2009
2010 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
2011 each of the elements; if some of the iterables are shorter than
2012 others, the missing values are set to *fillvalue*. For example::
Georg Brandl116aa622007-08-15 14:28:22 +00002013
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002014 >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
2015 ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))
Georg Brandl116aa622007-08-15 14:28:22 +00002016
Christian Heimes78644762008-03-04 23:39:23 +00002017 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
2018 of the supplied iterables, a set of tuples containing
2019 every possible combination of the elements returned from each iterable. ::
2020
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002021 >>> list(itertools.product([1,2,3], [4,5,6]))
2022 [(1, 4), (1, 5), (1, 6),
Georg Brandla1c6a1c2009-01-03 21:26:05 +00002023 (2, 4), (2, 5), (2, 6),
2024 (3, 4), (3, 5), (3, 6)]
Christian Heimes78644762008-03-04 23:39:23 +00002025
2026 The optional *repeat* keyword argument is used for taking the
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002027 product of an iterable or a set of iterables with themselves,
Christian Heimes78644762008-03-04 23:39:23 +00002028 repeated *N* times. With a single iterable argument, *N*-tuples
2029 are returned::
2030
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002031 >>> list(itertools.product([1,2], repeat=3))
2032 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
2033 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
Christian Heimes78644762008-03-04 23:39:23 +00002034
2035 With two iterables, *2N*-tuples are returned. ::
2036
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002037 >>> list(itertools.product([1,2], [3,4], repeat=2))
2038 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
2039 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
2040 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
2041 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
Christian Heimes78644762008-03-04 23:39:23 +00002042
Christian Heimes02781dc2008-03-21 01:11:52 +00002043 ``combinations(iterable, r)`` returns sub-sequences of length *r* from
Christian Heimes78644762008-03-04 23:39:23 +00002044 the elements of *iterable*. ::
2045
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002046 >>> list(itertools.combinations('123', 2))
2047 [('1', '2'), ('1', '3'), ('2', '3')]
2048 >>> list(itertools.combinations('123', 3))
2049 [('1', '2', '3')]
2050 >>> list(itertools.combinations('1234', 3))
2051 [('1', '2', '3'), ('1', '2', '4'),
2052 ('1', '3', '4'), ('2', '3', '4')]
Christian Heimes78644762008-03-04 23:39:23 +00002053
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002054 ``permutations(iter[, r])`` returns all the permutations of length *r* of
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002055 the iterable's elements. If *r* is not specified, it will default to the
Christian Heimes5d8da202008-05-06 13:58:24 +00002056 number of elements produced by the iterable. ::
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002057
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002058 >>> list(itertools.permutations([1,2,3,4], 2))
2059 [(1, 2), (1, 3), (1, 4),
2060 (2, 1), (2, 3), (2, 4),
2061 (3, 1), (3, 2), (3, 4),
2062 (4, 1), (4, 2), (4, 3)]
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002063
Christian Heimes5e696852008-04-09 08:37:03 +00002064 ``itertools.chain(*iterables)`` is an existing function in
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002065 :mod:`itertools` that gained a new constructor in Python 2.6.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002066 ``itertools.chain.from_iterable(iterable)`` takes a single
Christian Heimes78644762008-03-04 23:39:23 +00002067 iterable that should return other iterables. :func:`chain` will
2068 then return all the elements of the first iterable, then
2069 all the elements of the second, and so on. ::
2070
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002071 >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
2072 [1, 2, 3, 4, 5, 6]
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002073
Christian Heimes78644762008-03-04 23:39:23 +00002074 (All contributed by Raymond Hettinger.)
Georg Brandl116aa622007-08-15 14:28:22 +00002075
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002076* The :mod:`logging` module's :class:`FileHandler` class
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002077 and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002078 and :class:`TimedRotatingFileHandler` now
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002079 have an optional *delay* parameter to their constructors. If *delay*
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002080 is true, opening of the log file is deferred until the first
2081 :meth:`emit` call is made. (Contributed by Vinay Sajip.)
2082
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002083 :class:`TimedRotatingFileHandler` also has a *utc* constructor
2084 parameter. If the argument is true, UTC time will be used
Georg Brandl0c77a822008-06-10 16:37:50 +00002085 in determining when midnight occurs and in generating filenames;
2086 otherwise local time will be used.
2087
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002088* Several new functions were added to the :mod:`math` module:
Georg Brandl116aa622007-08-15 14:28:22 +00002089
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002090 * :func:`~math.isinf` and :func:`~math.isnan` determine whether a given float
2091 is a (positive or negative) infinity or a NaN (Not a Number), respectively.
2092
2093 * :func:`~math.copysign` copies the sign bit of an IEEE 754 number,
2094 returning the absolute value of *x* combined with the sign bit of
2095 *y*. For example, ``math.copysign(1, -0.0)`` returns -1.0.
2096 (Contributed by Christian Heimes.)
2097
2098 * :func:`~math.factorial` computes the factorial of a number.
2099 (Contributed by Raymond Hettinger; :issue:`2138`.)
2100
2101 * :func:`~math.fsum` adds up the stream of numbers from an iterable,
2102 and is careful to avoid loss of precision through using partial sums.
2103 (Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;
2104 :issue:`2819`.)
2105
2106 * :func:`~math.acosh`, :func:`~math.asinh`
2107 and :func:`~math.atanh` compute the inverse hyperbolic functions.
2108
2109 * :func:`~math.log1p` returns the natural logarithm of *1+x*
2110 (base *e*).
2111
2112 * :func:`trunc` rounds a number toward zero, returning the closest
2113 :class:`Integral` that's between the function's argument and zero.
2114 Added as part of the backport of
2115 `PEP 3141's type hierarchy for numbers <#pep-3141>`__.
2116
2117* The :mod:`math` module has been improved to give more consistent
2118 behaviour across platforms, especially with respect to handling of
2119 floating-point exceptions and IEEE 754 special values.
2120
2121 Whenever possible, the module follows the recommendations of the C99
2122 standard about 754's special values. For example, ``sqrt(-1.)``
2123 should now give a :exc:`ValueError` across almost all platforms,
2124 while ``sqrt(float('NaN'))`` should return a NaN on all IEEE 754
2125 platforms. Where Annex 'F' of the C99 standard recommends signaling
2126 'divide-by-zero' or 'invalid', Python will raise :exc:`ValueError`.
2127 Where Annex 'F' of the C99 standard recommends signaling 'overflow',
2128 Python will raise :exc:`OverflowError`. (See :issue:`711019` and
2129 :issue:`1640`.)
2130
2131 (Contributed by Christian Heimes and Mark Dickinson.)
2132
2133* :class:`mmap` objects now have a :meth:`rfind` method that searches for a
2134 substring beginning at the end of the string and searching
2135 backwards. The :meth:`find` method also gained an *end* parameter
2136 giving an index at which to stop searching.
Georg Brandlfceab5a2008-01-19 20:08:23 +00002137 (Contributed by John Lenton.)
2138
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002139* The :mod:`operator` module gained a
2140 :func:`methodcaller` function that takes a name and an optional
2141 set of arguments, returning a callable that will call
Christian Heimes78644762008-03-04 23:39:23 +00002142 the named function on any arguments passed to it. For example::
2143
2144 >>> # Equivalent to lambda s: s.replace('old', 'new')
2145 >>> replacer = operator.methodcaller('replace', 'old', 'new')
2146 >>> replacer('old wine in old bottles')
2147 'new wine in new bottles'
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002148
Christian Heimes78644762008-03-04 23:39:23 +00002149 (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
2150
2151 The :func:`attrgetter` function now accepts dotted names and performs
2152 the corresponding attribute lookups::
2153
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002154 >>> inst_name = operator.attrgetter(
2155 ... '__class__.__name__')
Christian Heimes78644762008-03-04 23:39:23 +00002156 >>> inst_name('')
2157 'str'
2158 >>> inst_name(help)
2159 '_Helper'
2160
2161 (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
2162
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002163* The :mod:`os` module now wraps several new system calls.
2164 ``fchmod(fd, mode)`` and ``fchown(fd, uid, gid)`` change the mode
2165 and ownership of an opened file, and ``lchmod(path, mode)`` changes
2166 the mode of a symlink. (Contributed by Georg Brandl and Christian
2167 Heimes.)
Christian Heimes90aa7642007-12-19 02:45:37 +00002168
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002169 :func:`chflags` and :func:`lchflags` are wrappers for the
2170 corresponding system calls (where they're available), changing the
2171 flags set on a file. Constants for the flag values are defined in
2172 the :mod:`stat` module; some possible values include
2173 :const:`UF_IMMUTABLE` to signal the file may not be changed and
2174 :const:`UF_APPEND` to indicate that data can only be appended to the
2175 file. (Contributed by M. Levinson.)
2176
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002177 ``os.closerange(low, high)`` efficiently closes all file descriptors
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002178 from *low* to *high*, ignoring any errors and not including *high* itself.
2179 This function is now used by the :mod:`subprocess` module to make starting
2180 processes faster. (Contributed by Georg Brandl; :issue:`1663329`.)
2181
2182* The ``os.environ`` object's :meth:`clear` method will now unset the
2183 environment variables using :func:`os.unsetenv` in addition to clearing
2184 the object's keys. (Contributed by Martin Horcicka; :issue:`1181`.)
Christian Heimes90aa7642007-12-19 02:45:37 +00002185
Georg Brandl9afde1c2007-11-01 20:32:30 +00002186* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002187 set to True, it will follow symlinks pointing to directories and
2188 visit the directory's contents. For backward compatibility, the
2189 parameter's default value is false. Note that the function can fall
2190 into an infinite recursion if there's a symlink that points to a
Christian Heimes33fe8092008-04-13 13:53:33 +00002191 parent directory. (:issue:`1273829`)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002192
Thomas Wouters89d996e2007-09-08 17:39:28 +00002193* In the :mod:`os.path` module, the :func:`splitext` function
2194 has been changed to not split on leading period characters.
2195 This produces better results when operating on Unix's dot-files.
2196 For example, ``os.path.splitext('.ipython')``
2197 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
Ezio Melotti19192dd2010-04-05 13:25:51 +00002198 (:issue:`1115886`)
Thomas Wouters89d996e2007-09-08 17:39:28 +00002199
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002200 A new function, ``os.path.relpath(path, start='.')``, returns a relative path
Thomas Wouters89d996e2007-09-08 17:39:28 +00002201 from the ``start`` path, if it's supplied, or from the current
2202 working directory to the destination ``path``. (Contributed by
Christian Heimes33fe8092008-04-13 13:53:33 +00002203 Richard Barran; :issue:`1339796`.)
Thomas Wouters89d996e2007-09-08 17:39:28 +00002204
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002205 On Windows, :func:`os.path.expandvars` will now expand environment variables
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002206 given in the form "%var%", and "~user" will be expanded into the
Christian Heimes33fe8092008-04-13 13:53:33 +00002207 user's home directory path. (Contributed by Josiah Carlson;
2208 :issue:`957650`.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002209
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002210* The Python debugger provided by the :mod:`pdb` module
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002211 gained a new command: "run" restarts the Python program being debugged
Georg Brandl9afde1c2007-11-01 20:32:30 +00002212 and can optionally take new command-line arguments for the program.
Christian Heimes33fe8092008-04-13 13:53:33 +00002213 (Contributed by Rocky Bernstein; :issue:`1393667`.)
Georg Brandl9afde1c2007-11-01 20:32:30 +00002214
Georg Brandl8bd05462009-11-18 18:53:54 +00002215* The :func:`pdb.post_mortem` function, used to begin debugging a
Christian Heimes5e696852008-04-09 08:37:03 +00002216 traceback, will now use the traceback returned by :func:`sys.exc_info`
Christian Heimes33fe8092008-04-13 13:53:33 +00002217 if no traceback is supplied. (Contributed by Facundo Batista;
2218 :issue:`1106316`.)
Christian Heimes5e696852008-04-09 08:37:03 +00002219
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002220* The :mod:`pickletools` module now has an :func:`optimize` function
2221 that takes a string containing a pickle and removes some unused
Christian Heimes78644762008-03-04 23:39:23 +00002222 opcodes, returning a shorter pickle that contains the same data structure.
2223 (Contributed by Raymond Hettinger.)
2224
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002225* A :func:`get_data` function was added to the :mod:`pkgutil`
2226 module that returns the contents of resource files included
2227 with an installed Python package. For example::
2228
2229 >>> import pkgutil
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002230 >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
2231 BaseException
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002232 +-- SystemExit
2233 +-- KeyboardInterrupt
2234 +-- GeneratorExit
2235 +-- Exception
2236 +-- StopIteration
2237 +-- StandardError
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002238 ...
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002239
2240 (Contributed by Paul Moore; :issue:`2439`.)
2241
Christian Heimes2380ac72008-01-09 00:17:24 +00002242* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002243 their :attr:`buffer_size` attribute to change the size of the buffer
Christian Heimes2380ac72008-01-09 00:17:24 +00002244 used to hold character data.
Christian Heimes33fe8092008-04-13 13:53:33 +00002245 (Contributed by Achim Gaedke; :issue:`1137`.)
Christian Heimes2380ac72008-01-09 00:17:24 +00002246
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002247* The :mod:`Queue` module now provides queue variants that retrieve entries
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002248 in different orders. The :class:`PriorityQueue` class stores
2249 queued items in a heap and retrieves them in priority order,
Christian Heimesaf98da12008-01-27 15:18:18 +00002250 and :class:`LifoQueue` retrieves the most recently added entries first,
2251 meaning that it behaves like a stack.
2252 (Contributed by Raymond Hettinger.)
2253
Christian Heimes90aa7642007-12-19 02:45:37 +00002254* The :mod:`random` module's :class:`Random` objects can
2255 now be pickled on a 32-bit system and unpickled on a 64-bit
2256 system, and vice versa. Unfortunately, this change also means
2257 that Python 2.6's :class:`Random` objects can't be unpickled correctly
2258 on earlier versions of Python.
Christian Heimes33fe8092008-04-13 13:53:33 +00002259 (Contributed by Shawn Ligocki; :issue:`1727780`.)
Christian Heimes90aa7642007-12-19 02:45:37 +00002260
Christian Heimesf6cd9672008-03-26 13:45:42 +00002261 The new ``triangular(low, high, mode)`` function returns random
2262 numbers following a triangular distribution. The returned values
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002263 are between *low* and *high*, not including *high* itself, and
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002264 with *mode* as the most frequently occurring value
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00002265 in the distribution. (Contributed by Wladmir van der Laan and
Christian Heimes33fe8092008-04-13 13:53:33 +00002266 Raymond Hettinger; :issue:`1681432`.)
Christian Heimesf6cd9672008-03-26 13:45:42 +00002267
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002268* Long regular expression searches carried out by the :mod:`re`
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002269 module will check for signals being delivered, so
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002270 time-consuming searches can now be interrupted.
Christian Heimes33fe8092008-04-13 13:53:33 +00002271 (Contributed by Josh Hoyt and Ralf Schmitt; :issue:`846388`.)
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002272
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002273 The regular expression module is implemented by compiling bytecodes
2274 for a tiny regex-specific virtual machine. Untrusted code
2275 could create malicious strings of bytecode directly and cause crashes,
2276 so Python 2.6 includes a verifier for the regex bytecode.
2277 (Contributed by Guido van Rossum from work for Google App Engine;
2278 :issue:`3487`.)
2279
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002280* The :mod:`rlcompleter` module's :meth:`Completer.complete()` method
2281 will now ignore exceptions triggered while evaluating a name.
2282 (Fixed by Lorenz Quack; :issue:`2250`.)
2283
2284* The :mod:`sched` module's :class:`scheduler` instances now
2285 have a read-only :attr:`queue` attribute that returns the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002286 contents of the scheduler's queue, represented as a list of
2287 named tuples with the fields ``(time, priority, action, argument)``.
Christian Heimes33fe8092008-04-13 13:53:33 +00002288 (Contributed by Raymond Hettinger; :issue:`1861`.)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002289
Christian Heimesf6cd9672008-03-26 13:45:42 +00002290* The :mod:`select` module now has wrapper functions
2291 for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002292 :meth:`modify` method was added to the existing :class:`poll`
Christian Heimesf6cd9672008-03-26 13:45:42 +00002293 objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002294 or file object and an event mask, modifying the recorded event mask
2295 for that file.
Christian Heimes33fe8092008-04-13 13:53:33 +00002296 (Contributed by Christian Heimes; :issue:`1657`.)
Christian Heimes5e696852008-04-09 08:37:03 +00002297
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002298* The :func:`shutil.copytree` function now has an optional *ignore* argument
Georg Brandl86b2fb92008-07-16 03:43:04 +00002299 that takes a callable object. This callable will receive each directory path
2300 and a list of the directory's contents, and returns a list of names that
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002301 will be ignored, not copied.
Georg Brandl86b2fb92008-07-16 03:43:04 +00002302
2303 The :mod:`shutil` module also provides an :func:`ignore_patterns`
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002304 function for use with this new parameter. :func:`ignore_patterns`
2305 takes an arbitrary number of glob-style patterns and returns a
2306 callable that will ignore any files and directories that match any
2307 of these patterns. The following example copies a directory tree,
2308 but skips both :file:`.svn` directories and Emacs backup files,
2309 which have names ending with '~'::
Georg Brandl86b2fb92008-07-16 03:43:04 +00002310
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002311 shutil.copytree('Doc/library', '/tmp/library',
Georg Brandl86b2fb92008-07-16 03:43:04 +00002312 ignore=shutil.ignore_patterns('*~', '.svn'))
2313
2314 (Contributed by Tarek Ziadé; :issue:`2663`.)
2315
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002316* Integrating signal handling with GUI handling event loops
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002317 like those used by Tkinter or GTk+ has long been a problem; most
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002318 software ends up polling, waking up every fraction of a second to check
2319 if any GUI events have occurred.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002320 The :mod:`signal` module can now make this more efficient.
2321 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002322 to be used; when a signal is received, a byte is written to that
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002323 file descriptor. There's also a C-level function,
2324 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
2325
2326 Event loops will use this by opening a pipe to create two descriptors,
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00002327 one for reading and one for writing. The writable descriptor
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002328 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
2329 will be added to the list of descriptors monitored by the event loop via
2330 :cfunc:`select` or :cfunc:`poll`.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002331 On receiving a signal, a byte will be written and the main event loop
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002332 will be woken up, avoiding the need to poll.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002333
Christian Heimes33fe8092008-04-13 13:53:33 +00002334 (Contributed by Adam Olsen; :issue:`1583`.)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002335
Christian Heimes78644762008-03-04 23:39:23 +00002336 The :func:`siginterrupt` function is now available from Python code,
2337 and allows changing whether signals can interrupt system calls or not.
2338 (Contributed by Ralf Schmitt.)
2339
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00002340 The :func:`setitimer` and :func:`getitimer` functions have also been
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002341 added (where they're available). :func:`setitimer`
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00002342 allows setting interval timers that will cause a signal to be
2343 delivered to the process after a specified time, measured in
2344 wall-clock time, consumed process time, or combined process+system
Christian Heimes33fe8092008-04-13 13:53:33 +00002345 time. (Contributed by Guilherme Polo; :issue:`2240`.)
Neal Norwitzf5c7c2e2008-04-05 04:47:45 +00002346
Thomas Wouters89d996e2007-09-08 17:39:28 +00002347* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
2348 addition of the :class:`SMTP_SSL` class. This class supports an
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002349 interface identical to the existing :class:`SMTP` class.
2350 (Contributed by Monty Taylor.) Both class constructors also have an
2351 optional ``timeout`` parameter that specifies a timeout for the
2352 initial connection attempt, measured in seconds. (Contributed by
2353 Facundo Batista.)
Thomas Wouters89d996e2007-09-08 17:39:28 +00002354
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002355 An implementation of the LMTP protocol (:rfc:`2033`) was also added
2356 to the module. LMTP is used in place of SMTP when transferring
2357 e-mail between agents that don't manage a mail queue. (LMTP
2358 implemented by Leif Hedstrom; :issue:`957003`.)
Thomas Wouters89d996e2007-09-08 17:39:28 +00002359
Georg Brandl8bd05462009-11-18 18:53:54 +00002360 :meth:`SMTP.starttls` now complies with :rfc:`3207` and forgets any
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002361 knowledge obtained from the server not obtained from the TLS
2362 negotiation itself. (Patch contributed by Bill Fenner;
Christian Heimes33fe8092008-04-13 13:53:33 +00002363 :issue:`829951`.)
Christian Heimes679db4a2008-01-18 09:56:22 +00002364
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002365* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
2366 a high-performance non-IP-based protocol designed for use in clustered
2367 environments. TIPC addresses are 4- or 5-tuples.
Christian Heimes33fe8092008-04-13 13:53:33 +00002368 (Contributed by Alberto Bertogli; :issue:`1646`.)
Georg Brandlfceab5a2008-01-19 20:08:23 +00002369
Benjamin Petersona0dfa822009-11-13 02:25:08 +00002370 A new function, :func:`create_connection`, takes an address and
2371 connects to it using an optional timeout value, returning the
2372 connected socket object. This function also looks up the address's
2373 type and connects to it using IPv4 or IPv6 as appropriate. Changing
2374 your code to use :func:`create_connection` instead of
2375 ``socket(socket.AF_INET, ...)`` may be all that's required to make
2376 your code work with IPv6.
Neal Norwitz32dde222008-04-15 06:43:13 +00002377
Georg Brandlfceab5a2008-01-19 20:08:23 +00002378* The base classes in the :mod:`SocketServer` module now support
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002379 calling a :meth:`handle_timeout` method after a span of inactivity
2380 specified by the server's :attr:`timeout` attribute. (Contributed
2381 by Michael Pomraning.) The :meth:`serve_forever` method
Christian Heimes5e696852008-04-09 08:37:03 +00002382 now takes an optional poll interval measured in seconds,
2383 controlling how often the server will check for a shutdown request.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002384 (Contributed by Pedro Werneck and Jeffrey Yasskin;
Christian Heimes33fe8092008-04-13 13:53:33 +00002385 :issue:`742598`, :issue:`1193577`.)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002386
Benjamin Peterson5478b472008-09-17 22:25:09 +00002387* The :mod:`sqlite3` module, maintained by Gerhard Haering,
Georg Brandl48310cd2009-01-03 21:18:54 +00002388 has been updated from version 2.3.2 in Python 2.5 to
Benjamin Peterson5478b472008-09-17 22:25:09 +00002389 version 2.4.1.
Georg Brandl48310cd2009-01-03 21:18:54 +00002390
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002391* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002392 using the format character ``'?'``.
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002393 (Contributed by David Remahl.)
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002394
2395* The :class:`Popen` objects provided by the :mod:`subprocess` module
2396 now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods.
2397 On Windows, :meth:`send_signal` only supports the :const:`SIGTERM`
2398 signal, and all these methods are aliases for the Win32 API function
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002399 :cfunc:`TerminateProcess`.
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002400 (Contributed by Christian Heimes.)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002401
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002402* A new variable in the :mod:`sys` module, :attr:`float_info`, is an
2403 object containing information derived from the :file:`float.h` file
2404 about the platform's floating-point support. Attributes of this
2405 object include :attr:`mant_dig` (number of digits in the mantissa),
2406 :attr:`epsilon` (smallest difference between 1.0 and the next
2407 largest value representable), and several others. (Contributed by
2408 Christian Heimes; :issue:`1534`.)
Christian Heimes90aa7642007-12-19 02:45:37 +00002409
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002410 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
2411 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
2412 If this variable is true, the compiled files are not written. The
2413 variable is initially set on start-up by supplying the :option:`-B`
2414 switch to the Python interpreter, or by setting the
2415 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002416 running the interpreter. Python code can subsequently
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002417 change the value of this variable to control whether bytecode files
2418 are written or not.
2419 (Contributed by Neal Norwitz and Georg Brandl.)
2420
Georg Brandl0c77a822008-06-10 16:37:50 +00002421 Information about the command-line arguments supplied to the Python
2422 interpreter is available by reading attributes of a named
2423 tuple available as ``sys.flags``. For example, the :attr:`verbose`
2424 attribute is true if Python
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002425 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
2426 These attributes are all read-only.
2427 (Contributed by Christian Heimes.)
2428
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002429 A new function, :func:`getsizeof`, takes a Python object and returns
Georg Brandl0c77a822008-06-10 16:37:50 +00002430 the amount of memory used by the object, measured in bytes. Built-in
2431 objects return correct results; third-party extensions may not,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002432 but can define a :meth:`__sizeof__` method to return the
Georg Brandl0c77a822008-06-10 16:37:50 +00002433 object's size.
2434 (Contributed by Robert Schuppenies; :issue:`2898`.)
2435
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002436 It's now possible to determine the current profiler and tracer functions
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002437 by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
Christian Heimes33fe8092008-04-13 13:53:33 +00002438 (Contributed by Georg Brandl; :issue:`1648`.)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00002439
Benjamin Peterson9bc93512008-09-22 22:10:59 +00002440* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) tarfiles in
2441 addition to the POSIX.1-1988 (ustar) and GNU tar formats that were
2442 already supported. The default format is GNU tar; specify the
2443 ``format`` parameter to open a file using a different format::
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002444
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002445 tar = tarfile.open("output.tar", "w",
2446 format=tarfile.PAX_FORMAT)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002447
Benjamin Peterson9bc93512008-09-22 22:10:59 +00002448 The new ``encoding`` and ``errors`` parameters specify an encoding and
2449 an error handling scheme for character conversions. ``'strict'``,
2450 ``'ignore'``, and ``'replace'`` are the three standard ways Python can
2451 handle errors,;
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002452 ``'utf-8'`` is a special value that replaces bad characters with
2453 their UTF-8 representation. (Character conversions occur because the
2454 PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002455
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002456 The :meth:`TarFile.add` method now accepts an ``exclude`` argument that's
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002457 a function that can be used to exclude certain filenames from
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002458 an archive.
2459 The function must take a filename and return true if the file
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002460 should be excluded or false if it should be archived.
2461 The function is applied to both the name initially passed to :meth:`add`
2462 and to the names of files in recursively-added directories.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002463
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002464 (All changes contributed by Lars Gustäbel).
2465
Thomas Wouters89d996e2007-09-08 17:39:28 +00002466* An optional ``timeout`` parameter was added to the
2467 :class:`telnetlib.Telnet` class constructor, specifying a timeout
2468 measured in seconds. (Added by Facundo Batista.)
Georg Brandl116aa622007-08-15 14:28:22 +00002469
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002470* The :class:`tempfile.NamedTemporaryFile` class usually deletes
2471 the temporary file it created when the file is closed. This
2472 behaviour can now be changed by passing ``delete=False`` to the
Christian Heimes33fe8092008-04-13 13:53:33 +00002473 constructor. (Contributed by Damien Miller; :issue:`1537850`.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002474
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002475 A new class, :class:`SpooledTemporaryFile`, behaves like
2476 a temporary file but stores its data in memory until a maximum size is
2477 exceeded. On reaching that limit, the contents will be written to
Christian Heimes78644762008-03-04 23:39:23 +00002478 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
2479
2480 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002481 both work as context managers, so you can write
Christian Heimes78644762008-03-04 23:39:23 +00002482 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
Christian Heimes33fe8092008-04-13 13:53:33 +00002483 (Contributed by Alexander Belopolsky; :issue:`2021`.)
Christian Heimes78644762008-03-04 23:39:23 +00002484
Georg Brandl48310cd2009-01-03 21:18:54 +00002485* The :mod:`test.test_support` module gained a number
2486 of context managers useful for writing tests.
2487 :func:`EnvironmentVarGuard` is a
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002488 context manager that temporarily changes environment variables and
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002489 automatically restores them to their old values.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002490
2491 Another context manager, :class:`TransientResource`, can surround calls
2492 to resources that may or may not be available; it will catch and
2493 ignore a specified list of exceptions. For example,
2494 a network test may ignore certain failures when connecting to an
2495 external web site::
2496
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002497 with test_support.TransientResource(IOError,
2498 errno=errno.ETIMEDOUT):
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002499 f = urllib.urlopen('https://sf.net')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002500 ...
2501
Georg Brandl48310cd2009-01-03 21:18:54 +00002502 Finally, :func:`check_warnings` resets the :mod:`warning` module's
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002503 warning filters and returns an object that will record all warning
2504 messages triggered (:issue:`3781`)::
2505
2506 with test_support.check_warnings() as wrec:
2507 warnings.simplefilter("always")
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002508 # ... code that triggers a warning ...
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002509 assert str(wrec.message) == "function is outdated"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002510 assert len(wrec.warnings) == 1, "Multiple warnings raised"
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002511
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002512 (Contributed by Brett Cannon.)
2513
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002514* The :mod:`textwrap` module can now preserve existing whitespace
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002515 at the beginnings and ends of the newly-created lines
2516 by specifying ``drop_whitespace=False``
2517 as an argument::
2518
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002519 >>> S = """This sentence has a bunch of
2520 ... extra whitespace."""
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002521 >>> print textwrap.fill(S, width=15)
2522 This sentence
2523 has a bunch
2524 of extra
2525 whitespace.
2526 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
2527 This sentence
2528 has a bunch
2529 of extra
2530 whitespace.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002531 >>>
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002532
Christian Heimes33fe8092008-04-13 13:53:33 +00002533 (Contributed by Dwayne Bailey; :issue:`1581073`.)
Georg Brandl116aa622007-08-15 14:28:22 +00002534
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002535* The :mod:`threading` module API is being changed to use properties
2536 such as :attr:`daemon` instead of :meth:`setDaemon` and
2537 :meth:`isDaemon` methods, and some methods have been renamed to use
2538 underscores instead of camel-case; for example, the
2539 :meth:`activeCount` method is renamed to :meth:`active_count`. Both
2540 the 2.6 and 3.0 versions of the module support the same properties
2541 and renamed methods, but don't remove the old methods. No date has been set
Georg Brandl48310cd2009-01-03 21:18:54 +00002542 for the deprecation of the old APIs in Python 3.x; the old APIs won't
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002543 be removed in any 2.x version.
Benjamin Petersondcc1e112008-09-03 22:22:18 +00002544 (Carried out by several people, most notably Benjamin Peterson.)
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002545
2546 The :mod:`threading` module's :class:`Thread` objects
2547 gained an :attr:`ident` property that returns the thread's
2548 identifier, a nonzero integer. (Contributed by Gregory P. Smith;
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002549 :issue:`2871`.)
Georg Brandl0c77a822008-06-10 16:37:50 +00002550
2551* The :mod:`timeit` module now accepts callables as well as strings
Thomas Wouters89d996e2007-09-08 17:39:28 +00002552 for the statement being timed and for the setup code.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002553 Two convenience functions were added for creating
2554 :class:`Timer` instances:
2555 ``repeat(stmt, setup, time, repeat, number)`` and
Thomas Wouters89d996e2007-09-08 17:39:28 +00002556 ``timeit(stmt, setup, time, number)`` create an instance and call
Christian Heimes33fe8092008-04-13 13:53:33 +00002557 the corresponding method. (Contributed by Erik Demaine;
2558 :issue:`1533909`.)
Thomas Wouters89d996e2007-09-08 17:39:28 +00002559
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002560* The :mod:`Tkinter` module now accepts lists and tuples for options,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002561 separating the elements by spaces before passing the resulting value to
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002562 Tcl/Tk.
2563 (Contributed by Guilherme Polo; :issue:`2906`.)
2564
Georg Brandl0c77a822008-06-10 16:37:50 +00002565* The :mod:`turtle` module for turtle graphics was greatly enhanced by
2566 Gregor Lingl. New features in the module include:
2567
2568 * Better animation of turtle movement and rotation.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002569 * Control over turtle movement using the new :meth:`delay`,
2570 :meth:`tracer`, and :meth:`speed` methods.
2571 * The ability to set new shapes for the turtle, and to
Georg Brandl0c77a822008-06-10 16:37:50 +00002572 define a new coordinate system.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002573 * Turtles now have an :meth:`undo()` method that can roll back actions.
Georg Brandl0c77a822008-06-10 16:37:50 +00002574 * Simple support for reacting to input events such as mouse and keyboard
2575 activity, making it possible to write simple games.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002576 * A :file:`turtle.cfg` file can be used to customize the starting appearance
Georg Brandl0c77a822008-06-10 16:37:50 +00002577 of the turtle's screen.
2578 * The module's docstrings can be replaced by new docstrings that have been
2579 translated into another language.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002580
Georg Brandl0c77a822008-06-10 16:37:50 +00002581 (:issue:`1513695`)
2582
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002583* An optional ``timeout`` parameter was added to the
2584 :func:`urllib.urlopen` function and the
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002585 :class:`urllib.ftpwrapper` class constructor, as well as the
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586 :func:`urllib2.urlopen` function. The parameter specifies a timeout
2587 measured in seconds. For example::
2588
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002589 >>> u = urllib2.urlopen("http://slow.example.com",
2590 timeout=3)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002591 Traceback (most recent call last):
2592 ...
2593 urllib2.URLError: <urlopen error timed out>
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002594 >>>
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002595
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002596 (Added by Facundo Batista.)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002597
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002598* The Unicode database provided by the :mod:`unicodedata` module
Georg Brandl48310cd2009-01-03 21:18:54 +00002599 has been updated to version 5.1.0. (Updated by
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002600 Martin von Loewis; :issue:`3811`.)
2601
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002602* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002603 gained an optional *line* argument that can be used to supply the
2604 line of source code. (Added as part of :issue:`1631171`, which re-implemented
2605 part of the :mod:`warnings` module in C code.)
2606
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00002607 A new function, :func:`catch_warnings`, is a context manager
2608 intended for testing purposes that lets you temporarily modify the
2609 warning filters and then restore their original values (:issue:`3781`).
Georg Brandl48310cd2009-01-03 21:18:54 +00002610
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002611* The XML-RPC :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Georg Brandl9afde1c2007-11-01 20:32:30 +00002612 classes can now be prevented from immediately opening and binding to
2613 their socket by passing True as the ``bind_and_activate``
2614 constructor parameter. This can be used to modify the instance's
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002615 :attr:`allow_reuse_address` attribute before calling the
2616 :meth:`server_bind` and :meth:`server_activate` methods to
Georg Brandl9afde1c2007-11-01 20:32:30 +00002617 open the socket and begin listening for connections.
Christian Heimes33fe8092008-04-13 13:53:33 +00002618 (Contributed by Peter Parente; :issue:`1599845`.)
Georg Brandl9afde1c2007-11-01 20:32:30 +00002619
2620 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002621 attribute; if true, the exception and formatted traceback are returned
2622 as HTTP headers "X-Exception" and "X-Traceback". This feature is
Georg Brandl9afde1c2007-11-01 20:32:30 +00002623 for debugging purposes only and should not be used on production servers
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002624 because the tracebacks might reveal passwords or other sensitive
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002625 information. (Contributed by Alan McIntyre as part of his
Georg Brandl9afde1c2007-11-01 20:32:30 +00002626 project for Google's Summer of Code 2007.)
2627
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002628* The :mod:`xmlrpclib` module no longer automatically converts
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002629 :class:`datetime.date` and :class:`datetime.time` to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002630 :class:`xmlrpclib.DateTime` type; the conversion semantics were
2631 not necessarily correct for all applications. Code using
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002632 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
2633 instances. (:issue:`1330538`) The code can also handle
Georg Brandl0c77a822008-06-10 16:37:50 +00002634 dates before 1900 (contributed by Ralf Schmitt; :issue:`2014`)
2635 and 64-bit integers represented by using ``<i8>`` in XML-RPC responses
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002636 (contributed by Riku Lindblad; :issue:`2985`).
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002637
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002638* The :mod:`zipfile` module's :class:`ZipFile` class now has
2639 :meth:`extract` and :meth:`extractall` methods that will unpack
2640 a single file or all the files in the archive to the current directory, or
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002641 to a specified directory::
2642
2643 z = zipfile.ZipFile('python-251.zip')
2644
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002645 # Unpack a single file, writing it relative
2646 # to the /tmp directory.
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002647 z.extract('Python/sysmodule.c', '/tmp')
2648
2649 # Unpack all the files in the archive.
2650 z.extractall()
2651
Christian Heimes33fe8092008-04-13 13:53:33 +00002652 (Contributed by Alan McIntyre; :issue:`467924`.)
Guido van Rossum7736b5b2008-01-15 21:44:53 +00002653
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002654 The :meth:`open`, :meth:`read` and :meth:`extract` methods can now
Georg Brandl0c77a822008-06-10 16:37:50 +00002655 take either a filename or a :class:`ZipInfo` object. This is useful when an
2656 archive accidentally contains a duplicated filename.
2657 (Contributed by Graham Horler; :issue:`1775025`.)
Alexandre Vassalotti6461e102008-05-15 22:09:29 +00002658
Georg Brandl0c77a822008-06-10 16:37:50 +00002659 Finally, :mod:`zipfile` now supports using Unicode filenames
2660 for archived files. (Contributed by Alexey Borzenkov; :issue:`1734346`.)
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002661
Christian Heimes5b5e81c2007-12-31 16:14:33 +00002662.. ======================================================================
2663.. whole new modules get described in subsections here
Georg Brandl9afde1c2007-11-01 20:32:30 +00002664
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002665The :mod:`ast` module
2666----------------------
2667
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002668The :mod:`ast` module provides an Abstract Syntax Tree
2669representation of Python code, and Armin Ronacher
2670contributed a set of helper functions that perform a variety of
2671common tasks. These will be useful for HTML templating
2672packages, code analyzers, and similar tools that process
2673Python code.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002674
2675The :func:`parse` function takes an expression and returns an AST.
2676The :func:`dump` function outputs a representation of a tree, suitable
2677for debugging::
2678
2679 import ast
2680
2681 t = ast.parse("""
2682 d = {}
2683 for i in 'abcdefghijklm':
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002684 d[i + i] = ord(i) - ord('a') + 1
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002685 print d
2686 """)
2687 print ast.dump(t)
2688
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002689This outputs a deeply nested tree::
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002690
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002691 Module(body=[
2692 Assign(targets=[
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002693 Name(id='d', ctx=Store())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002694 ], value=Dict(keys=[], values=[]))
2695 For(target=Name(id='i', ctx=Store()),
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002696 iter=Str(s='abcdefghijklm'), body=[
2697 Assign(targets=[
2698 Subscript(value=
2699 Name(id='d', ctx=Load()),
2700 slice=
2701 Index(value=
2702 BinOp(left=Name(id='i', ctx=Load()), op=Add(),
2703 right=Name(id='i', ctx=Load()))), ctx=Store())
2704 ], value=
2705 BinOp(left=
2706 BinOp(left=
2707 Call(func=
2708 Name(id='ord', ctx=Load()), args=[
2709 Name(id='i', ctx=Load())
2710 ], keywords=[], starargs=None, kwargs=None),
2711 op=Sub(), right=Call(func=
2712 Name(id='ord', ctx=Load()), args=[
2713 Str(s='a')
2714 ], keywords=[], starargs=None, kwargs=None)),
2715 op=Add(), right=Num(n=1)))
2716 ], orelse=[])
2717 Print(dest=None, values=[
2718 Name(id='d', ctx=Load())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002719 ], nl=True)
2720 ])
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002721
2722The :func:`literal_eval` method takes a string or an AST
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002723representing a literal expression, parses and evaluates it, and
2724returns the resulting value. A literal expression is a Python
2725expression containing only strings, numbers, dictionaries,
2726etc. but no statements or function calls. If you need to
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002727evaluate an expression but cannot accept the security risk of using an
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002728:func:`eval` call, :func:`literal_eval` will handle it safely::
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002729
2730 >>> literal = '("a", "b", {2:4, 3:8, 1:2})'
2731 >>> print ast.literal_eval(literal)
2732 ('a', 'b', {1: 2, 2: 4, 3: 8})
2733 >>> print ast.literal_eval('"a" + "b"')
2734 Traceback (most recent call last):
2735 ...
2736 ValueError: malformed string
2737
Georg Brandl86b2fb92008-07-16 03:43:04 +00002738The module also includes :class:`NodeVisitor` and
2739:class:`NodeTransformer` classes for traversing and modifying an AST,
2740and functions for common transformations such as changing line
2741numbers.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002742
2743.. ======================================================================
2744
2745The :mod:`future_builtins` module
2746--------------------------------------
2747
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002748Python 3.0 makes many changes to the repertoire of built-in
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002749functions, and most of the changes can't be introduced in the Python
27502.x series because they would break compatibility.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002751The :mod:`future_builtins` module provides versions
2752of these built-in functions that can be imported when writing
Benjamin Petersonf9c98b42008-07-02 16:19:28 +000027533.0-compatible code.
2754
2755The functions in this module currently include:
2756
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002757* ``ascii(obj)``: equivalent to :func:`repr`. In Python 3.0,
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002758 :func:`repr` will return a Unicode string, while :func:`ascii` will
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002759 return a pure ASCII bytestring.
2760
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002761* ``filter(predicate, iterable)``,
2762 ``map(func, iterable1, ...)``: the 3.0 versions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00002763 return iterators, unlike the 2.x builtins which return lists.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002764
Benjamin Petersonae5360b2008-09-08 23:05:23 +00002765* ``hex(value)``, ``oct(value)``: instead of calling the
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002766 :meth:`__hex__` or :meth:`__oct__` methods, these versions will
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002767 call the :meth:`__index__` method and convert the result to hexadecimal
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002768 or octal. :func:`oct` will use the new ``0o`` notation for its
2769 result.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002770
2771.. ======================================================================
2772
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002773The :mod:`json` module: JavaScript Object Notation
2774--------------------------------------------------------------------
Christian Heimes90540002008-05-08 14:29:10 +00002775
2776The new :mod:`json` module supports the encoding and decoding of Python types in
2777JSON (Javascript Object Notation). JSON is a lightweight interchange format
2778often used in web applications. For more information about JSON, see
2779http://www.json.org.
2780
Georg Brandl22b34312009-07-26 14:54:51 +00002781:mod:`json` comes with support for decoding and encoding most built-in Python
Christian Heimes90540002008-05-08 14:29:10 +00002782types. The following example encodes and decodes a dictionary::
2783
2784 >>> import json
2785 >>> data = {"spam" : "foo", "parrot" : 42}
2786 >>> in_json = json.dumps(data) # Encode the data
2787 >>> in_json
2788 '{"parrot": 42, "spam": "foo"}'
2789 >>> json.loads(in_json) # Decode into a Python object
2790 {"spam" : "foo", "parrot" : 42}
2791
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002792It's also possible to write your own decoders and encoders to support
2793more types. Pretty-printing of the JSON strings is also supported.
Christian Heimes90540002008-05-08 14:29:10 +00002794
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002795:mod:`json` (originally called simplejson) was written by Bob
2796Ippolito.
Christian Heimes90540002008-05-08 14:29:10 +00002797
2798
Christian Heimesaf98da12008-01-27 15:18:18 +00002799.. ======================================================================
2800
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002801The :mod:`plistlib` module: A Property-List Parser
Christian Heimesaf98da12008-01-27 15:18:18 +00002802--------------------------------------------------
2803
Georg Brandlc575c902008-09-13 17:46:05 +00002804The ``.plist`` format is commonly used on Mac OS X to
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002805store basic data types (numbers, strings, lists,
2806and dictionaries) by serializing them into an XML-based format.
2807It resembles the XML-RPC serialization of data types.
Christian Heimesaf98da12008-01-27 15:18:18 +00002808
Georg Brandlc575c902008-09-13 17:46:05 +00002809Despite being primarily used on Mac OS X, the format
Christian Heimesaf98da12008-01-27 15:18:18 +00002810has nothing Mac-specific about it and the Python implementation works
2811on any platform that Python supports, so the :mod:`plistlib` module
2812has been promoted to the standard library.
2813
2814Using the module is simple::
2815
2816 import sys
2817 import plistlib
2818 import datetime
2819
2820 # Create data structure
2821 data_struct = dict(lastAccessed=datetime.datetime.now(),
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002822 version=1,
2823 categories=('Personal','Shared','Private'))
Christian Heimesaf98da12008-01-27 15:18:18 +00002824
2825 # Create string containing XML.
2826 plist_str = plistlib.writePlistToString(data_struct)
2827 new_struct = plistlib.readPlistFromString(plist_str)
2828 print data_struct
2829 print new_struct
2830
2831 # Write data structure to a file and read it back.
2832 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
2833 new_struct = plistlib.readPlist('/tmp/customizations.plist')
2834
2835 # read/writePlist accepts file-like objects as well as paths.
2836 plistlib.writePlist(data_struct, sys.stdout)
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002837
2838.. ======================================================================
2839
Georg Brandl2ee470f2008-07-16 12:55:28 +00002840ctypes Enhancements
2841--------------------------------------------------
2842
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002843Thomas Heller continued to maintain and enhance the
2844:mod:`ctypes` module.
Georg Brandl2ee470f2008-07-16 12:55:28 +00002845
2846:mod:`ctypes` now supports a :class:`c_bool` datatype
2847that represents the C99 ``bool`` type. (Contributed by David Remahl;
2848:issue:`1649190`.)
2849
2850The :mod:`ctypes` string, buffer and array types have improved
2851support for extended slicing syntax,
2852where various combinations of ``(start, stop, step)`` are supplied.
2853(Implemented by Thomas Wouters.)
2854
2855.. Revision 57769
2856
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002857All :mod:`ctypes` data types now support
2858:meth:`from_buffer` and :meth:`from_buffer_copy`
2859methods that create a ctypes instance based on a
2860provided buffer object. :meth:`from_buffer_copy` copies
2861the contents of the object,
2862while :meth:`from_buffer` will share the same memory area.
2863
Georg Brandl2ee470f2008-07-16 12:55:28 +00002864A new calling convention tells :mod:`ctypes` to clear the ``errno`` or
2865Win32 LastError variables at the outset of each wrapped call.
2866(Implemented by Thomas Heller; :issue:`1798`.)
2867
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002868You can now retrieve the Unix ``errno`` variable after a function
2869call. When creating a wrapped function, you can supply
2870``use_errno=True`` as a keyword parameter to the :func:`DLL` function
2871and then call the module-level methods :meth:`set_errno` and
2872:meth:`get_errno` to set and retrieve the error value.
Georg Brandl2ee470f2008-07-16 12:55:28 +00002873
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002874The Win32 LastError variable is similarly supported by
Georg Brandl2ee470f2008-07-16 12:55:28 +00002875the :func:`DLL`, :func:`OleDLL`, and :func:`WinDLL` functions.
2876You supply ``use_last_error=True`` as a keyword parameter
2877and then call the module-level methods :meth:`set_last_error`
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002878and :meth:`get_last_error`.
Georg Brandl2ee470f2008-07-16 12:55:28 +00002879
2880The :func:`byref` function, used to retrieve a pointer to a ctypes
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002881instance, now has an optional *offset* parameter that is a byte
Georg Brandl2ee470f2008-07-16 12:55:28 +00002882count that will be added to the returned pointer.
2883
2884.. ======================================================================
2885
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002886Improved SSL Support
2887--------------------------------------------------
2888
2889Bill Janssen made extensive improvements to Python 2.6's support for
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002890the Secure Sockets Layer by adding a new module, :mod:`ssl`, that's
2891built atop the `OpenSSL <http://www.openssl.org/>`__ library.
2892This new module provides more control over the protocol negotiated,
2893the X.509 certificates used, and has better support for writing SSL
2894servers (as opposed to clients) in Python. The existing SSL support
2895in the :mod:`socket` module hasn't been removed and continues to work,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002896though it will be removed in Python 3.0.
2897
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002898To use the new module, you must first create a TCP connection in the
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002899usual way and then pass it to the :func:`ssl.wrap_socket` function.
2900It's possible to specify whether a certificate is required, and to
2901obtain certificate info by calling the :meth:`getpeercert` method.
2902
2903.. seealso::
2904
2905 The documentation for the :mod:`ssl` module.
Christian Heimesaf98da12008-01-27 15:18:18 +00002906
Christian Heimes5b5e81c2007-12-31 16:14:33 +00002907.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00002908
Georg Brandl8bd05462009-11-18 18:53:54 +00002909Deprecations and Removals
2910=========================
2911
2912* String exceptions have been removed. Attempting to use them raises a
2913 :exc:`TypeError`.
2914
2915* Changes to the :class:`Exception` interface
2916 as dictated by :pep:`352` continue to be made. For 2.6,
2917 the :attr:`message` attribute is being deprecated in favor of the
2918 :attr:`args` attribute.
2919
2920* (3.0-warning mode) Python 3.0 will feature a reorganized standard
2921 library that will drop many outdated modules and rename others.
2922 Python 2.6 running in 3.0-warning mode will warn about these modules
2923 when they are imported.
2924
2925 The list of deprecated modules is:
2926 :mod:`audiodev`,
2927 :mod:`bgenlocations`,
2928 :mod:`buildtools`,
2929 :mod:`bundlebuilder`,
2930 :mod:`Canvas`,
2931 :mod:`compiler`,
2932 :mod:`dircache`,
2933 :mod:`dl`,
2934 :mod:`fpformat`,
2935 :mod:`gensuitemodule`,
2936 :mod:`ihooks`,
2937 :mod:`imageop`,
2938 :mod:`imgfile`,
2939 :mod:`linuxaudiodev`,
2940 :mod:`mhlib`,
2941 :mod:`mimetools`,
2942 :mod:`multifile`,
2943 :mod:`new`,
2944 :mod:`pure`,
2945 :mod:`statvfs`,
2946 :mod:`sunaudiodev`,
2947 :mod:`test.testall`, and
2948 :mod:`toaiff`.
2949
2950* The :mod:`gopherlib` module has been removed.
2951
2952* The :mod:`MimeWriter` module and :mod:`mimify` module
2953 have been deprecated; use the :mod:`email`
2954 package instead.
2955
2956* The :mod:`md5` module has been deprecated; use the :mod:`hashlib` module
2957 instead.
2958
2959* The :mod:`posixfile` module has been deprecated; :func:`fcntl.lockf`
2960 provides better locking.
2961
2962* The :mod:`popen2` module has been deprecated; use the :mod:`subprocess`
2963 module.
2964
2965* The :mod:`rgbimg` module has been removed.
2966
2967* The :mod:`sets` module has been deprecated; it's better to
2968 use the built-in :class:`set` and :class:`frozenset` types.
2969
2970* The :mod:`sha` module has been deprecated; use the :mod:`hashlib` module
2971 instead.
2972
2973
2974.. ======================================================================
2975
Georg Brandl116aa622007-08-15 14:28:22 +00002976
2977Build and C API Changes
2978=======================
2979
2980Changes to Python's build process and to the C API include:
2981
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002982* Python now must be compiled with C89 compilers (after 19
2983 years!). This means that the Python source tree has dropped its
2984 own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
2985 are in the C89 standard library.
2986
2987* Python 2.6 can be built with Microsoft Visual Studio 2008 (version
2988 9.0), and this is the new default compiler. See the
2989 :file:`PCbuild` directory for the build files. (Implemented by
2990 Christian Heimes.)
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +00002991
Georg Brandlc575c902008-09-13 17:46:05 +00002992* On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002993 The :program:`configure` script
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002994 can take a :option:`--with-universal-archs=[32-bit|64-bit|all]`
2995 switch, controlling whether the binaries are built for 32-bit
2996 architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
2997 (Contributed by Ronald Oussoren.)
2998
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00002999* The BerkeleyDB module now has a C API object, available as
Georg Brandl9afde1c2007-11-01 20:32:30 +00003000 ``bsddb.db.api``. This object can be used by other C extensions
3001 that wish to use the :mod:`bsddb` module for their own purposes.
Georg Brandl495f7b52009-10-27 15:28:25 +00003002 (Contributed by Duncan Grisby.)
Georg Brandl9afde1c2007-11-01 20:32:30 +00003003
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003004* The new buffer interface, previously described in
Christian Heimes33fe8092008-04-13 13:53:33 +00003005 `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__,
Martin v. Löwis423be952008-08-13 15:53:07 +00003006 adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyBuffer_Release`,
Christian Heimes33fe8092008-04-13 13:53:33 +00003007 as well as a few other functions.
Georg Brandl9afde1c2007-11-01 20:32:30 +00003008
Christian Heimes5e696852008-04-09 08:37:03 +00003009* Python's use of the C stdio library is now thread-safe, or at least
3010 as thread-safe as the underlying library is. A long-standing potential
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003011 bug occurred if one thread closed a file object while another thread
3012 was reading from or writing to the object. In 2.6 file objects
3013 have a reference count, manipulated by the
Christian Heimes5e696852008-04-09 08:37:03 +00003014 :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount`
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003015 functions. File objects can't be closed unless the reference count
3016 is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL
3017 is still held, before carrying out an I/O operation using the
Christian Heimes5e696852008-04-09 08:37:03 +00003018 ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called
3019 immediately after the GIL is re-acquired.
3020 (Contributed by Antoine Pitrou and Gregory P. Smith.)
3021
Christian Heimes33fe8092008-04-13 13:53:33 +00003022* Importing modules simultaneously in two different threads no longer
3023 deadlocks; it will now raise an :exc:`ImportError`. A new API
3024 function, :cfunc:`PyImport_ImportModuleNoBlock`, will look for a
3025 module in ``sys.modules`` first, then try to import it after
3026 acquiring an import lock. If the import lock is held by another
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003027 thread, an :exc:`ImportError` is raised.
Christian Heimes33fe8092008-04-13 13:53:33 +00003028 (Contributed by Christian Heimes.)
3029
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003030* Several functions return information about the platform's
Christian Heimes90aa7642007-12-19 02:45:37 +00003031 floating-point support. :cfunc:`PyFloat_GetMax` returns
3032 the maximum representable floating point value,
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003033 and :cfunc:`PyFloat_GetMin` returns the minimum
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003034 positive value. :cfunc:`PyFloat_GetInfo` returns an object
Christian Heimes90aa7642007-12-19 02:45:37 +00003035 containing more information from the :file:`float.h` file, such as
3036 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
3037 (smallest difference between 1.0 and the next largest value
3038 representable), and several others.
Christian Heimes33fe8092008-04-13 13:53:33 +00003039 (Contributed by Christian Heimes; :issue:`1534`.)
Georg Brandl116aa622007-08-15 14:28:22 +00003040
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003041* C functions and methods that use
3042 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
3043 have a :meth:`__complex__` method. In particular, the functions in the
3044 :mod:`cmath` module will now accept objects with this method.
3045 This is a backport of a Python 3.0 change.
3046 (Contributed by Mark Dickinson; :issue:`1675423`.)
3047
Christian Heimesa34706f2008-01-04 03:06:10 +00003048* Python's C API now includes two functions for case-insensitive string
Christian Heimesc3f30c42008-02-22 16:37:40 +00003049 comparisons, ``PyOS_stricmp(char*, char*)``
Christian Heimesa34706f2008-01-04 03:06:10 +00003050 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimes33fe8092008-04-13 13:53:33 +00003051 (Contributed by Christian Heimes; :issue:`1635`.)
Christian Heimesa34706f2008-01-04 03:06:10 +00003052
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003053* Many C extensions define their own little macro for adding
3054 integers and strings to the module's dictionary in the
3055 ``init*`` function. Python 2.6 finally defines standard macros
Christian Heimes5e696852008-04-09 08:37:03 +00003056 for adding values to a module, :cmacro:`PyModule_AddStringMacro`
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003057 and :cmacro:`PyModule_AddIntMacro()`. (Contributed by
Christian Heimes5e696852008-04-09 08:37:03 +00003058 Christian Heimes.)
3059
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003060* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
3061 they are macros,
Christian Heimes3f419af2008-01-04 03:08:33 +00003062 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Christian Heimesa34706f2008-01-04 03:06:10 +00003063 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003064 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003065 The mixed-case macros are still available
3066 in Python 2.6 for backward compatibility.
Christian Heimes33fe8092008-04-13 13:53:33 +00003067 (:issue:`1629`)
Christian Heimesa34706f2008-01-04 03:06:10 +00003068
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003069* Distutils now places C extensions it builds in a
Christian Heimesaf98da12008-01-27 15:18:18 +00003070 different directory when running on a debug version of Python.
Christian Heimes33fe8092008-04-13 13:53:33 +00003071 (Contributed by Collin Winter; :issue:`1530959`.)
Christian Heimesaf98da12008-01-27 15:18:18 +00003072
Christian Heimes78644762008-03-04 23:39:23 +00003073* Several basic data types, such as integers and strings, maintain
3074 internal free lists of objects that can be re-used. The data
3075 structures for these free lists now follow a naming convention: the
3076 variable is always named ``free_list``, the counter is always named
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003077 ``numfree``, and a macro ``Py<typename>_MAXFREELIST`` is
Christian Heimes78644762008-03-04 23:39:23 +00003078 always defined.
Christian Heimesaf98da12008-01-27 15:18:18 +00003079
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003080* A new Makefile target, "make patchcheck", prepares the Python source tree
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003081 for making a patch: it fixes trailing whitespace in all modified
Christian Heimes5e696852008-04-09 08:37:03 +00003082 ``.py`` files, checks whether the documentation has been changed,
3083 and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files
3084 have been updated.
3085 (Contributed by Brett Cannon.)
3086
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003087 Another new target, "make profile-opt", compiles a Python binary
3088 using GCC's profile-guided optimization. It compiles Python with
3089 profiling enabled, runs the test suite to obtain a set of profiling
3090 results, and then compiles using these results for optimization.
3091 (Contributed by Gregory P. Smith.)
3092
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003093.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003094
Christian Heimesa34706f2008-01-04 03:06:10 +00003095Port-Specific Changes: Windows
3096-----------------------------------
3097
Christian Heimes81ee3ef2008-05-04 22:42:01 +00003098* The support for Windows 95, 98, ME and NT4 has been dropped.
3099 Python 2.6 requires at least Windows 2000 SP4.
3100
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003101* The new default compiler on Windows is Visual Studio 2008 (version
3102 9.0). The build directories for Visual Studio 2003 (version 7.1) and
3103 2005 (version 8.0) were moved into the PC/ directory. The new
3104 :file:`PCbuild` directory supports cross compilation for X64, debug
3105 builds and Profile Guided Optimization (PGO). PGO builds are roughly
3106 10% faster than normal builds. (Contributed by Christian Heimes
3107 with help from Amaury Forgeot d'Arc and Martin von Loewis.)
3108
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003109* The :mod:`msvcrt` module now supports
Christian Heimesa34706f2008-01-04 03:06:10 +00003110 both the normal and wide char variants of the console I/O
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003111 API. The :func:`getwch` function reads a keypress and returns a Unicode
Christian Heimesa34706f2008-01-04 03:06:10 +00003112 value, as does the :func:`getwche` function. The :func:`putwch` function
3113 takes a Unicode character and writes it to the console.
Christian Heimes679db4a2008-01-18 09:56:22 +00003114 (Contributed by Christian Heimes.)
3115
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003116* :func:`os.path.expandvars` will now expand environment variables in
3117 the form "%var%", and "~user" will be expanded into the user's home
3118 directory path. (Contributed by Josiah Carlson; :issue:`957650`.)
Christian Heimes679db4a2008-01-18 09:56:22 +00003119
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003120* The :mod:`socket` module's socket objects now have an
3121 :meth:`ioctl` method that provides a limited interface to the
Christian Heimes679db4a2008-01-18 09:56:22 +00003122 :cfunc:`WSAIoctl` system interface.
Georg Brandl116aa622007-08-15 14:28:22 +00003123
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003124* The :mod:`_winreg` module now has a function,
3125 :func:`ExpandEnvironmentStrings`,
Guido van Rossum7736b5b2008-01-15 21:44:53 +00003126 that expands environment variable references such as ``%NAME%``
3127 in an input string. The handle objects provided by this
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003128 module now support the context protocol, so they can be used
Christian Heimes679db4a2008-01-18 09:56:22 +00003129 in :keyword:`with` statements. (Contributed by Christian Heimes.)
3130
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003131 :mod:`_winreg` also has better support for x64 systems,
Christian Heimes5e696852008-04-09 08:37:03 +00003132 exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`,
3133 and :func:`QueryReflectionKey` functions, which enable and disable
3134 registry reflection for 32-bit processes running on 64-bit systems.
Christian Heimes33fe8092008-04-13 13:53:33 +00003135 (:issue:`1753245`)
Christian Heimes5e696852008-04-09 08:37:03 +00003136
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003137* The :mod:`msilib` module's :class:`Record` object
3138 gained :meth:`GetInteger` and :meth:`GetString` methods that
3139 return field values as an integer or a string.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003140 (Contributed by Floris Bruynooghe; :issue:`2125`.)
3141
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003142.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003143
Georg Brandlc575c902008-09-13 17:46:05 +00003144Port-Specific Changes: Mac OS X
Georg Brandl0c77a822008-06-10 16:37:50 +00003145-----------------------------------
3146
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003147* When compiling a framework build of Python, you can now specify the
3148 framework name to be used by providing the
3149 :option:`--with-framework-name=` option to the
Georg Brandl0c77a822008-06-10 16:37:50 +00003150 :program:`configure` script.
3151
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003152* The :mod:`macfs` module has been removed. This in turn required the
3153 :func:`macostools.touched` function to be removed because it depended on the
3154 :mod:`macfs` module. (:issue:`1490190`)
3155
Georg Brandlc575c902008-09-13 17:46:05 +00003156* Many other Mac OS modules have been deprecated and will removed in
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003157 Python 3.0:
3158 :mod:`_builtinSuites`,
3159 :mod:`aepack`,
3160 :mod:`aetools`,
3161 :mod:`aetypes`,
3162 :mod:`applesingle`,
3163 :mod:`appletrawmain`,
3164 :mod:`appletrunner`,
3165 :mod:`argvemulator`,
3166 :mod:`Audio_mac`,
3167 :mod:`autoGIL`,
3168 :mod:`Carbon`,
3169 :mod:`cfmfile`,
3170 :mod:`CodeWarrior`,
3171 :mod:`ColorPicker`,
3172 :mod:`EasyDialogs`,
3173 :mod:`Explorer`,
3174 :mod:`Finder`,
3175 :mod:`FrameWork`,
3176 :mod:`findertools`,
3177 :mod:`ic`,
3178 :mod:`icglue`,
3179 :mod:`icopen`,
3180 :mod:`macerrors`,
3181 :mod:`MacOS`,
3182 :mod:`macfs`,
3183 :mod:`macostools`,
3184 :mod:`macresource`,
3185 :mod:`MiniAEFrame`,
3186 :mod:`Nav`,
3187 :mod:`Netscape`,
3188 :mod:`OSATerminology`,
3189 :mod:`pimp`,
3190 :mod:`PixMapWrapper`,
3191 :mod:`StdSuites`,
3192 :mod:`SystemEvents`,
3193 :mod:`Terminal`, and
3194 :mod:`terminalcommand`.
3195
Georg Brandl0c77a822008-06-10 16:37:50 +00003196.. ======================================================================
3197
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003198Port-Specific Changes: IRIX
3199-----------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00003200
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003201A number of old IRIX-specific modules were deprecated and will
3202be removed in Python 3.0:
3203:mod:`al` and :mod:`AL`,
3204:mod:`cd`,
3205:mod:`cddb`,
3206:mod:`cdplayer`,
3207:mod:`CL` and :mod:`cl`,
3208:mod:`DEVICE`,
3209:mod:`ERRNO`,
3210:mod:`FILE`,
3211:mod:`FL` and :mod:`fl`,
3212:mod:`flp`,
3213:mod:`fm`,
3214:mod:`GET`,
3215:mod:`GLWS`,
3216:mod:`GL` and :mod:`gl`,
3217:mod:`IN`,
3218:mod:`IOCTL`,
3219:mod:`jpeg`,
3220:mod:`panelparser`,
3221:mod:`readcd`,
3222:mod:`SV` and :mod:`sv`,
3223:mod:`torgb`,
3224:mod:`videoreader`, and
3225:mod:`WAIT`.
Georg Brandl116aa622007-08-15 14:28:22 +00003226
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003227.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003228
3229
3230Porting to Python 2.6
3231=====================
3232
Christian Heimesf6cd9672008-03-26 13:45:42 +00003233This section lists previously described changes and other bugfixes
3234that may require changes to your code:
Georg Brandl116aa622007-08-15 14:28:22 +00003235
Benjamin Petersondcc1e112008-09-03 22:22:18 +00003236* Classes that aren't supposed to be hashable should
3237 set ``__hash__ = None`` in their definitions to indicate
3238 the fact.
3239
Benjamin Peterson28d88b42009-01-09 03:03:23 +00003240* String exceptions have been removed. Attempting to use them raises a
3241 :exc:`TypeError`.
3242
Christian Heimesfaf2f632008-01-06 16:59:19 +00003243* The :meth:`__init__` method of :class:`collections.deque`
Christian Heimesa34706f2008-01-04 03:06:10 +00003244 now clears any existing contents of the deque
3245 before adding elements from the iterable. This change makes the
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003246 behavior match ``list.__init__()``.
Christian Heimesa34706f2008-01-04 03:06:10 +00003247
Benjamin Peterson5478b472008-09-17 22:25:09 +00003248* :meth:`object.__init__` previously accepted arbitrary arguments and
3249 keyword arguments, ignoring them. In Python 2.6, this is no longer
Georg Brandl48310cd2009-01-03 21:18:54 +00003250 allowed and will result in a :exc:`TypeError`. This will affect
3251 :meth:`__init__` methods that end up calling the corresponding
Benjamin Peterson5478b472008-09-17 22:25:09 +00003252 method on :class:`object` (perhaps through using :func:`super`).
3253 See :issue:`1683368` for discussion.
3254
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003255* The :class:`Decimal` constructor now accepts leading and trailing
Guido van Rossum7736b5b2008-01-15 21:44:53 +00003256 whitespace when passed a string. Previously it would raise an
3257 :exc:`InvalidOperation` exception. On the other hand, the
3258 :meth:`create_decimal` method of :class:`Context` objects now
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003259 explicitly disallows extra whitespace, raising a
Guido van Rossum7736b5b2008-01-15 21:44:53 +00003260 :exc:`ConversionSyntax` exception.
3261
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003262* Due to an implementation accident, if you passed a file path to
Guido van Rossum7736b5b2008-01-15 21:44:53 +00003263 the built-in :func:`__import__` function, it would actually import
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003264 the specified file. This was never intended to work, however, and
3265 the implementation now explicitly checks for this case and raises
Guido van Rossum7736b5b2008-01-15 21:44:53 +00003266 an :exc:`ImportError`.
3267
Christian Heimes33fe8092008-04-13 13:53:33 +00003268* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule`
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003269 functions now default to absolute imports, not relative imports.
Christian Heimes33fe8092008-04-13 13:53:33 +00003270 This will affect C extensions that import other modules.
3271
Benjamin Petersondcc1e112008-09-03 22:22:18 +00003272* C API: extension data types that shouldn't be hashable
3273 should define their ``tp_hash`` slot to
3274 :cfunc:`PyObject_HashNotImplemented`.
3275
Georg Brandl9afde1c2007-11-01 20:32:30 +00003276* The :mod:`socket` module exception :exc:`socket.error` now inherits
3277 from :exc:`IOError`. Previously it wasn't a subclass of
3278 :exc:`StandardError` but now it is, through :exc:`IOError`.
Christian Heimes33fe8092008-04-13 13:53:33 +00003279 (Implemented by Gregory P. Smith; :issue:`1706815`.)
Georg Brandl116aa622007-08-15 14:28:22 +00003280
Christian Heimes05e8be12008-02-23 18:30:17 +00003281* The :mod:`xmlrpclib` module no longer automatically converts
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003282 :class:`datetime.date` and :class:`datetime.time` to the
Christian Heimes05e8be12008-02-23 18:30:17 +00003283 :class:`xmlrpclib.DateTime` type; the conversion semantics were
3284 not necessarily correct for all applications. Code using
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003285 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
Christian Heimes33fe8092008-04-13 13:53:33 +00003286 instances. (:issue:`1330538`)
Christian Heimes05e8be12008-02-23 18:30:17 +00003287
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003288* (3.0-warning mode) The :class:`Exception` class now warns
3289 when accessed using slicing or index access; having
Christian Heimesf6cd9672008-03-26 13:45:42 +00003290 :class:`Exception` behave like a tuple is being phased out.
3291
3292* (3.0-warning mode) inequality comparisons between two dictionaries
Christian Heimes02781dc2008-03-21 01:11:52 +00003293 or two objects that don't implement comparison methods are reported
3294 as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2``
3295 is being phased out.
Benjamin Petersonf9c98b42008-07-02 16:19:28 +00003296
Christian Heimes02781dc2008-03-21 01:11:52 +00003297 Comparisons between cells, which are an implementation detail of Python's
3298 scoping rules, also cause warnings because such comparisons are forbidden
3299 entirely in 3.0.
3300
Christian Heimes5b5e81c2007-12-31 16:14:33 +00003301.. ======================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003302
3303
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003304.. _26acks:
Georg Brandl116aa622007-08-15 14:28:22 +00003305
3306Acknowledgements
3307================
3308
Benjamin Petersonae5360b2008-09-08 23:05:23 +00003309The author would like to thank the following people for offering
3310suggestions, corrections and assistance with various drafts of this
Georg Brandl48310cd2009-01-03 21:18:54 +00003311article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy,
3312Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr,
Benjamin Peterson206e3072008-10-19 14:07:49 +00003313Antoine Pitrou, Brian Warner.
Georg Brandl116aa622007-08-15 14:28:22 +00003314