blob: cf9682b86c8d113fc40230ea562f670d547c4d2b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001****************************
Georg Brandle152a772008-05-24 18:31:28 +00002 What's New in Python 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +00003****************************
4
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00005.. XXX add trademark info for Apple, Microsoft, SourceForge.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00006
Georg Brandl8ec7f652007-08-15 14:28:01 +00007:Author: A.M. Kuchling
8:Release: |release|
9:Date: |today|
10
Georg Brandlb19be572007-12-29 10:57:00 +000011.. $Id: whatsnew26.tex 55746 2007-06-02 18:33:53Z neal.norwitz $
12 Rules for maintenance:
Georg Brandle152a772008-05-24 18:31:28 +000013
Georg Brandlb19be572007-12-29 10:57:00 +000014 * Anyone can add text to this document. Do not spend very much time
15 on the wording of your changes, because your text will probably
16 get rewritten to some degree.
Georg Brandle152a772008-05-24 18:31:28 +000017
Georg Brandlb19be572007-12-29 10:57:00 +000018 * The maintainer will go through Misc/NEWS periodically and add
19 changes; it's therefore more important to add your changes to
20 Misc/NEWS than to this file.
Georg Brandle152a772008-05-24 18:31:28 +000021
Georg Brandlb19be572007-12-29 10:57:00 +000022 * This is not a complete list of every single change; completeness
23 is the purpose of Misc/NEWS. Some changes I consider too small
24 or esoteric to include. If such a change is added to the text,
25 I'll just remove it. (This is another reason you shouldn't spend
26 too much time on writing your addition.)
Georg Brandle152a772008-05-24 18:31:28 +000027
Georg Brandlb19be572007-12-29 10:57:00 +000028 * If you want to draw your new text to the attention of the
29 maintainer, add 'XXX' to the beginning of the paragraph or
30 section.
Georg Brandle152a772008-05-24 18:31:28 +000031
Georg Brandlb19be572007-12-29 10:57:00 +000032 * It's OK to just add a fragmentary note about a change. For
33 example: "XXX Describe the transmogrify() function added to the
34 socket module." The maintainer will research the change and
35 write the necessary text.
Georg Brandle152a772008-05-24 18:31:28 +000036
Georg Brandlb19be572007-12-29 10:57:00 +000037 * You can comment out your additions if you like, but it's not
38 necessary (especially when a final release is some months away).
Georg Brandle152a772008-05-24 18:31:28 +000039
Georg Brandlb19be572007-12-29 10:57:00 +000040 * Credit the author of a patch or bugfix. Just the name is
41 sufficient; the e-mail address isn't necessary.
Georg Brandle152a772008-05-24 18:31:28 +000042
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +000043 * It's helpful to add the bug/patch number in a parenthetical comment.
Georg Brandle152a772008-05-24 18:31:28 +000044
Georg Brandlb19be572007-12-29 10:57:00 +000045 XXX Describe the transmogrify() function added to the socket
46 module.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +000047 (Contributed by P.Y. Developer; :issue:`12345`.)
Georg Brandle152a772008-05-24 18:31:28 +000048
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +000049 This saves the maintainer some effort going through the SVN logs
Georg Brandlb19be572007-12-29 10:57:00 +000050 when researching a change.
Georg Brandl8ec7f652007-08-15 14:28:01 +000051
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +000052This article explains the new features in Python 2.6. The release
53schedule is described in :pep:`361`; currently the final release is
Andrew M. Kuchlingb93dc5f2008-07-13 21:43:52 +000054scheduled for October 1 2008.
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
Andrew M. Kuchling17f84292008-04-10 21:29:01 +000056This article doesn't attempt to provide a complete specification of
57the new features, but instead provides a convenient overview. For
58full details, you should refer to the documentation for Python 2.6. If
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +000059you want to understand the rationale for the design and
60implementation, refer to the PEP for a particular new feature.
61Whenever possible, "What's New in Python" links to the bug/patch item
62for each change.
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
Georg Brandlb19be572007-12-29 10:57:00 +000064.. Compare with previous release in 2 - 3 sentences here.
65 add hyperlink when the documentation becomes available online.
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
Georg Brandlb19be572007-12-29 10:57:00 +000067.. ========================================================================
68.. Large, PEP-level features and changes should be described here.
69.. Should there be a new section here for 3k migration?
70.. Or perhaps a more general section describing module changes/deprecation?
71.. ========================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000073Python 3.0
74================
75
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000076The development cycle for Python 2.6 also saw the release of the first
Georg Brandle152a772008-05-24 18:31:28 +000077alphas of Python 3.0, and the development of 3.0 has influenced
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000078a number of features in 2.6.
79
80Python 3.0 is a far-ranging redesign of Python that breaks
81compatibility with the 2.x series. This means that existing Python
82code will need a certain amount of conversion in order to run on
83Python 3.0. However, not all the changes in 3.0 necessarily break
84compatibility. In cases where new features won't cause existing code
85to break, they've been backported to 2.6 and are described in this
Georg Brandle152a772008-05-24 18:31:28 +000086document in the appropriate place. Some of the 3.0-derived features
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000087are:
88
89* A :meth:`__complex__` method for converting objects to a complex number.
90* Alternate syntax for catching exceptions: ``except TypeError as exc``.
91* The addition of :func:`functools.reduce` as a synonym for the built-in
92 :func:`reduce` function.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000093
94A new command-line switch, :option:`-3`, enables warnings
95about features that will be removed in Python 3.0. You can run code
96with this switch to see how much work will be necessary to port
Georg Brandle152a772008-05-24 18:31:28 +000097code to 3.0. The value of this switch is available
Georg Brandld5b635f2008-03-25 08:29:14 +000098to Python code as the boolean variable :data:`sys.py3kwarning`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000099and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000100
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000101Python 3.0 adds several new built-in functions and change the
102semantics of some existing built-ins. Entirely new functions such as
103:func:`bin` have simply been added to Python 2.6, but existing
104built-ins haven't been changed; instead, the :mod:`future_builtins`
105module has versions with the new 3.0 semantics. Code written to be
106compatible with 3.0 can do ``from future_builtins import hex, map``
107as necessary.
108
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000109.. seealso::
110
111 The 3xxx series of PEPs, which describes the development process for
112 Python 3.0 and various features that have been accepted, rejected,
113 or are still under consideration.
114
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000115
116Development Changes
117==================================================
118
Georg Brandle152a772008-05-24 18:31:28 +0000119While 2.6 was being developed, the Python development process
120underwent two significant changes: the developer group
121switched from SourceForge's issue tracker to a customized
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000122Roundup installation, and the documentation was converted from
David Goodger09f57b72008-04-21 14:40:22 +0000123LaTeX to reStructuredText.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000124
125
126New Issue Tracker: Roundup
127--------------------------------------------------
128
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000129For a long time, the Python developers have been growing increasingly
130annoyed by SourceForge's bug tracker. SourceForge's hosted solution
131doesn't permit much customization; for example, it wasn't possible to
132customize the life cycle of issues.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000133
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000134The infrastructure committee of the Python Software Foundation
135therefore posted a call for issue trackers, asking volunteers to set
136up different products and import some of the bugs and patches from
137SourceForge. Four different trackers were examined: Atlassian's `Jira
Georg Brandle152a772008-05-24 18:31:28 +0000138<http://www.atlassian.com/software/jira/>`__,
139`Launchpad <http://www.launchpad.net>`__,
140`Roundup <http://roundup.sourceforge.net/>`__, and
141`Trac <http://trac.edgewall.org/>`__.
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000142The committee eventually settled on Jira
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000143and Roundup as the two candidates. Jira is a commercial product that
Georg Brandle152a772008-05-24 18:31:28 +0000144offers a no-cost hosted instance to free-software projects; Roundup
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000145is an open-source project that requires volunteers
146to administer it and a server to host it.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000147
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000148After posting a call for volunteers, a new Roundup installation was
149set up at http://bugs.python.org. One installation of Roundup can
150host multiple trackers, and this server now also hosts issue trackers
Georg Brandle152a772008-05-24 18:31:28 +0000151for Jython and for the Python web site. It will surely find
Andrew M. Kuchling17f84292008-04-10 21:29:01 +0000152other uses in the future. Where possible,
153this edition of "What's New in Python" links to the bug/patch
154item for each change.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000155
Georg Brandle152a772008-05-24 18:31:28 +0000156Hosting is kindly provided by
157`Upfront Systems <http://www.upfrontsystems.co.za/>`__
Andrew M. Kuchling17f84292008-04-10 21:29:01 +0000158of Stellenbosch, South Africa. Martin von Loewis put a
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000159lot of effort into importing existing bugs and patches from
Georg Brandle152a772008-05-24 18:31:28 +0000160SourceForge; his scripts for this import operation are at
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000161http://svn.python.org/view/tracker/importer/.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000162
163.. seealso::
164
Georg Brandle152a772008-05-24 18:31:28 +0000165 http://bugs.python.org
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000166 The Python bug tracker.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000167
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000168 http://bugs.jython.org:
169 The Jython bug tracker.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000170
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000171 http://roundup.sourceforge.net/
172 Roundup downloads and documentation.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000173
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000174
Benjamin Peterson56fcb0b2008-05-02 22:12:58 +0000175New Documentation Format: reStructuredText Using Sphinx
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000176-----------------------------------------------------------
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000177
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000178Since the Python project's inception around 1989, the documentation
179had been written using LaTeX. At that time, most documentation was
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000180printed out for later study, not viewed online. LaTeX was widely used
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000181because it provided attractive printed output while remaining
182straightforward to write, once the basic rules of the markup have been
183learned.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000184
185LaTeX is still used today for writing technical publications destined
186for printing, but the landscape for programming tools has shifted. We
187no longer print out reams of documentation; instead, we browse through
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000188it online and HTML has become the most important format to support.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000189Unfortunately, converting LaTeX to HTML is fairly complicated, and
190Fred L. Drake Jr., the Python documentation editor for many years,
191spent a lot of time wrestling the conversion process into shape.
Georg Brandle152a772008-05-24 18:31:28 +0000192Occasionally people would suggest converting the documentation into
193SGML or, later, XML, but performing a good conversion is a major task
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000194and no one pursued the task to completion.
195
Andrew M. Kuchling17f84292008-04-10 21:29:01 +0000196During the 2.6 development cycle, Georg Brandl put a substantial
197effort into building a new toolchain for processing the documentation.
198The resulting package is called Sphinx, and is available from
David Goodger09f57b72008-04-21 14:40:22 +0000199http://sphinx.pocoo.org/. The input format is reStructuredText, a
Andrew M. Kuchling17f84292008-04-10 21:29:01 +0000200markup commonly used in the Python community that supports custom
201extensions and directives. Sphinx concentrates on HTML output,
202producing attractively styled and modern HTML, though printed output
203is still supported through conversion to LaTeX. Sphinx is a
204standalone package that can be used in documenting other projects.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000205
206.. seealso::
207
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000208 :ref:`documenting-index`
209 Describes how to write for Python's documentation.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000210
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000211 `Sphinx <http://sphinx.pocoo.org/>`__
212 Documentation and code for the Sphinx toolchain.
213
214 `Docutils <http://docutils.sf.net>`__
David Goodger09f57b72008-04-21 14:40:22 +0000215 The underlying reStructuredText parser and toolset.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000216
217
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000218PEP 343: The 'with' statement
219=============================
220
221The previous version, Python 2.5, added the ':keyword:`with`'
222statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000223import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000224be specially enabled; this means that :keyword:`with` is now always a
Georg Brandle152a772008-05-24 18:31:28 +0000225keyword. The rest of this section is a copy of the corresponding
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000226section from "What's New in Python 2.5" document; if you read
227it back when Python 2.5 came out, you can skip the rest of this
228section.
229
230The ':keyword:`with`' statement clarifies code that previously would use
231``try...finally`` blocks to ensure that clean-up code is executed. In this
232section, I'll discuss the statement as it will commonly be used. In the next
233section, I'll examine the implementation details and show how to write objects
234for use with this statement.
235
236The ':keyword:`with`' statement is a new control-flow structure whose basic
237structure is::
238
239 with expression [as variable]:
240 with-block
241
242The expression is evaluated, and it should result in an object that supports the
243context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
244methods.
245
246The object's :meth:`__enter__` is called before *with-block* is executed and
247therefore can run set-up code. It also may return a value that is bound to the
248name *variable*, if given. (Note carefully that *variable* is *not* assigned
249the result of *expression*.)
250
251After execution of the *with-block* is finished, the object's :meth:`__exit__`
252method is called, even if the block raised an exception, and can therefore run
253clean-up code.
254
255Some standard Python objects now support the context management protocol and can
256be used with the ':keyword:`with`' statement. File objects are one example::
257
258 with open('/etc/passwd', 'r') as f:
259 for line in f:
260 print line
261 ... more processing code ...
262
263After this statement has executed, the file object in *f* will have been
264automatically closed, even if the :keyword:`for` loop raised an exception part-
265way through the block.
266
267.. note::
268
269 In this case, *f* is the same object created by :func:`open`, because
270 :meth:`file.__enter__` returns *self*.
271
272The :mod:`threading` module's locks and condition variables also support the
273':keyword:`with`' statement::
274
275 lock = threading.Lock()
276 with lock:
277 # Critical section of code
278 ...
279
280The lock is acquired before the block is executed and always released once the
281block is complete.
282
283The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
284to save and restore the current decimal context, which encapsulates the desired
285precision and rounding characteristics for computations::
286
287 from decimal import Decimal, Context, localcontext
288
289 # Displays with default precision of 28 digits
290 v = Decimal('578')
291 print v.sqrt()
292
293 with localcontext(Context(prec=16)):
294 # All code in this block uses a precision of 16 digits.
295 # The original context is restored on exiting the block.
296 print v.sqrt()
297
298
299.. _new-26-context-managers:
300
301Writing Context Managers
302------------------------
303
304Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
305people will only use ':keyword:`with`' in company with existing objects and
306don't need to know these details, so you can skip the rest of this section if
307you like. Authors of new objects will need to understand the details of the
308underlying implementation and should keep reading.
309
310A high-level explanation of the context management protocol is:
311
312* The expression is evaluated and should result in an object called a "context
313 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
314 methods.
315
316* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000317 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000318 discarded.
319
320* The code in *BLOCK* is executed.
321
322* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
323 is called with the exception details, the same values returned by
324 :func:`sys.exc_info`. The method's return value controls whether the exception
325 is re-raised: any false value re-raises the exception, and ``True`` will result
326 in suppressing it. You'll only rarely want to suppress the exception, because
327 if you do the author of the code containing the ':keyword:`with`' statement will
328 never realize anything went wrong.
329
330* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
331 called, but *type*, *value*, and *traceback* are all ``None``.
332
333Let's think through an example. I won't present detailed code but will only
334sketch the methods necessary for a database that supports transactions.
335
336(For people unfamiliar with database terminology: a set of changes to the
337database are grouped into a transaction. Transactions can be either committed,
338meaning that all the changes are written into the database, or rolled back,
339meaning that the changes are all discarded and the database is unchanged. See
340any database textbook for more information.)
341
342Let's assume there's an object representing a database connection. Our goal will
343be to let the user write code like this::
344
345 db_connection = DatabaseConnection()
346 with db_connection as cursor:
347 cursor.execute('insert into ...')
348 cursor.execute('delete from ...')
349 # ... more operations ...
350
351The transaction should be committed if the code in the block runs flawlessly or
352rolled back if there's an exception. Here's the basic interface for
353:class:`DatabaseConnection` that I'll assume::
354
355 class DatabaseConnection:
356 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000357 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000358 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000359 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000360 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000361 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000362 "Rolls back current transaction"
363
364The :meth:`__enter__` method is pretty easy, having only to start a new
365transaction. For this application the resulting cursor object would be a useful
366result, so the method will return it. The user can then add ``as cursor`` to
367their ':keyword:`with`' statement to bind the cursor to a variable name. ::
368
369 class DatabaseConnection:
370 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000371 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000372 # Code to start a new transaction
373 cursor = self.cursor()
374 return cursor
375
376The :meth:`__exit__` method is the most complicated because it's where most of
377the work has to be done. The method has to check if an exception occurred. If
378there was no exception, the transaction is committed. The transaction is rolled
379back if there was an exception.
380
381In the code below, execution will just fall off the end of the function,
382returning the default value of ``None``. ``None`` is false, so the exception
383will be re-raised automatically. If you wished, you could be more explicit and
384add a :keyword:`return` statement at the marked location. ::
385
386 class DatabaseConnection:
387 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000388 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000389 if tb is None:
390 # No exception, so commit
391 self.commit()
392 else:
393 # Exception occurred, so rollback.
394 self.rollback()
395 # return False
396
397
398.. _module-contextlib:
399
400The contextlib module
401---------------------
402
403The new :mod:`contextlib` module provides some functions and a decorator that
404are useful for writing objects for use with the ':keyword:`with`' statement.
405
406The decorator is called :func:`contextmanager`, and lets you write a single
407generator function instead of defining a new class. The generator should yield
408exactly one value. The code up to the :keyword:`yield` will be executed as the
409:meth:`__enter__` method, and the value yielded will be the method's return
410value that will get bound to the variable in the ':keyword:`with`' statement's
411:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
412executed in the :meth:`__exit__` method. Any exception raised in the block will
413be raised by the :keyword:`yield` statement.
414
415Our database example from the previous section could be written using this
416decorator as::
417
418 from contextlib import contextmanager
419
420 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000421 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000422 cursor = connection.cursor()
423 try:
424 yield cursor
425 except:
426 connection.rollback()
427 raise
428 else:
429 connection.commit()
430
431 db = DatabaseConnection()
432 with db_transaction(db) as cursor:
433 ...
434
435The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
436that combines a number of context managers so you don't need to write nested
437':keyword:`with`' statements. In this example, the single ':keyword:`with`'
438statement both starts a database transaction and acquires a thread lock::
439
440 lock = threading.Lock()
441 with nested (db_transaction(db), lock) as (cursor, locked):
442 ...
443
444Finally, the :func:`closing(object)` function returns *object* so that it can be
445bound to a variable, and calls ``object.close`` at the end of the block. ::
446
447 import urllib, sys
448 from contextlib import closing
449
450 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
451 for line in f:
452 sys.stdout.write(line)
453
454
455.. seealso::
456
457 :pep:`343` - The "with" statement
458 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
459 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
460 ':keyword:`with`' statement, which can be helpful in learning how the statement
461 works.
462
463 The documentation for the :mod:`contextlib` module.
464
Georg Brandlb19be572007-12-29 10:57:00 +0000465.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000466
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000467.. _pep-0366:
468
469PEP 366: Explicit Relative Imports From a Main Module
470============================================================
471
472Python's :option:`-m` switch allows running a module as a script.
473When you ran a module that was located inside a package, relative
474imports didn't work correctly.
475
476The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
477When present, relative imports will be relative to the value of this
478attribute instead of the :attr:`__name__` attribute. PEP 302-style
479importers can then set :attr:`__package__`. The :mod:`runpy` module
480that implements the :option:`-m` switch now does this, so relative imports
481can now be used in scripts running from inside a package.
482
Georg Brandlb19be572007-12-29 10:57:00 +0000483.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000484
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000485.. _pep-0370:
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000486
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000487PEP 370: Per-user ``site-packages`` Directory
488=====================================================
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000489
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000490When you run Python, the module search path ``sys.modules`` usually
491includes a directory whose path ends in ``"site-packages"``. This
492directory is intended to hold locally-installed packages available to
493all users on a machine or using a particular site installation.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000494
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000495Python 2.6 introduces a convention for user-specific site directories.
496The directory varies depending on the platform:
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000497
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000498* Unix and MacOS: :file:`~/.local/`
499* Windows: :file:`%APPDATA%/Python`
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000500
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000501Within this directory, there will be version-specific subdirectories,
502such as :file:`lib/python2.6/site-packages` on Unix/MacOS and
503:file:`Python26/site-packages` on Windows.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000504
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +0000505If you don't like the default directory, it can be overridden by an
506environment variable. :envvar:`PYTHONUSERBASE` sets the root
507directory used for all Python versions supporting this feature. On
508Windows, the directory for application-specific data can be changed by
509setting the :envvar:`APPDATA` environment variable. You can also
510modify the :file:`site.py` file for your Python installation.
511
512The feature can be disabled entirely by running Python with the
513:option:`-s` option or setting the :envvar:`PYTHONNOUSERSITE`
514environment variable.
515
516.. seealso::
517
518 :pep:`370` - Per-user ``site-packages`` Directory
519 PEP written and implemented by Christian Heimes.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000520
Georg Brandle152a772008-05-24 18:31:28 +0000521
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000522.. ======================================================================
523
Andrew M. Kuchlinga809c982008-06-11 12:53:14 +0000524.. _pep-0371:
525
526PEP 371: The ``multiprocessing`` Package
527=====================================================
528
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000529The new :mod:`multiprocessing` package lets Python programs create new
530processes that will perform a computation and return a result to the
531parent. The parent and child processes can communicate using queues
532and pipes, synchronize their operations using locks and semaphores,
533and can share simple arrays of data.
Benjamin Petersona6a72922008-07-01 19:51:54 +0000534
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000535The :mod:`multiprocessing` module started out as an exact emulation of
536the :mod:`threading` module using processes instead of threads. That
537goal was discarded along the path to Python 2.6, but the general
538approach of the module is still similar. The fundamental class
539is the :class:`Process`, which is passed a callable object and
540a collection of arguments. The :meth:`start` method
541sets the callable running in a subprocess, after which you can call
542the :meth:`is_alive` method to check whether the subprocess is still running
543and the :meth:`join` method to wait for the process to exit.
Benjamin Petersona6a72922008-07-01 19:51:54 +0000544
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000545Here's a simple example where the subprocess will calculate a
546factorial. The function doing the calculation is a bit strange; it's
547written to take significantly longer when the input argument is a
548multiple of 4.
Benjamin Petersona6a72922008-07-01 19:51:54 +0000549
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000550::
Benjamin Petersona6a72922008-07-01 19:51:54 +0000551
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000552 import time
553 from multiprocessing import Process, Queue
Benjamin Petersona6a72922008-07-01 19:51:54 +0000554
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000555
556 def factorial(queue, N):
557 "Compute a factorial."
558 # If N is a multiple of 4, this function will take much longer.
559 if (N % 4) == 0:
560 time.sleep(.05 * N/4)
561
562 # Calculate the result
563 fact = 1L
564 for i in range(1, N+1):
565 fact = fact * i
566
567 # Put the result on the queue
568 queue.put(fact)
569
570 if __name__ == '__main__':
571 queue = Queue()
572
573 N = 5
574
575 p = Process(target=factorial, args=(queue, N))
576 p.start()
577 p.join()
578
579 result = queue.get()
580 print 'Factorial', N, '=', result
581
582A :class:`Queue` object is created and stored as a global. The child
583process will use the value of the variable when the child was created;
584because it's a :class:`Queue`, parent and child can use the object to
585communicate. (If the parent were to change the value of the global
586variable, the child's value would be unaffected, and vice versa.)
587
588Two other classes, :class:`Pool` and :class:`Manager`, provide
589higher-level interfaces. :class:`Pool` will create a fixed number of
590worker processes, and requests can then be distributed to the workers
591by calling :meth:`apply` or `apply_async`, adding a single request,
592and :meth:`map` or :meth:`map_async` to distribute a number of
593requests. The following code uses a :class:`Pool` to spread requests
594across 5 worker processes, receiving a list of results back.
595
596::
597
598 from multiprocessing import Pool
599
600 p = Pool(5)
601 result = p.map(factorial, range(1, 1000, 10))
602 for v in result:
603 print v
604
605This produces the following output::
606
607 1
608 39916800
609 51090942171709440000
610 8222838654177922817725562880000000
611 33452526613163807108170062053440751665152000000000
612 ...
613
614The :class:`Manager` class creates a separate server process that can
615hold master copies of Python data structures. Other processes can
616then access and modify these data structures by using proxy objects.
617The following example creates a shared dictionary by calling the
618:meth:`dict` method; the worker processes then insert values into the
619dictionary. (No locking is done automatically, which doesn't matter
620in this example. :class:`Manager`'s methods also include
621:meth:`Lock`, :meth:`RLock`, and :meth:`Semaphore` to create shared locks.
622
623::
624
625 import time
626 from multiprocessing import Pool, Manager
627
628 def factorial(N, dictionary):
629 "Compute a factorial."
630 # Calculate the result
631 fact = 1L
632 for i in range(1, N+1):
633 fact = fact * i
634
635 # Store result in dictionary
636 dictionary[N] = fact
637
638 if __name__ == '__main__':
639 p = Pool(5)
640 mgr = Manager()
641 d = mgr.dict() # Create shared dictionary
642
643 # Run tasks using the pool
644 for N in range(1, 1000, 10):
645 p.apply_async(factorial, (N, d))
646
647 # Mark pool as closed -- no more tasks can be added.
648 p.close()
649
650 # Wait for tasks to exit
651 p.join()
652
653 # Output results
654 for k, v in sorted(d.items()):
655 print k, v
656
657This will produce the output::
658
659 1 1
660 11 39916800
661 21 51090942171709440000
662 31 8222838654177922817725562880000000
663 41 33452526613163807108170062053440751665152000000000
664 51 1551118753287382280224243016469303211063259720016986112000000000000
Andrew M. Kuchlinga809c982008-06-11 12:53:14 +0000665
666.. seealso::
667
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000668 The documentation for the :mod:`multiprocessing` module.
669
Benjamin Peterson2b917c92008-06-24 02:41:08 +0000670 :pep:`371` - Addition of the multiprocessing package
Andrew M. Kuchlinga809c982008-06-11 12:53:14 +0000671 PEP written by Jesse Noller and Richard Oudkerk;
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +0000672 implemented by Richard Oudkerk and Jesse Noller.
Andrew M. Kuchlinga809c982008-06-11 12:53:14 +0000673
Andrew M. Kuchling4ec0c272008-07-14 01:18:31 +0000674
Andrew M. Kuchlinga809c982008-06-11 12:53:14 +0000675.. ======================================================================
676
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000677.. _pep-3101:
678
679PEP 3101: Advanced String Formatting
680=====================================================
681
Benjamin Petersonc3cb6832008-05-26 12:29:46 +0000682In Python 3.0, the `%` operator is supplemented by a more powerful string
683formatting method, :meth:`format`. Support for the :meth:`str.format` method
684has been backported to Python 2.6.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000685
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000686In 2.6, both 8-bit and Unicode strings have a `.format()` method that
687treats the string as a template and takes the arguments to be formatted.
688The formatting template uses curly brackets (`{`, `}`) as special characters::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000689
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000690 # Substitute positional argument 0 into the string.
691 "User ID: {0}".format("root") -> "User ID: root"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000692
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000693 # Use the named keyword arguments
694 uid = 'root'
Georg Brandle152a772008-05-24 18:31:28 +0000695
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000696 'User ID: {uid} Last seen: {last_login}'.format(uid='root',
697 last_login = '5 Mar 2008 07:20') ->
698 'User ID: root Last seen: 5 Mar 2008 07:20'
699
700Curly brackets can be escaped by doubling them::
701
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000702 format("Empty dict: {{}}") -> "Empty dict: {}"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000703
Georg Brandle152a772008-05-24 18:31:28 +0000704Field names can be integers indicating positional arguments, such as
705``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000706supply compound field names that read attributes or access dictionary keys::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000707
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000708 import sys
709 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) ->
710 'Platform: darwin\n
711 Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) \n
712 [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
713
714 import mimetypes
715 'Content-type: {0[.mp4]}'.format(mimetypes.types_map) ->
716 'Content-type: video/mp4'
717
718Note that when using dictionary-style notation such as ``[.mp4]``, you
719don't need to put any quotation marks around the string; it will look
720up the value using ``.mp4`` as the key. Strings beginning with a
721number will be converted to an integer. You can't write more
722complicated expressions inside a format string.
723
724So far we've shown how to specify which field to substitute into the
725resulting string. The precise formatting used is also controllable by
Georg Brandl859043c2008-03-21 17:19:29 +0000726adding a colon followed by a format specifier. For example::
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000727
728 # Field 0: left justify, pad to 15 characters
729 # Field 1: right justify, pad to 6 characters
730 fmt = '{0:15} ${1:>6}'
731 fmt.format('Registration', 35) ->
732 'Registration $ 35'
733 fmt.format('Tutorial', 50) ->
734 'Tutorial $ 50'
735 fmt.format('Banquet', 125) ->
736 'Banquet $ 125'
737
Georg Brandl859043c2008-03-21 17:19:29 +0000738Format specifiers can reference other fields through nesting::
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000739
740 fmt = '{0:{1}}'
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000741 fmt.format('Invoice #1234', 15) ->
742 'Invoice #1234 '
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000743 width = 35
744 fmt.format('Invoice #1234', width) ->
745 'Invoice #1234 '
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000746
747The alignment of a field within the desired width can be specified:
748
749================ ============================================
750Character Effect
751================ ============================================
752< (default) Left-align
753> Right-align
754^ Center
755= (For numeric types only) Pad after the sign.
756================ ============================================
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000757
Georg Brandle152a772008-05-24 18:31:28 +0000758Format specifiers can also include a presentation type, which
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000759controls how the value is formatted. For example, floating-point numbers
760can be formatted as a general number or in exponential notation:
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000761
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000762 >>> '{0:g}'.format(3.75)
763 '3.75'
764 >>> '{0:e}'.format(3.75)
765 '3.750000e+00'
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000766
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000767A variety of presentation types are available. Consult the 2.6
Georg Brandle321c2f2008-05-12 16:45:43 +0000768documentation for a :ref:`complete list <formatstrings>`; here's a sample::
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000769
770 'b' - Binary. Outputs the number in base 2.
771 'c' - Character. Converts the integer to the corresponding
772 Unicode character before printing.
773 'd' - Decimal Integer. Outputs the number in base 10.
774 'o' - Octal format. Outputs the number in base 8.
775 'x' - Hex format. Outputs the number in base 16, using lower-
776 case letters for the digits above 9.
777 'e' - Exponent notation. Prints the number in scientific
778 notation using the letter 'e' to indicate the exponent.
779 'g' - General format. This prints the number as a fixed-point
780 number, unless the number is too large, in which case
781 it switches to 'e' exponent notation.
Eric Smith103f19d2008-05-12 14:00:01 +0000782 'n' - Number. This is the same as 'g' (for floats) or 'd' (for
783 integers), except that it uses the current locale setting to
784 insert the appropriate number separator characters.
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000785 '%' - Percentage. Multiplies the number by 100 and displays
786 in fixed ('f') format, followed by a percent sign.
787
788Classes and types can define a __format__ method to control how they're
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000789formatted. It receives a single argument, the format specifier::
790
791 def __format__(self, format_spec):
792 if isinstance(format_spec, unicode):
793 return unicode(str(self))
794 else:
795 return str(self)
796
797There's also a format() built-in that will format a single value. It calls
798the type's :meth:`__format__` method with the provided specifier::
799
800 >>> format(75.6564, '.2f')
801 '75.66'
802
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +0000803
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000804.. seealso::
805
Benjamin Petersonc3cb6832008-05-26 12:29:46 +0000806 :ref:`formatstrings`
807 The reference format fields.
808
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000809 :pep:`3101` - Advanced String Formatting
Benjamin Petersonc3cb6832008-05-26 12:29:46 +0000810 PEP written by Talin. Implemented by Eric Smith.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000811
812.. ======================================================================
813
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000814.. _pep-3105:
815
816PEP 3105: ``print`` As a Function
817=====================================================
818
819The ``print`` statement becomes the :func:`print` function in Python 3.0.
Georg Brandle152a772008-05-24 18:31:28 +0000820Making :func:`print` a function makes it easier to change
821by doing 'def print(...)' or importing a new function from somewhere else.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000822
Georg Brandle152a772008-05-24 18:31:28 +0000823Python 2.6 has a ``__future__`` import that removes ``print`` as language
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000824syntax, letting you use the functional form instead. For example::
825
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000826 from __future__ import print_function
827 print('# of entries', len(dictionary), file=sys.stderr)
828
829The signature of the new function is::
830
831 def print(*args, sep=' ', end='\n', file=None)
832
833The parameters are:
834
835 * **args**: positional arguments whose values will be printed out.
836 * **sep**: the separator, which will be printed between arguments.
Georg Brandle152a772008-05-24 18:31:28 +0000837 * **end**: the ending text, which will be printed after all of the
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000838 arguments have been output.
839 * **file**: the file object to which the output will be sent.
840
841.. seealso::
842
Eric Smith33dd0942008-03-20 23:04:04 +0000843 :pep:`3105` - Make print a function
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000844 PEP written by Georg Brandl.
845
846.. ======================================================================
847
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000848.. _pep-3110:
849
850PEP 3110: Exception-Handling Changes
851=====================================================
852
Georg Brandle152a772008-05-24 18:31:28 +0000853One error that Python programmers occasionally make
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000854is the following::
855
856 try:
857 ...
858 except TypeError, ValueError:
859 ...
860
Georg Brandle152a772008-05-24 18:31:28 +0000861The author is probably trying to catch both
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000862:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
Georg Brandle152a772008-05-24 18:31:28 +0000863actually does something different: it will catch
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000864:exc:`TypeError` and bind the resulting exception object
Georg Brandle152a772008-05-24 18:31:28 +0000865to the local name ``"ValueError"``. The correct code
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000866would have specified a tuple::
867
868 try:
869 ...
870 except (TypeError, ValueError):
871 ...
872
873This error is possible because the use of the comma here is ambiguous:
874does it indicate two different nodes in the parse tree, or a single
875node that's a tuple.
876
877Python 3.0 changes the syntax to make this unambiguous by replacing
Georg Brandle152a772008-05-24 18:31:28 +0000878the comma with the word "as". To catch an exception and store the
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000879exception object in the variable ``exc``, you must write::
880
881 try:
882 ...
883 except TypeError as exc:
884 ...
885
886Python 3.0 will only support the use of "as", and therefore interprets
887the first example as catching two different exceptions. Python 2.6
888supports both the comma and "as", so existing code will continue to
889work.
890
891.. seealso::
892
893 :pep:`3110` - Catching Exceptions in Python 3000
894 PEP written and implemented by Collin Winter.
895
Georg Brandlb19be572007-12-29 10:57:00 +0000896.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000897
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000898.. _pep-3112:
899
900PEP 3112: Byte Literals
901=====================================================
902
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +0000903Python 3.0 adopts Unicode as the language's fundamental string type and
Georg Brandle152a772008-05-24 18:31:28 +0000904denotes 8-bit literals differently, either as ``b'string'``
905or using a :class:`bytes` constructor. For future compatibility,
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000906Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
907and it also supports the ``b''`` notation.
908
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +0000909There's also a ``__future__`` import that causes all string literals
Georg Brandle152a772008-05-24 18:31:28 +0000910to become Unicode strings. This means that ``\u`` escape sequences
Benjamin Peterson83343302008-05-04 03:05:49 +0000911can be used to include Unicode characters::
912
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +0000913
Andrew M. Kuchlingda950eb2008-04-13 22:39:12 +0000914 from __future__ import unicode_literals
915
916 s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
917 '\u3081\u3000\u751f\u305f\u307e\u3054')
918
919 print len(s) # 12 Unicode characters
920
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +0000921At the C level, Python 3.0 will rename the existing 8-bit
922string type, called :ctype:`PyStringObject` in Python 2.x,
923to :ctype:`PyBytesObject`. Python 2.6 uses ``#define``
924to support using the names :cfunc:`PyBytesObject`,
925:cfunc:`PyBytes_Check`, :cfunc:`PyBytes_FromStringAndSize`,
926and all the other functions and macros used with strings.
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +0000927
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +0000928Instances of the :class:`bytes` type are immutable just
929as strings are. A new :class:`bytearray` type stores a mutable
930sequence of bytes::
931
932 >>> bytearray([65, 66, 67])
933 bytearray(b'ABC')
934 >>> b = bytearray(u'\u21ef\u3244', 'utf-8')
935 >>> b
936 bytearray(b'\xe2\x87\xaf \xe3\x89\x84')
937 >>> b[0] = '\xe3'
938 >>> b
939 bytearray(b'\xe3\x87\xaf \xe3\x89\x84')
940 >>> unicode(str(b), 'utf-8')
941 u'\u31ef \u3244'
942
943Byte arrays support most of the methods of string types, such as
944:meth:`startswith`/:meth:`endswith`, :meth:`find`/:meth:`rfind`,
945and some of the methods of lists, such as :meth:`append`,
946:meth:`pop`, and :meth:`reverse`.
947
948 >>> b = bytearray('ABC')
949 >>> b.append('d')
950 >>> b.append(ord('e'))
951 >>> b
952 bytearray(b'ABCde')
Benjamin Peterson83343302008-05-04 03:05:49 +0000953
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000954.. seealso::
955
956 :pep:`3112` - Bytes literals in Python 3000
957 PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
958
959.. ======================================================================
960
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000961.. _pep-3116:
962
963PEP 3116: New I/O Library
964=====================================================
965
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +0000966Python's built-in file objects support a number of methods, but
967file-like objects don't necessarily support all of them. Objects that
968imitate files usually support :meth:`read` and :meth:`write`, but they
969may not support :meth:`readline`. Python 3.0 introduces a layered I/O
970library in the :mod:`io` module that separates buffering and
971text-handling features from the fundamental read and write operations.
972
973There are three levels of abstract base classes provided by
974the :mod:`io` module:
975
976* :class:`RawIOBase`: defines raw I/O operations: :meth:`read`,
Georg Brandle152a772008-05-24 18:31:28 +0000977 :meth:`readinto`,
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +0000978 :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
979 and :meth:`close`.
980 Most of the methods of this class will often map to a single system call.
981 There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable`
982 methods for determining what operations a given object will allow.
983
984 Python 3.0 has concrete implementations of this class for files and
985 sockets, but Python 2.6 hasn't restructured its file and socket objects
986 in this way.
987
988 .. XXX should 2.6 register them in io.py?
989
Georg Brandle152a772008-05-24 18:31:28 +0000990* :class:`BufferedIOBase`: is an abstract base class that
991 buffers data in memory to reduce the number of
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +0000992 system calls used, making I/O processing more efficient.
Georg Brandle152a772008-05-24 18:31:28 +0000993 It supports all of the methods of :class:`RawIOBase`,
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +0000994 and adds a :attr:`raw` attribute holding the underlying raw object.
995
996 There are four concrete classes implementing this ABC:
Georg Brandle152a772008-05-24 18:31:28 +0000997 :class:`BufferedWriter` and
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +0000998 :class:`BufferedReader` for objects that only support
999 writing or reading and don't support random access,
1000 :class:`BufferedRandom` for objects that support the :meth:`seek` method
1001 for random access,
Georg Brandle152a772008-05-24 18:31:28 +00001002 and :class:`BufferedRWPair` for objects such as TTYs that have
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00001003 both read and write operations that act upon unconnected streams of data.
1004
1005* :class:`TextIOBase`: Provides functions for reading and writing
1006 strings (remember, strings will be Unicode in Python 3.0),
Georg Brandle152a772008-05-24 18:31:28 +00001007 and supporting universal newlines. :class:`TextIOBase` defines
1008 the :meth:`readline` method and supports iteration upon
1009 objects.
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00001010
1011 There are two concrete implementations. :class:`TextIOWrapper`
1012 wraps a buffered I/O object, supporting all of the methods for
Georg Brandle152a772008-05-24 18:31:28 +00001013 text I/O and adding a :attr:`buffer` attribute for access
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00001014 to the underlying object. :class:`StringIO` simply buffers
1015 everything in memory without ever writing anything to disk.
1016
1017 (In current 2.6 alpha releases, :class:`io.StringIO` is implemented in
Georg Brandle152a772008-05-24 18:31:28 +00001018 pure Python, so it's pretty slow. You should therefore stick with the
1019 existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00001020 point Python 3.0's :mod:`io` module will be rewritten into C for speed,
1021 and perhaps the C implementation will be backported to the 2.x releases.)
1022
1023 .. XXX check before final release: is io.py still written in Python?
1024
1025In Python 2.6, the underlying implementations haven't been
1026restructured to build on top of the :mod:`io` module's classes. The
Georg Brandle152a772008-05-24 18:31:28 +00001027module is being provided to make it easier to write code that's
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00001028forward-compatible with 3.0, and to save developers the effort of writing
1029their own implementations of buffering and text I/O.
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001030
1031.. seealso::
1032
1033 :pep:`3116` - New I/O
1034 PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
Andrew M. Kuchling04f58762008-04-15 02:24:15 +00001035 Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
1036 Jeremy Hylton, Martin von Loewis, Tony Lownds, and others.
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001037
1038.. ======================================================================
1039
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001040.. _pep-3118:
1041
1042PEP 3118: Revised Buffer Protocol
1043=====================================================
1044
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001045The buffer protocol is a C-level API that lets Python types
Georg Brandle152a772008-05-24 18:31:28 +00001046exchange pointers into their internal representations. A
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001047memory-mapped file can be viewed as a buffer of characters, for
1048example, and this lets another module such as :mod:`re`
1049treat memory-mapped files as a string of characters to be searched.
1050
1051The primary users of the buffer protocol are numeric-processing
1052packages such as NumPy, which can expose the internal representation
1053of arrays so that callers can write data directly into an array instead
Georg Brandle152a772008-05-24 18:31:28 +00001054of going through a slower API. This PEP updates the buffer protocol in light of experience
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001055from NumPy development, adding a number of new features
Georg Brandle152a772008-05-24 18:31:28 +00001056such as indicating the shape of an array,
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001057locking memory .
1058
Georg Brandle152a772008-05-24 18:31:28 +00001059The most important new C API function is
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001060``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which
1061takes an object and a set of flags, and fills in the
Georg Brandle152a772008-05-24 18:31:28 +00001062``Py_buffer`` structure with information
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001063about the object's memory representation. Objects
Georg Brandle152a772008-05-24 18:31:28 +00001064can use this operation to lock memory in place
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001065while an external caller could be modifying the contents,
Georg Brandle152a772008-05-24 18:31:28 +00001066so there's a corresponding
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001067``PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)`` to
1068indicate that the external caller is done.
1069
1070The **flags** argument to :cfunc:`PyObject_GetBuffer` specifies
1071constraints upon the memory returned. Some examples are:
1072
1073 * :const:`PyBUF_WRITABLE` indicates that the memory must be writable.
Georg Brandle152a772008-05-24 18:31:28 +00001074
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001075 * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory.
1076
1077 * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS`
1078 requests a C-contiguous (last dimension varies the fastest) or
1079 Fortran-contiguous (first dimension varies the fastest) layout.
1080
1081.. XXX this feature is not in 2.6 docs yet
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001082
1083.. seealso::
1084
1085 :pep:`3118` - Revising the buffer protocol
Andrew M. Kuchling217057f2008-04-05 15:57:46 +00001086 PEP written by Travis Oliphant and Carl Banks; implemented by
1087 Travis Oliphant.
Georg Brandle152a772008-05-24 18:31:28 +00001088
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001089
1090.. ======================================================================
1091
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001092.. _pep-3119:
1093
1094PEP 3119: Abstract Base Classes
1095=====================================================
1096
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001097Some object-oriented languages such as Java support interfaces: declarations
1098that a class has a given set of methods or supports a given access protocol.
1099Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC
Georg Brandle152a772008-05-24 18:31:28 +00001100support consists of an :mod:`abc` module containing a metaclass called
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001101:class:`ABCMeta`, special handling
1102of this metaclass by the :func:`isinstance` and :func:`issubclass` built-ins,
1103and a collection of basic ABCs that the Python developers think will be widely
1104useful.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001105
Georg Brandle152a772008-05-24 18:31:28 +00001106Let's say you have a particular class and wish to know whether it supports
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001107dictionary-style access. The phrase "dictionary-style" is vague, however.
Georg Brandle152a772008-05-24 18:31:28 +00001108It probably means that accessing items with ``obj[1]`` works.
1109Does it imply that setting items with ``obj[2] = value`` works?
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001110Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items`
1111methods? What about the iterative variants such as :meth:`iterkeys`? :meth:`copy`
1112and :meth:`update`? Iterating over the object with :func:`iter`?
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001113
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001114Python 2.6 includes a number of different ABCs in the :mod:`collections`
1115module. :class:`Iterable` indicates that a class defines :meth:`__iter__`,
1116and :class:`Container` means the class supports ``x in y`` expressions
1117by defining a :meth:`__contains__` method. The basic dictionary interface of
Georg Brandle152a772008-05-24 18:31:28 +00001118getting items, setting items, and
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001119:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
1120:class:`MutableMapping` ABC.
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001121
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001122You can derive your own classes from a particular ABC
1123to indicate they support that ABC's interface::
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001124
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001125 import collections
Georg Brandle152a772008-05-24 18:31:28 +00001126
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001127 class Storage(collections.MutableMapping):
1128 ...
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001129
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001130
Georg Brandle152a772008-05-24 18:31:28 +00001131Alternatively, you could write the class without deriving from
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001132the desired ABC and instead register the class by
1133calling the ABC's :meth:`register` method::
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001134
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001135 import collections
Georg Brandle152a772008-05-24 18:31:28 +00001136
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001137 class Storage:
1138 ...
Georg Brandle152a772008-05-24 18:31:28 +00001139
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001140 collections.MutableMapping.register(Storage)
Georg Brandle152a772008-05-24 18:31:28 +00001141
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001142For classes that you write, deriving from the ABC is probably clearer.
1143The :meth:`register` method is useful when you've written a new
1144ABC that can describe an existing type or class, or if you want
1145to declare that some third-party class implements an ABC.
1146For example, if you defined a :class:`PrintableType` ABC,
1147it's legal to do:
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001148
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001149 # Register Python's types
1150 PrintableType.register(int)
1151 PrintableType.register(float)
1152 PrintableType.register(str)
1153
Georg Brandle152a772008-05-24 18:31:28 +00001154Classes should obey the semantics specified by an ABC, but
1155Python can't check this; it's up to the class author to
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001156understand the ABC's requirements and to implement the code accordingly.
1157
1158To check whether an object supports a particular interface, you can
1159now write::
1160
1161 def func(d):
1162 if not isinstance(d, collections.MutableMapping):
Georg Brandle152a772008-05-24 18:31:28 +00001163 raise ValueError("Mapping object expected, not %r" % d)
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001164
Georg Brandle152a772008-05-24 18:31:28 +00001165(Don't feel that you must now begin writing lots of checks as in the
1166above example. Python has a strong tradition of duck-typing, where
1167explicit type-checking isn't done and code simply calls methods on
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001168an object, trusting that those methods will be there and raising an
1169exception if they aren't. Be judicious in checking for ABCs
1170and only do it where it helps.)
1171
1172You can write your own ABCs by using ``abc.ABCMeta`` as the
1173metaclass in a class definition::
1174
1175 from abc import ABCMeta
1176
1177 class Drawable():
1178 __metaclass__ = ABCMeta
Georg Brandle152a772008-05-24 18:31:28 +00001179
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001180 def draw(self, x, y, scale=1.0):
1181 pass
1182
1183 def draw_doubled(self, x, y):
1184 self.draw(x, y, scale=2.0)
1185
Georg Brandle152a772008-05-24 18:31:28 +00001186
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001187 class Square(Drawable):
1188 def draw(self, x, y, scale):
1189 ...
1190
Georg Brandle152a772008-05-24 18:31:28 +00001191
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001192In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
1193renders the object at twice its size and can be implemented in terms
1194of other methods described in :class:`Drawable`. Classes implementing
Georg Brandle152a772008-05-24 18:31:28 +00001195this ABC therefore don't need to provide their own implementation
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001196of :meth:`draw_doubled`, though they can do so. An implementation
Georg Brandle152a772008-05-24 18:31:28 +00001197of :meth:`draw` is necessary, though; the ABC can't provide
1198a useful generic implementation. You
1199can apply the ``@abstractmethod`` decorator to methods such as
1200:meth:`draw` that must be implemented; Python will
1201then raise an exception for classes that
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001202don't define the method::
1203
1204 class Drawable():
1205 __metaclass__ = ABCMeta
Georg Brandle152a772008-05-24 18:31:28 +00001206
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001207 @abstractmethod
1208 def draw(self, x, y, scale):
1209 pass
1210
Georg Brandle152a772008-05-24 18:31:28 +00001211Note that the exception is only raised when you actually
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001212try to create an instance of a subclass without the method::
1213
1214 >>> s=Square()
1215 Traceback (most recent call last):
1216 File "<stdin>", line 1, in <module>
1217 TypeError: Can't instantiate abstract class Square with abstract methods draw
Georg Brandle152a772008-05-24 18:31:28 +00001218 >>>
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001219
1220Abstract data attributes can be declared using the ``@abstractproperty`` decorator::
1221
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001222 @abstractproperty
1223 def readonly(self):
1224 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001225
Georg Brandle152a772008-05-24 18:31:28 +00001226Subclasses must then define a :meth:`readonly` property
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001227
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001228.. seealso::
1229
1230 :pep:`3119` - Introducing Abstract Base Classes
1231 PEP written by Guido van Rossum and Talin.
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001232 Implemented by Guido van Rossum.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001233 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001234
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001235.. ======================================================================
1236
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001237.. _pep-3127:
1238
1239PEP 3127: Integer Literal Support and Syntax
1240=====================================================
1241
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001242Python 3.0 changes the syntax for octal (base-8) integer literals,
1243which are now prefixed by "0o" or "0O" instead of a leading zero, and
1244adds support for binary (base-2) integer literals, signalled by a "0b"
1245or "0B" prefix.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001246
Georg Brandle152a772008-05-24 18:31:28 +00001247Python 2.6 doesn't drop support for a leading 0 signalling
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001248an octal number, but it does add support for "0o" and "0b"::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001249
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001250 >>> 0o21, 2*8 + 1
1251 (17, 17)
1252 >>> 0b101111
1253 47
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001254
Georg Brandle152a772008-05-24 18:31:28 +00001255The :func:`oct` built-in still returns numbers
1256prefixed with a leading zero, and a new :func:`bin`
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001257built-in returns the binary representation for a number::
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001258
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001259 >>> oct(42)
1260 '052'
1261 >>> bin(173)
1262 '0b10101101'
1263
1264The :func:`int` and :func:`long` built-ins will now accept the "0o"
1265and "0b" prefixes when base-8 or base-2 are requested, or when the
1266**base** argument is zero (meaning the base used is determined from
1267the string):
1268
1269 >>> int ('0o52', 0)
1270 42
1271 >>> int('1101', 2)
1272 13
1273 >>> int('0b1101', 2)
1274 13
1275 >>> int('0b1101', 0)
1276 13
1277
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001278
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001279.. seealso::
1280
1281 :pep:`3127` - Integer Literal Support and Syntax
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001282 PEP written by Patrick Maupin; backported to 2.6 by
1283 Eric Smith.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001284
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001285.. ======================================================================
1286
1287.. _pep-3129:
1288
1289PEP 3129: Class Decorators
1290=====================================================
1291
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001292Decorators have been extended from functions to classes. It's now legal to
1293write::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001294
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001295 @foo
1296 @bar
1297 class A:
1298 pass
1299
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001300This is equivalent to::
1301
1302 class A:
1303 pass
1304
1305 A = foo(bar(A))
1306
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001307.. seealso::
1308
1309 :pep:`3129` - Class Decorators
1310 PEP written by Collin Winter.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001311
1312.. ======================================================================
1313
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001314.. _pep-3141:
1315
1316PEP 3141: A Type Hierarchy for Numbers
1317=====================================================
1318
1319In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001320inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001321This change was backported to 2.6 as the :mod:`numbers` module.
1322
1323The most general ABC is :class:`Number`. It defines no operations at
1324all, and only exists to allow checking if an object is a number by
1325doing ``isinstance(obj, Number)``.
1326
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001327:class:`Complex` is a subclass of :class:`Number`. Complex numbers
1328can undergo the basic operations of addition, subtraction,
1329multiplication, division, and exponentiation, and you can retrieve the
Georg Brandle152a772008-05-24 18:31:28 +00001330real and imaginary parts and obtain a number's conjugate. Python's built-in
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001331complex type is an implementation of :class:`Complex`.
1332
Georg Brandle152a772008-05-24 18:31:28 +00001333:class:`Real` further derives from :class:`Complex`, and adds
1334operations that only work on real numbers: :func:`floor`, :func:`trunc`,
1335rounding, taking the remainder mod N, floor division,
1336and comparisons.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001337
1338:class:`Rational` numbers derive from :class:`Real`, have
1339:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +00001340converted to floats. Python 2.6 adds a simple rational-number class,
Georg Brandle152a772008-05-24 18:31:28 +00001341:class:`Fraction`, in the :mod:`fractions` module. (It's called
1342:class:`Fraction` instead of :class:`Rational` to avoid
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001343a name clash with :class:`numbers.Rational`.)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001344
1345:class:`Integral` numbers derive from :class:`Rational`, and
Georg Brandle152a772008-05-24 18:31:28 +00001346can be shifted left and right with ``<<`` and ``>>``,
1347combined using bitwise operations such as ``&`` and ``|``,
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001348and can be used as array indexes and slice boundaries.
1349
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001350In Python 3.0, the PEP slightly redefines the existing built-ins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001351:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
Georg Brandle152a772008-05-24 18:31:28 +00001352one, :func:`math.trunc`, that's been backported to Python 2.6.
1353:func:`math.trunc` rounds toward zero, returning the closest
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001354:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001355
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001356.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001357
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001358 :pep:`3141` - A Type Hierarchy for Numbers
1359 PEP written by Jeffrey Yasskin.
1360
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001361 `Scheme's numerical tower <http://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001362
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001363 `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
Georg Brandle152a772008-05-24 18:31:28 +00001364
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001365
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001366The :mod:`fractions` Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001367--------------------------------------------------
1368
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001369To fill out the hierarchy of numeric types, a rational-number class is
1370provided by the :mod:`fractions` module. Rational numbers store their
1371values as a numerator and denominator forming a fraction, and can
1372exactly represent numbers such as ``2/3`` that floating-point numbers
1373can only approximate.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001374
Mark Dickinsond058cd22008-02-10 21:29:51 +00001375The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001376that will be the numerator and denominator of the resulting fraction. ::
1377
Mark Dickinsond058cd22008-02-10 21:29:51 +00001378 >>> from fractions import Fraction
1379 >>> a = Fraction(2, 3)
1380 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001381 >>> float(a), float(b)
1382 (0.66666666666666663, 0.40000000000000002)
1383 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +00001384 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001385 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +00001386 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001387
Georg Brandle152a772008-05-24 18:31:28 +00001388To help in converting floating-point numbers to rationals,
1389the float type now has a :meth:`as_integer_ratio()` method that returns
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001390the numerator and denominator for a fraction that evaluates to the same
1391floating-point value::
1392
1393 >>> (2.5) .as_integer_ratio()
1394 (5, 2)
1395 >>> (3.1415) .as_integer_ratio()
1396 (7074029114692207L, 2251799813685248L)
1397 >>> (1./3) .as_integer_ratio()
1398 (6004799503160661L, 18014398509481984L)
1399
1400Note that values that can only be approximated by floating-point
1401numbers, such as 1./3, are not simplified to the number being
1402approximated; the fraction attempts to match the floating-point value
1403**exactly**.
1404
Mark Dickinsond058cd22008-02-10 21:29:51 +00001405The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001406Mullender that was in Python's :file:`Demo/classes/` directory for a
1407long time. This implementation was significantly updated by Jeffrey
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001408Yasskin.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001409
Brett Cannon4b964f92008-05-05 20:21:38 +00001410
Georg Brandl8ec7f652007-08-15 14:28:01 +00001411Other Language Changes
1412======================
1413
1414Here are all of the changes that Python 2.6 makes to the core Python language.
1415
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +00001416* The :func:`hasattr` function was catching and ignoring all errors,
Benjamin Peterson77cec6e2008-06-28 13:18:14 +00001417 under the assumption that they meant a :meth:`__getattr__` method
1418 was failing somewhere and the return value of :func:`hasattr` would
1419 therefore be ``False``. This logic shouldn't be applied to
1420 :exc:`KeyboardInterrupt` and :exc:`SystemExit`, however; Python 2.6
1421 will no longer discard such exceptions when :func:`hasattr`
1422 encounters them. (Fixed by Benjamin Peterson; :issue:`2196`.)
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +00001423
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001424* When calling a function using the ``**`` syntax to provide keyword
1425 arguments, you are no longer required to use a Python dictionary;
1426 any mapping will now work::
1427
1428 >>> def f(**kw):
1429 ... print sorted(kw)
Georg Brandle152a772008-05-24 18:31:28 +00001430 ...
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001431 >>> ud=UserDict.UserDict()
1432 >>> ud['a'] = 1
1433 >>> ud['b'] = 'string'
1434 >>> f(**ud)
1435 ['a', 'b']
1436
Andrew M. Kuchlingc157c9c2008-04-09 22:28:43 +00001437 (Contributed by Alexander Belopolsky; :issue:`1686487`.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001438
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00001439* A new built-in, ``next(*iterator*, [*default*])`` returns the next item
1440 from the specified iterator. If the *default* argument is supplied,
1441 it will be returned if *iterator* has been exhausted; otherwise,
1442 the :exc:`StopIteration` exception will be raised. (:issue:`2719`)
1443
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001444* Tuples now have an :meth:`index` method matching the list type's
1445 :meth:`index` method::
1446
1447 >>> t = (0,1,2,3,4)
1448 >>> t.index(3)
1449 3
1450
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001451* The built-in types now have improved support for extended slicing syntax,
1452 where various combinations of ``(start, stop, step)`` are supplied.
1453 Previously, the support was partial and certain corner cases wouldn't work.
1454 (Implemented by Thomas Wouters.)
1455
Georg Brandlb19be572007-12-29 10:57:00 +00001456 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001457
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001458* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001459 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Georg Brandle152a772008-05-24 18:31:28 +00001460 adding or modifying a getter, setter or deleter function to an
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001461 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001462
1463 class C(object):
Georg Brandle152a772008-05-24 18:31:28 +00001464 @property
1465 def x(self):
1466 return self._x
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001467
Georg Brandle152a772008-05-24 18:31:28 +00001468 @x.setter
1469 def x(self, value):
1470 self._x = value
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001471
Georg Brandle152a772008-05-24 18:31:28 +00001472 @x.deleter
1473 def x(self):
1474 del self._x
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001475
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001476 class D(C):
1477 @C.x.getter
1478 def x(self):
1479 return self._x * 2
1480
1481 @x.setter
1482 def x(self, value):
1483 self._x = value / 2
1484
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001485* Several methods of the built-in set types now accept multiple iterables:
1486 :meth:`intersection`,
1487 :meth:`intersection_update`,
1488 :meth:`union`, :meth:`update`,
1489 :meth:`difference` and :meth:`difference_update`.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001490
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001491 ::
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001492
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001493 >>> s=set('1234567890')
1494 >>> s.intersection('abc123', 'cdf246') # Intersection between all inputs
1495 set(['2'])
1496 >>> s.difference('246', '789')
1497 set(['1', '0', '3', '5'])
1498
1499 (Contributed by Raymond Hettinger.)
1500
1501* A numerical nicety: when creating a complex number from two floats
Georg Brandle152a772008-05-24 18:31:28 +00001502 on systems that support signed zeros (-0 and +0), the
1503 :func:`complex` constructor will now preserve the sign
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001504 of the zero. (Fixed by Mark T. Dickinson; :issue:`1507`)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001505
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001506* More floating-point features were also added. The :func:`float` function
Mark Dickinsonc72b7872008-06-24 11:08:58 +00001507 will now turn the string ``nan`` into an
1508 IEEE 754 Not A Number value, and ``+inf`` and ``-inf`` into
Georg Brandle152a772008-05-24 18:31:28 +00001509 positive or negative infinity. This works on any platform with
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001510 IEEE 754 semantics. (Contributed by Christian Heimes; :issue:`1635`.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001511
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001512 Other functions in the :mod:`math` module, :func:`isinf` and
1513 :func:`isnan`, return true if their floating-point argument is
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001514 infinite or Not A Number. (:issue:`1640`)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001515
Mark Dickinson7103aa42008-07-15 19:08:33 +00001516 The float type has a new instance method :meth:`float.hex` and a
1517 corresponding new class method :meth:`float.fromhex` to convert
1518 floating-point numbers to and from hexadecimal strings,
1519 respectively. (:issue:`3008`)
1520
Mark Dickinsond3035782008-06-20 15:17:41 +00001521* The :mod:`math` module has a number of new functions, and the existing
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001522 functions have been improved to give more consistent behaviour
1523 across platforms, especially with respect to handling of
1524 floating-point exceptions and IEEE 754 special values.
Georg Brandle152a772008-05-24 18:31:28 +00001525 The new functions are:
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001526
Georg Brandlf91c70a2008-06-20 19:28:18 +00001527 * :func:`~math.isinf` and :func:`~math.isnan` determine whether a given float
1528 is a (positive or negative) infinity or a NaN (Not a Number), respectively.
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001529
Georg Brandlf91c70a2008-06-20 19:28:18 +00001530 * :func:`~math.copysign` copies the sign bit of an IEEE 754 number,
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001531 returning the absolute value of *x* combined with the sign bit of
1532 *y*. For example, ``math.copysign(1, -0.0)`` returns -1.0.
1533 (Contributed by Christian Heimes.)
1534
Georg Brandlf91c70a2008-06-20 19:28:18 +00001535 * :func:`~math.factorial` computes the factorial of a number.
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001536 (Contributed by Raymond Hettinger; :issue:`2138`.)
1537
Georg Brandlf91c70a2008-06-20 19:28:18 +00001538 * :func:`~math.sum` adds up the stream of numbers from an iterable,
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001539 and is careful to avoid loss of precision by calculating partial sums.
1540 (Contributed by Jean Brouwers; :issue:`2819`.)
1541
Georg Brandlf91c70a2008-06-20 19:28:18 +00001542 * The inverse hyperbolic functions :func:`~math.acosh`, :func:`~math.asinh`
1543 and :func:`~math.atanh`.
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001544
Georg Brandlf91c70a2008-06-20 19:28:18 +00001545 * The function :func:`~math.log1p`, returning the natural logarithm of *1+x*
1546 (base *e*).
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001547
Georg Brandlf91c70a2008-06-20 19:28:18 +00001548 There's also a new :func:`trunc` built-in function as a result of the
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001549 backport of `PEP 3141's type hierarchy for numbers <#pep-3141>`__.
1550
1551 The existing math functions have been modified to follow the
1552 recommendations of the C99 standard with respect to special values
1553 whenever possible. For example, ``sqrt(-1.)`` should now give a
1554 :exc:`ValueError` across (nearly) all platforms, while
1555 ``sqrt(float('NaN'))`` should return a NaN on all IEEE 754
1556 platforms. Where Annex 'F' of the C99 standard recommends signaling
1557 'divide-by-zero' or 'invalid', Python will raise :exc:`ValueError`.
1558 Where Annex 'F' of the C99 standard recommends signaling 'overflow',
1559 Python will raise :exc:`OverflowError`. (See :issue:`711019`,
1560 :issue:`1640`.)
1561
1562 (Contributed by Christian Heimes and Mark Dickinson.)
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001563
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001564* Changes to the :class:`Exception` interface
Georg Brandle152a772008-05-24 18:31:28 +00001565 as dictated by :pep:`352` continue to be made. For 2.6,
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001566 the :attr:`message` attribute is being deprecated in favor of the
1567 :attr:`args` attribute.
1568
Georg Brandle152a772008-05-24 18:31:28 +00001569* The :exc:`GeneratorExit` exception now subclasses
1570 :exc:`BaseException` instead of :exc:`Exception`. This means
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001571 that an exception handler that does ``except Exception:``
Georg Brandle152a772008-05-24 18:31:28 +00001572 will not inadvertently catch :exc:`GeneratorExit`.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001573 (Contributed by Chad Austin; :issue:`1537`.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001574
Georg Brandle152a772008-05-24 18:31:28 +00001575* Generator objects now have a :attr:`gi_code` attribute that refers to
1576 the original code object backing the generator.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001577 (Contributed by Collin Winter; :issue:`1473257`.)
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001578
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001579* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001580 as well as positional parameters. (Contributed by Thomas Wouters;
1581 :issue:`1444529`.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001582
Georg Brandle152a772008-05-24 18:31:28 +00001583* The :func:`complex` constructor now accepts strings containing
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001584 parenthesized complex numbers, letting ``complex(repr(cmplx))``
1585 will now round-trip values. For example, ``complex('(3+4j)')``
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001586 now returns the value (3+4j). (:issue:`1491866`)
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001587
Georg Brandle152a772008-05-24 18:31:28 +00001588* The string :meth:`translate` method now accepts ``None`` as the
1589 translation table parameter, which is treated as the identity
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001590 transformation. This makes it easier to carry out operations
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001591 that only delete characters. (Contributed by Bengt Richter;
1592 :issue:`1193128`.)
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001593
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001594* The built-in :func:`dir` function now checks for a :meth:`__dir__`
1595 method on the objects it receives. This method must return a list
1596 of strings containing the names of valid attributes for the object,
1597 and lets the object control the value that :func:`dir` produces.
Georg Brandle152a772008-05-24 18:31:28 +00001598 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +00001599 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001600 (:issue:`1591665`)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001601
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001602* Instance method objects have new attributes for the object and function
1603 comprising the method; the new synonym for :attr:`im_self` is
1604 :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`.
1605 The old names are still supported in Python 2.6; they're gone in 3.0.
1606
Georg Brandl8ec7f652007-08-15 14:28:01 +00001607* An obscure change: when you use the the :func:`locals` function inside a
1608 :keyword:`class` statement, the resulting dictionary no longer returns free
1609 variables. (Free variables, in this case, are variables referred to in the
1610 :keyword:`class` statement that aren't attributes of the class.)
1611
Georg Brandlb19be572007-12-29 10:57:00 +00001612.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001613
1614
1615Optimizations
1616-------------
1617
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00001618* The :mod:`warnings` module has been rewritten in C. This makes
1619 it possible to invoke warnings from the parser, and may also
1620 make the interpreter's startup faster.
1621 (Contributed by Neal Norwitz and Brett Cannon; :issue:`1631171`.)
1622
Georg Brandlaf30b282008-01-15 06:55:56 +00001623* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001624 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +00001625 for a particular class; once cached, the interpreter doesn't need to
Georg Brandle152a772008-05-24 18:31:28 +00001626 traverse base classes to figure out the right method to call.
1627 The cache is cleared if a base class or the class itself is modified,
1628 so the cache should remain correct even in the face of Python's dynamic
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +00001629 nature.
Georg Brandle152a772008-05-24 18:31:28 +00001630 (Original optimization implemented by Armin Rigo, updated for
1631 Python 2.6 by Kevin Jacobs; :issue:`1700288`.)
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001632
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001633* All of the functions in the :mod:`struct` module have been rewritten in
1634 C, thanks to work at the Need For Speed sprint.
1635 (Contributed by Raymond Hettinger.)
1636
Georg Brandl8ec7f652007-08-15 14:28:01 +00001637* Internally, a bit is now set in type objects to indicate some of the standard
1638 built-in types. This speeds up checking if an object is a subclass of one of
1639 these types. (Contributed by Neal Norwitz.)
1640
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00001641* Unicode strings now use faster code for detecting
Georg Brandle152a772008-05-24 18:31:28 +00001642 whitespace and line breaks; this speeds up the :meth:`split` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001643 by about 25% and :meth:`splitlines` by 35%.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001644 (Contributed by Antoine Pitrou.) Memory usage is reduced
1645 by using pymalloc for the Unicode string's data.
1646
1647* The ``with`` statement now stores the :meth:`__exit__` method on the stack,
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001648 producing a small speedup. (Implemented by Jeffrey Yasskin.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001649
1650* To reduce memory usage, the garbage collector will now clear internal
1651 free lists when garbage-collecting the highest generation of objects.
1652 This may return memory to the OS sooner.
1653
Georg Brandl8ec7f652007-08-15 14:28:01 +00001654The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
1655benchmark around XX% faster than Python 2.5.
1656
Georg Brandlb19be572007-12-29 10:57:00 +00001657.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001658
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001659.. _new-26-interpreter:
Andrew M. Kuchlingc161df62008-04-13 01:05:59 +00001660
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001661Interpreter Changes
Andrew M. Kuchlingc161df62008-04-13 01:05:59 +00001662-------------------------------
1663
1664Two command-line options have been reserved for use by other Python
1665implementations. The :option:`-J` switch has been reserved for use by
1666Jython for Jython-specific options, such as ones that are passed to
1667the underlying JVM. :option:`-X` has been reserved for options
1668specific to a particular implementation of Python such as CPython,
1669Jython, or IronPython. If either option is used with Python 2.6, the
1670interpreter will report that the option isn't currently used.
1671
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00001672It's now possible to prevent Python from writing :file:`.pyc` or
1673:file:`.pyo` files on importing a module by supplying the :option:`-B`
1674switch to the Python interpreter, or by setting the
1675:envvar:`PYTHONDONTWRITEBYTECODE` environment variable before running
1676the interpreter. This setting is available to Python programs as the
1677``sys.dont_write_bytecode`` variable, and can be changed by Python
1678code to modify the interpreter's behaviour. (Contributed by Neal
1679Norwitz and Georg Brandl.)
1680
1681The encoding used for standard input, output, and standard error can
1682be specified by setting the :envvar:`PYTHONIOENCODING` environment
1683variable before running the interpreter. The value should be a string
1684in the form ``**encoding**`` or ``**encoding**:**errorhandler**``.
1685The **encoding** part specifies the encoding's name, e.g. ``utf-8`` or
1686``latin-1``; the optional **errorhandler** part specifies
1687what to do with characters that can't be handled by the encoding,
1688and should be one of "error", "ignore", or "replace". (Contributed
1689by Martin von Loewis.)
1690
Andrew M. Kuchlingc161df62008-04-13 01:05:59 +00001691.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001692
1693New, Improved, and Deprecated Modules
1694=====================================
1695
1696As usual, Python's standard library received a number of enhancements and bug
1697fixes. Here's a partial list of the most notable changes, sorted alphabetically
1698by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
Benjamin Peterson7b5151c2008-05-15 22:41:16 +00001699complete list of changes, or look through the Subversion logs for all the
1700details.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001701
Georg Brandle152a772008-05-24 18:31:28 +00001702* (3.0-warning mode) Python 3.0 will feature a reorganized standard
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001703 library; many outdated modules are being dropped.
Georg Brandle152a772008-05-24 18:31:28 +00001704 Python 2.6 running in 3.0-warning mode will warn about these modules
Andrew M. Kuchling3a1693a2008-05-15 01:10:24 +00001705 when they are imported.
Andrew M. Kuchling09ed01f2008-05-19 03:03:46 +00001706
Andrew M. Kuchling3a1693a2008-05-15 01:10:24 +00001707 The list of deprecated modules is:
Andrew M. Kuchling09ed01f2008-05-19 03:03:46 +00001708 :mod:`audiodev`,
1709 :mod:`bgenlocations`,
1710 :mod:`buildtools`,
1711 :mod:`bundlebuilder`,
1712 :mod:`Canvas`,
1713 :mod:`compiler`,
1714 :mod:`dircache`,
1715 :mod:`dl`,
1716 :mod:`fpformat`,
1717 :mod:`gensuitemodule`,
1718 :mod:`ihooks`,
1719 :mod:`imageop`,
1720 :mod:`imgfile`,
1721 :mod:`linuxaudiodev`,
1722 :mod:`mhlib`,
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001723 :mod:`mimetools`,
Andrew M. Kuchling09ed01f2008-05-19 03:03:46 +00001724 :mod:`multifile`,
1725 :mod:`new`,
1726 :mod:`popen2`,
1727 :mod:`pure`,
1728 :mod:`statvfs`,
1729 :mod:`sunaudiodev`,
1730 :mod:`test.testall`,
1731 :mod:`toaiff`.
1732
Benjamin Peterson36d879b2008-05-19 11:55:54 +00001733 Various MacOS modules have been removed:
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001734 :mod:`_builtinSuites`,
1735 :mod:`aepack`,
1736 :mod:`aetools`,
1737 :mod:`aetypes`,
1738 :mod:`applesingle`,
1739 :mod:`appletrawmain`,
1740 :mod:`appletrunner`,
1741 :mod:`argvemulator`,
1742 :mod:`Audio_mac`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001743 :mod:`autoGIL`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001744 :mod:`Carbon`,
1745 :mod:`cfmfile`,
1746 :mod:`CodeWarrior`,
1747 :mod:`ColorPicker`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001748 :mod:`EasyDialogs`,
1749 :mod:`Explorer`,
1750 :mod:`Finder`,
1751 :mod:`FrameWork`,
1752 :mod:`findertools`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001753 :mod:`ic`,
1754 :mod:`icglue`,
1755 :mod:`icopen`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001756 :mod:`macerrors`,
1757 :mod:`MacOS`,
1758 :mod:`macostools`,
1759 :mod:`macresource`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001760 :mod:`MiniAEFrame`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001761 :mod:`Nav`,
1762 :mod:`Netscape`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001763 :mod:`OSATerminology`,
1764 :mod:`pimp`,
1765 :mod:`PixMapWrapper`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001766 :mod:`StdSuites`,
Benjamin Petersona19f9f92008-05-15 22:34:33 +00001767 :mod:`SystemEvents`,
1768 :mod:`Terminal`,
Andrew M. Kuchling09ed01f2008-05-19 03:03:46 +00001769 :mod:`terminalcommand`.
Andrew M. Kuchlingc72df332008-05-14 00:46:41 +00001770
Andrew M. Kuchling09ed01f2008-05-19 03:03:46 +00001771 A number of old IRIX-specific modules were deprecated:
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00001772 :mod:`al` and :mod:`AL`,
Andrew M. Kuchling09ed01f2008-05-19 03:03:46 +00001773 :mod:`cd`,
1774 :mod:`cddb`,
1775 :mod:`cdplayer`,
1776 :mod:`CL` and :mod:`cl`,
1777 :mod:`DEVICE`,
1778 :mod:`ERRNO`,
1779 :mod:`FILE`,
1780 :mod:`FL` and :mod:`fl`,
1781 :mod:`flp`,
1782 :mod:`fm`,
1783 :mod:`GET`,
1784 :mod:`GLWS`,
1785 :mod:`GL` and :mod:`gl`,
1786 :mod:`IN`,
1787 :mod:`IOCTL`,
1788 :mod:`jpeg`,
1789 :mod:`panelparser`,
1790 :mod:`readcd`,
1791 :mod:`SV` and :mod:`sv`,
1792 :mod:`torgb`,
1793 :mod:`videoreader`,
1794 :mod:`WAIT`.
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +00001795
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00001796* The :mod:`asyncore` and :mod:`asynchat` modules are
1797 being actively maintained again, and a number of patches and bugfixes
1798 were applied. (Maintained by Josiah Carlson; see :issue:`1736190` for
1799 one patch.)
1800
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001801* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
1802 available, instead of restricting itself to protocol 1.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001803 (Contributed by W. Barnes; :issue:`1551443`.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001804
Andrew M. Kuchlingaaca9782008-07-06 17:44:17 +00001805* The :mod:`cgi` module will now read variables from the query string of an
1806 HTTP POST request. This makes it possible to use form actions with
1807 URLs such as "/cgi-bin/add.py?category=1". (Contributed by
1808 Alexandre Fiori and Nubis; :issue:`1817`.)
1809
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001810* The :mod:`cmath` module underwent an extensive set of revisions,
1811 thanks to Mark Dickinson and Christian Heimes, that added some new
1812 features and greatly improved the accuracy of the computations.
Mark Dickinson53bd2e12008-04-19 20:31:16 +00001813
Georg Brandle152a772008-05-24 18:31:28 +00001814 Five new functions were added:
Mark Dickinson53bd2e12008-04-19 20:31:16 +00001815
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001816 * :func:`polar` converts a complex number to polar form, returning
Georg Brandle152a772008-05-24 18:31:28 +00001817 the modulus and argument of that complex number.
Mark Dickinson53bd2e12008-04-19 20:31:16 +00001818
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001819 * :func:`rect` does the opposite, turning a (modulus, argument) pair
1820 back into the corresponding complex number.
1821
Georg Brandle152a772008-05-24 18:31:28 +00001822 * :func:`phase` returns the phase or argument of a complex number.
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001823
1824 * :func:`isnan` returns True if either
Georg Brandle152a772008-05-24 18:31:28 +00001825 the real or imaginary part of its argument is a NaN.
Andrew M. Kuchling2cede392008-04-20 16:54:02 +00001826
1827 * :func:`isinf` returns True if either the real or imaginary part of
1828 its argument is infinite.
1829
1830 The revisions also improved the numerical soundness of the
1831 :mod:`cmath` module. For all functions, the real and imaginary
1832 parts of the results are accurate to within a few units of least
1833 precision (ulps) whenever possible. See :issue:`1381` for the
1834 details. The branch cuts for :func:`asinh`, :func:`atanh`: and
1835 :func:`atan` have also been corrected.
1836
1837 The tests for the module have been greatly expanded; nearly 2000 new
1838 test cases exercise the algebraic functions.
Mark Dickinson53bd2e12008-04-19 20:31:16 +00001839
1840 On IEEE 754 platforms, the :mod:`cmath` module now handles IEEE 754
1841 special values and floating-point exceptions in a manner consistent
1842 with Annex 'G' of the C99 standard.
1843
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001844* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001845 fieldnames)` is a factory function that creates subclasses of the standard tuple
1846 whose fields are accessible by name as well as index. For example::
1847
Georg Brandle152a772008-05-24 18:31:28 +00001848 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001849 ... 'id name type size')
1850 # Names are separated by spaces or commas.
1851 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +00001852 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001853 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001854
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001855 >>> var = var_type(1, 'frequency', 'int', 4)
1856 >>> print var[0], var.id # Equivalent
1857 1 1
1858 >>> print var[2], var.type # Equivalent
1859 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +00001860 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001861 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +00001862 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001863 >>> v2
1864 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001865
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001866 Where the new :class:`namedtuple` type proved suitable, the standard
Georg Brandle152a772008-05-24 18:31:28 +00001867 library has been modified to return them. For example,
1868 the :meth:`Decimal.as_tuple` method now returns a named tuple with
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001869 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1870
Georg Brandl8ec7f652007-08-15 14:28:01 +00001871 (Contributed by Raymond Hettinger.)
1872
Georg Brandle152a772008-05-24 18:31:28 +00001873* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +00001874 :class:`deque` type now supports an optional *maxlen* parameter;
Georg Brandle152a772008-05-24 18:31:28 +00001875 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +00001876 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001877 old items to be discarded.
1878
1879 ::
1880
1881 >>> from collections import deque
1882 >>> dq=deque(maxlen=3)
1883 >>> dq
1884 deque([], maxlen=3)
1885 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
1886 >>> dq
1887 deque([1, 2, 3], maxlen=3)
1888 >>> dq.append(4)
1889 >>> dq
1890 deque([2, 3, 4], maxlen=3)
1891
1892 (Contributed by Raymond Hettinger.)
1893
Georg Brandl8ec7f652007-08-15 14:28:01 +00001894* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001895 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001896 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001897 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001898
Georg Brandle152a772008-05-24 18:31:28 +00001899 # Boldface text starting at y=0,x=21
Georg Brandl8ec7f652007-08-15 14:28:01 +00001900 # and affecting the rest of the line.
Georg Brandle152a772008-05-24 18:31:28 +00001901 stdscr.chgat(0,21, curses.A_BOLD)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001902
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001903 The :class:`Textbox` class in the :mod:`curses.textpad` module
1904 now supports editing in insert mode as well as overwrite mode.
1905 Insert mode is enabled by supplying a true value for the *insert_mode*
1906 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001907
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001908* The :mod:`datetime` module's :meth:`strftime` methods now support a
1909 ``%f`` format code that expands to the number of microseconds in the
1910 object, zero-padded on
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001911 the left to six places. (Contributed by Skip Montanaro; :issue:`1158`.)
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001912
Georg Brandle152a772008-05-24 18:31:28 +00001913* The :mod:`decimal` module was updated to version 1.66 of
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001914 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
1915 include some methods for some basic mathematical functions such as
1916 :meth:`exp` and :meth:`log10`::
1917
1918 >>> Decimal(1).exp()
1919 Decimal("2.718281828459045235360287471")
1920 >>> Decimal("2.7182818").ln()
1921 Decimal("0.9999999895305022877376682436")
1922 >>> Decimal(1000).log10()
1923 Decimal("3")
1924
Georg Brandle152a772008-05-24 18:31:28 +00001925 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001926 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
Georg Brandle152a772008-05-24 18:31:28 +00001927
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001928 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
1929 support added by Raymond Hettinger.)
1930
Georg Brandle152a772008-05-24 18:31:28 +00001931* The :mod:`difflib` module's :class:`SequenceMatcher` class
1932 now returns named tuples representing matches.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001933 In addition to behaving like tuples, the returned values
1934 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
1935 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001936
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001937* An optional ``timeout`` parameter was added to the
1938 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
1939 method, specifying a timeout measured in seconds. (Added by Facundo
Georg Brandle152a772008-05-24 18:31:28 +00001940 Batista.) Also, the :class:`FTP` class's
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001941 :meth:`storbinary` and :meth:`storlines`
Georg Brandle152a772008-05-24 18:31:28 +00001942 now take an optional *callback* parameter that will be called with
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001943 each block of data after the data has been sent.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001944 (Contributed by Phil Schwartz; :issue:`1221598`.)
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001945
Georg Brandle152a772008-05-24 18:31:28 +00001946* The :func:`reduce` built-in function is also available in the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001947 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
1948 only available from :mod:`functools`; currently there are no plans
Georg Brandle152a772008-05-24 18:31:28 +00001949 to drop the built-in in the 2.x series. (Patched by
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001950 Christian Heimes; :issue:`1739906`.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001951
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00001952* When possible, the :mod:`getpass` module will now use
1953 :file:`/dev/tty` (when available) to print
1954 a prompting message and read the password, falling back to using
1955 standard error and standard input. If the password may be echoed to
1956 the terminal, a warning is printed before the prompt is displayed.
1957 (Contributed by Gregory P. Smith.)
1958
Georg Brandle152a772008-05-24 18:31:28 +00001959* The :func:`glob.glob` function can now return Unicode filenames if
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00001960 a Unicode path was used and Unicode filenames are matched within the
1961 directory. (:issue:`1001604`)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001962
1963* The :mod:`gopherlib` module has been removed.
1964
Georg Brandle152a772008-05-24 18:31:28 +00001965* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001966 takes any number of iterables that return data *in sorted
1967 order*, and returns a new iterator that returns the contents of all
1968 the iterators, also in sorted order. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001969
1970 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
1971 [1, 2, 3, 5, 8, 9, 16]
1972
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001973 Another new function, ``heappushpop(heap, item)``,
Georg Brandle152a772008-05-24 18:31:28 +00001974 pushes *item* onto *heap*, then pops off and returns the smallest item.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001975 This is more efficient than making a call to :func:`heappush` and then
1976 :func:`heappop`.
1977
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00001978 :mod:`heapq` is now implemented to only use less-than comparison,
1979 instead of the less-than-or-equal comparison it previously used.
1980 This makes :mod:`heapq`'s usage of a type match that of the
1981 :meth:`list.sort` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001982 (Contributed by Raymond Hettinger.)
1983
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001984* An optional ``timeout`` parameter was added to the
Georg Brandle152a772008-05-24 18:31:28 +00001985 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001986 class constructors, specifying a timeout measured in seconds.
1987 (Added by Facundo Batista.)
1988
Georg Brandle152a772008-05-24 18:31:28 +00001989* Most of the :mod:`inspect` module's functions, such as
1990 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001991 In addition to behaving like tuples, the elements of the return value
1992 can also be accessed as attributes.
1993 (Contributed by Raymond Hettinger.)
1994
Georg Brandle152a772008-05-24 18:31:28 +00001995 Some new functions in the module include
1996 :func:`isgenerator`, :func:`isgeneratorfunction`,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001997 and :func:`isabstract`.
1998
1999* The :mod:`itertools` module gained several new functions.
2000
2001 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
2002 each of the elements; if some of the iterables are shorter than
2003 others, the missing values are set to *fillvalue*. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00002004
2005 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
2006 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
2007
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002008 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
2009 of the supplied iterables, a set of tuples containing
2010 every possible combination of the elements returned from each iterable. ::
2011
2012 itertools.product([1,2,3], [4,5,6]) ->
Georg Brandle152a772008-05-24 18:31:28 +00002013 [(1, 4), (1, 5), (1, 6),
2014 (2, 4), (2, 5), (2, 6),
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002015 (3, 4), (3, 5), (3, 6)]
2016
2017 The optional *repeat* keyword argument is used for taking the
Georg Brandle152a772008-05-24 18:31:28 +00002018 product of an iterable or a set of iterables with themselves,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002019 repeated *N* times. With a single iterable argument, *N*-tuples
2020 are returned::
2021
2022 itertools.product([1,2], repeat=3)) ->
Georg Brandle152a772008-05-24 18:31:28 +00002023 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002024 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
2025
2026 With two iterables, *2N*-tuples are returned. ::
2027
2028 itertools(product([1,2], [3,4], repeat=2) ->
Georg Brandle152a772008-05-24 18:31:28 +00002029 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
2030 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
2031 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002032 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
2033
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00002034 ``combinations(iterable, r)`` returns sub-sequences of length *r* from
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002035 the elements of *iterable*. ::
2036
2037 itertools.combinations('123', 2) ->
2038 [('1', '2'), ('1', '3'), ('2', '3')]
2039
2040 itertools.combinations('123', 3) ->
2041 [('1', '2', '3')]
2042
2043 itertools.combinations('1234', 3) ->
Georg Brandle152a772008-05-24 18:31:28 +00002044 [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002045 ('2', '3', '4')]
2046
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00002047 ``permutations(iter[, r])`` returns all the permutations of length *r* of
Georg Brandle152a772008-05-24 18:31:28 +00002048 the iterable's elements. If *r* is not specified, it will default to the
Georg Brandlcb635652008-05-05 20:59:05 +00002049 number of elements produced by the iterable. ::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002050
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00002051 itertools.permutations([1,2,3,4], 2) ->
Georg Brandle152a772008-05-24 18:31:28 +00002052 [(1, 2), (1, 3), (1, 4),
2053 (2, 1), (2, 3), (2, 4),
2054 (3, 1), (3, 2), (3, 4),
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00002055 (4, 1), (4, 2), (4, 3)]
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002056
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00002057 ``itertools.chain(*iterables)`` is an existing function in
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00002058 :mod:`itertools` that gained a new constructor in Python 2.6.
Georg Brandle152a772008-05-24 18:31:28 +00002059 ``itertools.chain.from_iterable(iterable)`` takes a single
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002060 iterable that should return other iterables. :func:`chain` will
2061 then return all the elements of the first iterable, then
2062 all the elements of the second, and so on. ::
2063
2064 chain.from_iterable([[1,2,3], [4,5,6]]) ->
2065 [1, 2, 3, 4, 5, 6]
Georg Brandle152a772008-05-24 18:31:28 +00002066
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002067 (All contributed by Raymond Hettinger.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002068
Georg Brandle152a772008-05-24 18:31:28 +00002069* The :mod:`logging` module's :class:`FileHandler` class
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002070 and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
Georg Brandle152a772008-05-24 18:31:28 +00002071 and :class:`TimedRotatingFileHandler` now
2072 have an optional *delay* parameter to its constructor. If *delay*
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002073 is true, opening of the log file is deferred until the first
2074 :meth:`emit` call is made. (Contributed by Vinay Sajip.)
2075
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002076 :class:`TimedRotatingFileHandler` also has a *utc* constructor
2077 parameter. If the argument is true, UTC time will be used
2078 in determining when midnight occurs and in generating filenames;
2079 otherwise local time will be used.
2080
Georg Brandl8ec7f652007-08-15 14:28:01 +00002081* The :mod:`macfs` module has been removed. This in turn required the
2082 :func:`macostools.touched` function to be removed because it depended on the
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002083 :mod:`macfs` module. (:issue:`1490190`)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002084
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00002085* :class:`mmap` objects now have a :meth:`rfind` method that finds
2086 a substring, beginning at the end of the string and searching
2087 backwards. The :meth:`find` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002088 also gained an *end* parameter containing the index at which to stop
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00002089 the forward search.
2090 (Contributed by John Lenton.)
2091
Georg Brandle152a772008-05-24 18:31:28 +00002092* The :mod:`operator` module gained a
2093 :func:`methodcaller` function that takes a name and an optional
2094 set of arguments, returning a callable that will call
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002095 the named function on any arguments passed to it. For example::
2096
2097 >>> # Equivalent to lambda s: s.replace('old', 'new')
2098 >>> replacer = operator.methodcaller('replace', 'old', 'new')
2099 >>> replacer('old wine in old bottles')
2100 'new wine in new bottles'
Georg Brandle152a772008-05-24 18:31:28 +00002101
Georg Brandl27504da2008-03-04 07:25:54 +00002102 (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002103
2104 The :func:`attrgetter` function now accepts dotted names and performs
2105 the corresponding attribute lookups::
2106
2107 >>> inst_name = operator.attrgetter('__class__.__name__')
2108 >>> inst_name('')
2109 'str'
2110 >>> inst_name(help)
2111 '_Helper'
2112
Georg Brandl27504da2008-03-04 07:25:54 +00002113 (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002114
Georg Brandle152a772008-05-24 18:31:28 +00002115* New functions in the :mod:`os` module include
2116 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002117 and ``lchmod(path, mode)``, on operating systems that support these
2118 functions. :func:`fchmod` and :func:`fchown` let you change the mode
2119 and ownership of an opened file, and :func:`lchmod` changes the mode
2120 of a symlink.
2121
2122 (Contributed by Georg Brandl and Christian Heimes.)
2123
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002124* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002125 set to True, it will follow symlinks pointing to directories and
2126 visit the directory's contents. For backward compatibility, the
2127 parameter's default value is false. Note that the function can fall
2128 into an infinite recursion if there's a symlink that points to a
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002129 parent directory. (:issue:`1273829`)
Georg Brandle152a772008-05-24 18:31:28 +00002130
2131* The ``os.environ`` object's :meth:`clear` method will now unset the
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002132 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002133 the object's keys. (Contributed by Martin Horcicka; :issue:`1181`.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002134
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002135* In the :mod:`os.path` module, the :func:`splitext` function
2136 has been changed to not split on leading period characters.
2137 This produces better results when operating on Unix's dot-files.
2138 For example, ``os.path.splitext('.ipython')``
2139 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002140 (:issue:`115886`)
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002141
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00002142 A new function, :func:`relpath(path, start)` returns a relative path
2143 from the ``start`` path, if it's supplied, or from the current
2144 working directory to the destination ``path``. (Contributed by
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002145 Richard Barran; :issue:`1339796`.)
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00002146
Georg Brandle152a772008-05-24 18:31:28 +00002147 On Windows, :func:`os.path.expandvars` will now expand environment variables
2148 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002149 user's home directory path. (Contributed by Josiah Carlson;
2150 :issue:`957650`.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002151
Georg Brandle152a772008-05-24 18:31:28 +00002152* The Python debugger provided by the :mod:`pdb` module
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002153 gained a new command: "run" restarts the Python program being debugged,
2154 and can optionally take new command-line arguments for the program.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002155 (Contributed by Rocky Bernstein; :issue:`1393667`.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002156
Georg Brandle152a772008-05-24 18:31:28 +00002157 The :func:`post_mortem` function, used to enter debugging of a
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002158 traceback, will now use the traceback returned by :func:`sys.exc_info`
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002159 if no traceback is supplied. (Contributed by Facundo Batista;
2160 :issue:`1106316`.)
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002161
Georg Brandle152a772008-05-24 18:31:28 +00002162* The :mod:`pickletools` module now has an :func:`optimize` function
2163 that takes a string containing a pickle and removes some unused
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002164 opcodes, returning a shorter pickle that contains the same data structure.
2165 (Contributed by Raymond Hettinger.)
2166
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002167* A :func:`get_data` function was added to the :mod:`pkgutil`
2168 module that returns the contents of resource files included
2169 with an installed Python package. For example::
2170
Benjamin Peterson60ffcbe2008-04-21 22:57:00 +00002171 >>> import pkgutil
2172 >>> pkgutil.get_data('test', 'exception_hierarchy.txt')
2173 'BaseException
2174 +-- SystemExit
2175 +-- KeyboardInterrupt
2176 +-- GeneratorExit
2177 +-- Exception
2178 +-- StopIteration
2179 +-- StandardError
2180 ...'
Georg Brandle152a772008-05-24 18:31:28 +00002181 >>>
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002182
2183 (Contributed by Paul Moore; :issue:`2439`.)
2184
Georg Brandl8ec7f652007-08-15 14:28:01 +00002185* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
2186 are wrappers for the corresponding system calls (where they're available).
2187 Constants for the flag values are defined in the :mod:`stat` module; some
2188 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
2189 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
2190 file. (Contributed by M. Levinson.)
2191
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002192 ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors
2193 from *low* to *high*, ignoring any errors and not including *high* itself.
2194 This function is now used by the :mod:`subprocess` module to make starting
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002195 processes faster. (Contributed by Georg Brandl; :issue:`1663329`.)
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002196
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00002197* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
Georg Brandle152a772008-05-24 18:31:28 +00002198 their :attr:`buffer_size` attribute to change the size of the buffer
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00002199 used to hold character data.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002200 (Contributed by Achim Gaedke; :issue:`1137`.)
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00002201
Georg Brandla6168f92008-05-25 07:20:14 +00002202* The :mod:`Queue` module now provides queue classes that retrieve entries
Georg Brandle152a772008-05-24 18:31:28 +00002203 in different orders. The :class:`PriorityQueue` class stores
2204 queued items in a heap and retrieves them in priority order,
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002205 and :class:`LifoQueue` retrieves the most recently added entries first,
2206 meaning that it behaves like a stack.
2207 (Contributed by Raymond Hettinger.)
2208
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002209* The :mod:`random` module's :class:`Random` objects can
2210 now be pickled on a 32-bit system and unpickled on a 64-bit
2211 system, and vice versa. Unfortunately, this change also means
2212 that Python 2.6's :class:`Random` objects can't be unpickled correctly
2213 on earlier versions of Python.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002214 (Contributed by Shawn Ligocki; :issue:`1727780`.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002215
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002216 The new ``triangular(low, high, mode)`` function returns random
2217 numbers following a triangular distribution. The returned values
Georg Brandle152a772008-05-24 18:31:28 +00002218 are between *low* and *high*, not including *high* itself, and
2219 with *mode* as the mode, the most frequently occurring value
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00002220 in the distribution. (Contributed by Wladmir van der Laan and
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002221 Raymond Hettinger; :issue:`1681432`.)
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002222
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002223* Long regular expression searches carried out by the :mod:`re`
2224 module will now check for signals being delivered, so especially
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +00002225 time-consuming searches can now be interrupted.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002226 (Contributed by Josh Hoyt and Ralf Schmitt; :issue:`846388`.)
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002227
Georg Brandl8ec7f652007-08-15 14:28:01 +00002228* The :mod:`rgbimg` module has been removed.
2229
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +00002230* The :mod:`rlcompleter` module's :meth:`Completer.complete()` method
2231 will now ignore exceptions triggered while evaluating a name.
2232 (Fixed by Lorenz Quack; :issue:`2250`.)
2233
Georg Brandle152a772008-05-24 18:31:28 +00002234* The :mod:`sched` module's :class:`scheduler` instances now
2235 have a read-only :attr:`queue` attribute that returns the
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002236 contents of the scheduler's queue, represented as a list of
Georg Brandl225163d2008-03-05 07:10:35 +00002237 named tuples with the fields ``(time, priority, action, argument)``.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002238 (Contributed by Raymond Hettinger; :issue:`1861`.)
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002239
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002240* The :mod:`select` module now has wrapper functions
2241 for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls.
2242 Also, a :meth:`modify` method was added to the existing :class:`poll`
2243 objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
Georg Brandle152a772008-05-24 18:31:28 +00002244 or file object and an event mask,
2245
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002246 (Contributed by Christian Heimes; :issue:`1657`.)
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002247
Georg Brandle152a772008-05-24 18:31:28 +00002248* The :mod:`sets` module has been deprecated; it's better to
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002249 use the built-in :class:`set` and :class:`frozenset` types.
2250
Andrew M. Kuchlingaaca9782008-07-06 17:44:17 +00002251* The :func:`shutil.copytree` function now has an optional **ignore** argument
2252 that takes a callable object. This callable will receive each directory path
2253 and a list of the directory's contents, and returns a list of names that
2254 will be ignored, not copied.
2255
2256 The :mod:`shutil` module also provides an :func:`ignore_patterns`
2257 function for use with this new parameter.
2258 :func:`ignore_patterns` takes an arbitrary number of glob-style patterns
2259 and will ignore any files and directories that match this pattern.
2260 The following example copies a directory tree, but skip both SVN's internal
2261 :file:`.svn` directories and Emacs backup
2262 files, which have names ending with '~'::
2263
2264 shutil.copytree('Doc/library', '/tmp/library',
Andrew M. Kuchling10cf7d92008-07-07 16:51:09 +00002265 ignore=shutil.ignore_patterns('*~', '.svn'))
Andrew M. Kuchlingaaca9782008-07-06 17:44:17 +00002266
2267 (Contributed by Tarek Ziadé; :issue:`2663`.)
2268
Georg Brandle152a772008-05-24 18:31:28 +00002269* Integrating signal handling with GUI handling event loops
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00002270 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00002271 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00002272 The :mod:`signal` module can now make this more efficient.
2273 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
Georg Brandle152a772008-05-24 18:31:28 +00002274 to be used; when a signal is received, a byte is written to that
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00002275 file descriptor. There's also a C-level function,
2276 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
2277
2278 Event loops will use this by opening a pipe to create two descriptors,
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00002279 one for reading and one for writing. The writable descriptor
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00002280 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
2281 will be added to the list of descriptors monitored by the event loop via
2282 :cfunc:`select` or :cfunc:`poll`.
Georg Brandle152a772008-05-24 18:31:28 +00002283 On receiving a signal, a byte will be written and the main event loop
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00002284 will be woken up, without the need to poll.
2285
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002286 (Contributed by Adam Olsen; :issue:`1583`.)
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00002287
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002288 The :func:`siginterrupt` function is now available from Python code,
2289 and allows changing whether signals can interrupt system calls or not.
2290 (Contributed by Ralf Schmitt.)
2291
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00002292 The :func:`setitimer` and :func:`getitimer` functions have also been
2293 added on systems that support these system calls. :func:`setitimer`
2294 allows setting interval timers that will cause a signal to be
2295 delivered to the process after a specified time, measured in
2296 wall-clock time, consumed process time, or combined process+system
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002297 time. (Contributed by Guilherme Polo; :issue:`2240`.)
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00002298
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002299* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
2300 addition of the :class:`SMTP_SSL` class. This class supports an
Georg Brandle152a772008-05-24 18:31:28 +00002301 interface identical to the existing :class:`SMTP` class. Both
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00002302 class constructors also have an optional ``timeout`` parameter
2303 that specifies a timeout for the initial connection attempt, measured in
2304 seconds.
2305
2306 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002307 the module. LMTP is used in place of SMTP when transferring e-mail
2308 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00002309
2310 (SMTP over SSL contributed by Monty Taylor; timeout parameter
2311 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002312 Hedstrom; :issue:`957003`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002313
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00002314* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
2315 and forgets any knowledge obtained from the server not obtained from
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002316 the TLS negotiation itself. (Patch contributed by Bill Fenner;
2317 :issue:`829951`.)
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00002318
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002319* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
2320 a high-performance non-IP-based protocol designed for use in clustered
2321 environments. TIPC addresses are 4- or 5-tuples.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002322 (Contributed by Alberto Bertogli; :issue:`1646`.)
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00002323
Georg Brandle152a772008-05-24 18:31:28 +00002324 A new function, :func:`create_connection`, takes an address
2325 and connects to it using an optional timeout value, returning
Andrew M. Kuchling04f58762008-04-15 02:24:15 +00002326 the connected socket object.
2327
Georg Brandle152a772008-05-24 18:31:28 +00002328* The base classes in the :mod:`SocketServer` module now support
2329 calling a :meth:`handle_timeout` method after a span of inactivity
2330 specified by the server's :attr:`timeout` attribute. (Contributed
2331 by Michael Pomraning.) The :meth:`serve_forever` method
Andrew M. Kuchlingf68b5532008-04-09 01:08:32 +00002332 now takes an optional poll interval measured in seconds,
2333 controlling how often the server will check for a shutdown request.
Georg Brandle152a772008-05-24 18:31:28 +00002334 (Contributed by Pedro Werneck and Jeffrey Yasskin;
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002335 :issue:`742598`, :issue:`1193577`.)
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00002336
2337* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
Georg Brandle152a772008-05-24 18:31:28 +00002338 using the format character ``'?'``.
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00002339 (Contributed by David Remahl.)
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002340
2341* The :class:`Popen` objects provided by the :mod:`subprocess` module
2342 now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods.
2343 On Windows, :meth:`send_signal` only supports the :const:`SIGTERM`
2344 signal, and all these methods are aliases for the Win32 API function
Georg Brandle152a772008-05-24 18:31:28 +00002345 :cfunc:`TerminateProcess`.
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002346 (Contributed by Christian Heimes.)
Georg Brandle152a772008-05-24 18:31:28 +00002347
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002348* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00002349 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002350 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00002351 derived from the :file:`float.h` file. Attributes of this object
Georg Brandle152a772008-05-24 18:31:28 +00002352 include
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00002353 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002354 (smallest difference between 1.0 and the next largest value
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002355 representable), and several others. (Contributed by Christian Heimes;
2356 :issue:`1534`.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002357
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00002358 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
2359 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
2360 If this variable is true, the compiled files are not written. The
2361 variable is initially set on start-up by supplying the :option:`-B`
2362 switch to the Python interpreter, or by setting the
2363 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
Georg Brandle152a772008-05-24 18:31:28 +00002364 running the interpreter. Python code can subsequently
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00002365 change the value of this variable to control whether bytecode files
2366 are written or not.
2367 (Contributed by Neal Norwitz and Georg Brandl.)
2368
Georg Brandle152a772008-05-24 18:31:28 +00002369 Information about the command-line arguments supplied to the Python
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002370 interpreter is available by reading attributes of a named
2371 tuple available as ``sys.flags``. For example, the :attr:`verbose`
2372 attribute is true if Python
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002373 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
2374 These attributes are all read-only.
2375 (Contributed by Christian Heimes.)
2376
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002377 A new function, :func:`getsizeof`, takes a Python object and returns
2378 the amount of memory used by the object, measured in bytes. Built-in
2379 objects return correct results; third-party extensions may not,
2380 but can define a :meth:`__sizeof__` method to return the
2381 object's size.
2382 (Contributed by Robert Schuppenies; :issue:`2898`.)
2383
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002384 It's now possible to determine the current profiler and tracer functions
Georg Brandle152a772008-05-24 18:31:28 +00002385 by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002386 (Contributed by Georg Brandl; :issue:`1648`.)
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002387
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002388* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
2389 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
Georg Brandle152a772008-05-24 18:31:28 +00002390 format that was already supported. The default format
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002391 is GNU tar; specify the ``format`` parameter to open a file
2392 using a different format::
2393
2394 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
2395
2396 The new ``errors`` parameter lets you specify an error handling
2397 scheme for character conversions: the three standard ways Python can
2398 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
2399 special value ``'utf-8'``, which replaces bad characters with their
2400 UTF-8 representation. Character conversions occur because the PAX
2401 format supports Unicode filenames, defaulting to UTF-8 encoding.
2402
2403 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
2404 a function that can be used to exclude certain filenames from
Georg Brandle152a772008-05-24 18:31:28 +00002405 an archive.
2406 The function must take a filename and return true if the file
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002407 should be excluded or false if it should be archived.
2408 The function is applied to both the name initially passed to :meth:`add`
2409 and to the names of files in recursively-added directories.
Georg Brandle152a772008-05-24 18:31:28 +00002410
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002411 (All changes contributed by Lars Gustäbel).
2412
2413* An optional ``timeout`` parameter was added to the
2414 :class:`telnetlib.Telnet` class constructor, specifying a timeout
2415 measured in seconds. (Added by Facundo Batista.)
2416
Georg Brandle152a772008-05-24 18:31:28 +00002417* The :class:`tempfile.NamedTemporaryFile` class usually deletes
2418 the temporary file it created when the file is closed. This
2419 behaviour can now be changed by passing ``delete=False`` to the
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002420 constructor. (Contributed by Damien Miller; :issue:`1537850`.)
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002421
Georg Brandle152a772008-05-24 18:31:28 +00002422 A new class, :class:`SpooledTemporaryFile`, behaves like
2423 a temporary file but stores its data in memory until a maximum size is
2424 exceeded. On reaching that limit, the contents will be written to
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002425 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
2426
2427 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
Georg Brandle152a772008-05-24 18:31:28 +00002428 both work as context managers, so you can write
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002429 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002430 (Contributed by Alexander Belopolsky; :issue:`2021`.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002431
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002432* The :mod:`test.test_support` module now contains a
2433 :func:`EnvironmentVarGuard`
2434 context manager that supports temporarily changing environment variables and
Georg Brandle152a772008-05-24 18:31:28 +00002435 automatically restores them to their old values.
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002436
2437 Another context manager, :class:`TransientResource`, can surround calls
2438 to resources that may or may not be available; it will catch and
2439 ignore a specified list of exceptions. For example,
2440 a network test may ignore certain failures when connecting to an
2441 external web site::
2442
2443 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
Georg Brandle152a772008-05-24 18:31:28 +00002444 f = urllib.urlopen('https://sf.net')
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00002445 ...
2446
2447 (Contributed by Brett Cannon.)
2448
Georg Brandle152a772008-05-24 18:31:28 +00002449* The :mod:`textwrap` module can now preserve existing whitespace
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002450 at the beginnings and ends of the newly-created lines
2451 by specifying ``drop_whitespace=False``
2452 as an argument::
2453
2454 >>> S = """This sentence has a bunch of extra whitespace."""
2455 >>> print textwrap.fill(S, width=15)
2456 This sentence
2457 has a bunch
2458 of extra
2459 whitespace.
2460 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
2461 This sentence
2462 has a bunch
2463 of extra
2464 whitespace.
Georg Brandle152a772008-05-24 18:31:28 +00002465 >>>
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002466
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002467 (Contributed by Dwayne Bailey; :issue:`1581073`.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002468
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002469* The :mod:`threading` module's :class:`Thread` objects
2470 gained a :meth:`getIdent` method that returns the thread's
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002471 identifier, a nonzero integer. (Contributed by Gregory P. Smith;
2472 :issue:`2871`.)
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002473
Georg Brandle152a772008-05-24 18:31:28 +00002474* The :mod:`timeit` module now accepts callables as well as strings
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002475 for the statement being timed and for the setup code.
Georg Brandle152a772008-05-24 18:31:28 +00002476 Two convenience functions were added for creating
2477 :class:`Timer` instances:
2478 ``repeat(stmt, setup, time, repeat, number)`` and
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002479 ``timeit(stmt, setup, time, number)`` create an instance and call
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002480 the corresponding method. (Contributed by Erik Demaine;
2481 :issue:`1533909`.)
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002482
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002483* The :mod:`Tkinter` module now accepts lists and tuples for options,
2484 separating the elements by spaces before passing the resulting value to
2485 Tcl/Tk.
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +00002486 (Contributed by Guilherme Polo; :issue:`2906`.)
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002487
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002488* The :mod:`turtle` module for turtle graphics was greatly enhanced by
2489 Gregor Lingl. New features in the module include:
2490
2491 * Better animation of turtle movement and rotation.
2492 * Control over turtle movement using the new delay(),
2493 tracer(), and speed() methods.
2494 * The ability to set new shapes for the turtle, and to
2495 define a new coordinate system.
2496 * Turtles now have an undo() method that can roll back actions.
2497 * Simple support for reacting to input events such as mouse and keyboard
2498 activity, making it possible to write simple games.
2499 * A :file:`turtle.cfg` file can be used to customize the starting appearance
2500 of the turtle's screen.
2501 * The module's docstrings can be replaced by new docstrings that have been
2502 translated into another language.
2503
2504 (:issue:`1513695`)
2505
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002506* An optional ``timeout`` parameter was added to the
2507 :func:`urllib.urlopen` function and the
Georg Brandle152a772008-05-24 18:31:28 +00002508 :class:`urllib.ftpwrapper` class constructor, as well as the
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002509 :func:`urllib2.urlopen` function. The parameter specifies a timeout
2510 measured in seconds. For example::
2511
2512 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
2513 Traceback (most recent call last):
2514 ...
2515 urllib2.URLError: <urlopen error timed out>
Georg Brandle152a772008-05-24 18:31:28 +00002516 >>>
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002517
Georg Brandle152a772008-05-24 18:31:28 +00002518 (Added by Facundo Batista.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002519
Georg Brandle152a772008-05-24 18:31:28 +00002520* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +00002521 gained an optional *line* argument that can be used to supply the
2522 line of source code. (Added as part of :issue:`1631171`, which re-implemented
2523 part of the :mod:`warnings` module in C code.)
2524
2525* The XML-RPC :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002526 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002527 their socket by passing True as the ``bind_and_activate``
2528 constructor parameter. This can be used to modify the instance's
Georg Brandle152a772008-05-24 18:31:28 +00002529 :attr:`allow_reuse_address` attribute before calling the
2530 :meth:`server_bind` and :meth:`server_activate` methods to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002531 open the socket and begin listening for connections.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002532 (Contributed by Peter Parente; :issue:`1599845`.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002533
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002534 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
Georg Brandle152a772008-05-24 18:31:28 +00002535 attribute; if true, the exception and formatted traceback are returned
2536 as HTTP headers "X-Exception" and "X-Traceback". This feature is
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002537 for debugging purposes only and should not be used on production servers
2538 because the tracebacks could possibly reveal passwords or other sensitive
Georg Brandle152a772008-05-24 18:31:28 +00002539 information. (Contributed by Alan McIntyre as part of his
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002540 project for Google's Summer of Code 2007.)
2541
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002542* The :mod:`xmlrpclib` module no longer automatically converts
Georg Brandle152a772008-05-24 18:31:28 +00002543 :class:`datetime.date` and :class:`datetime.time` to the
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002544 :class:`xmlrpclib.DateTime` type; the conversion semantics were
2545 not necessarily correct for all applications. Code using
Georg Brandle152a772008-05-24 18:31:28 +00002546 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
2547 instances. (:issue:`1330538`) The code can also handle
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002548 dates before 1900 (contributed by Ralf Schmitt; :issue:`2014`)
2549 and 64-bit integers represented by using ``<i8>`` in XML-RPC responses
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002550 (contributed by Riku Lindblad; :issue:`2985`).
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002551
Georg Brandle152a772008-05-24 18:31:28 +00002552* The :mod:`zipfile` module's :class:`ZipFile` class now has
2553 :meth:`extract` and :meth:`extractall` methods that will unpack
2554 a single file or all the files in the archive to the current directory, or
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002555 to a specified directory::
2556
2557 z = zipfile.ZipFile('python-251.zip')
2558
2559 # Unpack a single file, writing it relative to the /tmp directory.
2560 z.extract('Python/sysmodule.c', '/tmp')
2561
2562 # Unpack all the files in the archive.
2563 z.extractall()
2564
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002565 (Contributed by Alan McIntyre; :issue:`467924`.)
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002566
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002567 The :meth:`open`, :meth:`read` and :meth:`extract` methods can now
2568 take either a filename or a :class:`ZipInfo` object. This is useful when an
2569 archive accidentally contains a duplicated filename.
2570 (Contributed by Graham Horler; :issue:`1775025`.)
Andrew M. Kuchlingba290db2008-05-09 11:46:05 +00002571
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002572 Finally, :mod:`zipfile` now supports using Unicode filenames
2573 for archived files. (Contributed by Alexey Borzenkov; :issue:`1734346`.)
2574
Georg Brandlb19be572007-12-29 10:57:00 +00002575.. ======================================================================
2576.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002577
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002578The :mod:`ast` module
2579----------------------
2580
2581The :mod:`ast` module provides an Abstract Syntax Tree representation
2582of Python code. For Python 2.6, Armin Ronacher contributed a set of
2583helper functions that perform various common tasks. These will be useful
2584for HTML templating packages, code analyzers, and similar tools that
2585process Python code.
2586
2587The :func:`parse` function takes an expression and returns an AST.
2588The :func:`dump` function outputs a representation of a tree, suitable
2589for debugging::
2590
2591 import ast
2592
2593 t = ast.parse("""
2594 d = {}
2595 for i in 'abcdefghijklm':
2596 d[i + i] = ord(i) - ord('a') + 1
2597 print d
2598 """)
2599 print ast.dump(t)
2600
2601This outputs::
2602
2603 Module(body=[Assign(targets=[Name(id='d', ctx=Store())],
2604 value=Dict(keys=[], values=[])), For(target=Name(id='i',
2605 ctx=Store()), iter=Str(s='abcdefghijklm'),
2606 body=[Assign(targets=[Subscript(value=Name(id='d', ctx=Load()),
2607 slice=Index(value=BinOp(left=Name(id='i', ctx=Load()), op=Add(),
2608 right=Name(id='i', ctx=Load()))), ctx=Store())],
2609 value=BinOp(left=BinOp(left=Call(func=Name(id='ord', ctx=Load()),
2610 args=[Name(id='i', ctx=Load())], keywords=[], starargs=None,
2611 kwargs=None), op=Sub(), right=Call(func=Name(id='ord',
2612 ctx=Load()), args=[Str(s='a')], keywords=[], starargs=None,
2613 kwargs=None)), op=Add(), right=Num(n=1)))], orelse=[]),
2614 Print(dest=None, values=[Name(id='d', ctx=Load())], nl=True)])
2615
2616The :func:`literal_eval` method takes a string or an AST
2617representing a literal expression, one that contains a Python
2618expression containing only strings, numbers, dictionaries, etc. but no
2619statements or function calls, and returns the resulting value. If you
2620need to unserialize an expression but need to worry about security
2621and can't risk using an :func:`eval` call, :func:`literal_eval` will
2622handle it safely::
2623
2624 >>> literal = '("a", "b", {2:4, 3:8, 1:2})'
2625 >>> print ast.literal_eval(literal)
2626 ('a', 'b', {1: 2, 2: 4, 3: 8})
2627 >>> print ast.literal_eval('"a" + "b"')
2628 Traceback (most recent call last):
2629 ...
2630 ValueError: malformed string
2631
Andrew M. Kuchlingaaca9782008-07-06 17:44:17 +00002632The module also includes :class:`NodeVisitor` and
2633:class:`NodeTransformer` classes for traversing and modifying an AST,
2634and functions for common transformations such as changing line
2635numbers.
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002636
2637.. ======================================================================
2638
2639The :mod:`future_builtins` module
2640--------------------------------------
2641
2642Python 3.0 makes various changes to the repertoire of built-in
2643functions, and most of the changes can't be introduced in the Python
26442.x series because they would break compatibility.
2645The :mod:`future_builtins` module provides versions
2646of these built-in functions that can be imported when writing
26473.0-compatible code.
2648
2649The functions in this module currently include:
2650
2651* ``ascii(**obj**)``: equivalent to :func:`repr`. In Python 3.0,
2652 :func:`repr` will return a Unicode string, while :func:`ascii` will
2653 return a pure ASCII bytestring.
2654
2655* ``filter(**predicate**, **iterable**)``,
2656 ``map(**func**, **iterable1**, ...)``: the 3.0 versions
2657 return iterators, differing from the 2.x built-ins that return lists.
2658
2659* ``hex(**value**)``, ``oct(**value**)``: instead of calling the
2660 :meth:`__hex__` or :meth:`__oct__` methods, these versions will
2661 call the :meth:`__index__` method and convert the result to hexadecimal
2662 or octal.
2663
2664.. ======================================================================
2665
Brett Cannon4b964f92008-05-05 20:21:38 +00002666The :mod:`json` module
2667----------------------
2668
2669The new :mod:`json` module supports the encoding and decoding of Python types in
2670JSON (Javascript Object Notation). JSON is a lightweight interchange format
2671often used in web applications. For more information about JSON, see
2672http://www.json.org.
2673
2674:mod:`json` comes with support for decoding and encoding most builtin Python
2675types. The following example encodes and decodes a dictionary::
2676
2677 >>> import json
2678 >>> data = {"spam" : "foo", "parrot" : 42}
2679 >>> in_json = json.dumps(data) # Encode the data
2680 >>> in_json
2681 '{"parrot": 42, "spam": "foo"}'
2682 >>> json.loads(in_json) # Decode into a Python object
2683 {"spam" : "foo", "parrot" : 42}
2684
2685It is also possible to write your own decoders and encoders to support more
2686types. Pretty-printing of the JSON strings is also supported.
2687
2688:mod:`json` (originally called simplejson) was written by Bob Ippolito.
2689
2690
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002691.. ======================================================================
2692
2693plistlib: A Property-List Parser
2694--------------------------------------------------
2695
Georg Brandle152a772008-05-24 18:31:28 +00002696A commonly-used format on MacOS X is the ``.plist`` format,
2697which stores basic data types (numbers, strings, lists,
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002698and dictionaries) and serializes them into an XML-based format.
2699(It's a lot like the XML-RPC serialization of data types.)
2700
Georg Brandle152a772008-05-24 18:31:28 +00002701Despite being primarily used on MacOS X, the format
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002702has nothing Mac-specific about it and the Python implementation works
2703on any platform that Python supports, so the :mod:`plistlib` module
2704has been promoted to the standard library.
2705
2706Using the module is simple::
2707
2708 import sys
2709 import plistlib
2710 import datetime
2711
2712 # Create data structure
2713 data_struct = dict(lastAccessed=datetime.datetime.now(),
2714 version=1,
2715 categories=('Personal', 'Shared', 'Private'))
2716
2717 # Create string containing XML.
2718 plist_str = plistlib.writePlistToString(data_struct)
2719 new_struct = plistlib.readPlistFromString(plist_str)
2720 print data_struct
2721 print new_struct
2722
2723 # Write data structure to a file and read it back.
2724 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
2725 new_struct = plistlib.readPlist('/tmp/customizations.plist')
2726
2727 # read/writePlist accepts file-like objects as well as paths.
2728 plistlib.writePlist(data_struct, sys.stdout)
Georg Brandle152a772008-05-24 18:31:28 +00002729
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002730.. ======================================================================
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002731
Andrew M. Kuchlingb93dc5f2008-07-13 21:43:52 +00002732ctypes Enhancements
2733--------------------------------------------------
2734
2735Thomas Heller continued to maintain and enhance the
2736:mod:`ctypes` module.
2737
2738:mod:`ctypes` now supports a :class:`c_bool` datatype
2739that represents the C99 ``bool`` type. (Contributed by David Remahl;
2740:issue:`1649190`.)
2741
2742The :mod:`ctypes` string, buffer and array types have improved
2743support for extended slicing syntax,
2744where various combinations of ``(start, stop, step)`` are supplied.
2745(Implemented by Thomas Wouters.)
2746
2747.. Revision 57769
2748
2749A new calling convention tells :mod:`ctypes` to clear the ``errno`` or
2750Win32 LastError variables at the outset of each wrapped call.
2751(Implemented by Thomas Heller; :issue:`1798`.)
2752
2753For the Unix ``errno`` variable: when creating a wrapped function,
2754you can supply ``use_errno=True`` as a keyword parameter
2755to the :func:`DLL` function
2756and then call the module-level methods :meth:`set_errno`
2757and :meth:`get_errno` to set and retrieve the error value.
2758
2759The Win32 LastError variable is supported similarly by
2760the :func:`DLL`, :func:`OleDLL`, and :func:`WinDLL` functions.
2761You supply ``use_last_error=True`` as a keyword parameter
2762and then call the module-level methods :meth:`set_last_error`
2763and :meth:`get_last_error`.
2764
2765The :func:`byref` function, used to retrieve a pointer to a ctypes
2766instance, now has an optional **offset** parameter that is a byte
2767count that will be added to the returned pointer.
2768
2769.. ======================================================================
2770
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002771Improved SSL Support
2772--------------------------------------------------
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002773
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002774Bill Janssen made extensive improvements to Python 2.6's support for
2775the Secure Sockets Layer by adding a new module, :mod:`ssl`, on top of
2776the `OpenSSL <http://www.openssl.org/>`__ library. This new module
2777provides more control over the protocol negotiated, the X.509
2778certificates used, and has better support for writing SSL servers (as
2779opposed to clients) in Python. The existing SSL support in the
2780:mod:`socket` module hasn't been removed and continues to work,
2781though it will be removed in Python 3.0.
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002782
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002783To use the new module, first you must create a TCP connection in the
2784usual way and then pass it to the :func:`ssl.wrap_socket` function.
2785It's possible to specify whether a certificate is required, and to
2786obtain certificate info by calling the :meth:`getpeercert` method.
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002787
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002788.. seealso::
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002789
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002790 The documentation for the :mod:`ssl` module.
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002791
Georg Brandlb19be572007-12-29 10:57:00 +00002792.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002793
2794
2795Build and C API Changes
2796=======================
2797
2798Changes to Python's build process and to the C API include:
2799
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00002800* Python 2.6 can be built with Microsoft Visual Studio 2008.
2801 See the :file:`PCbuild9` directory for the build files.
2802 (Implemented by Christian Heimes.)
2803
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002804* On MacOS X, Python 2.6 can be compiled as a 4-way universal build.
2805 The :program:`configure` script
2806 can take a :option:`--with-universal-archs=[32-bit|64-bit|all]`
2807 switch, controlling whether the binaries are built for 32-bit
2808 architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
2809 (Contributed by Ronald Oussoren.)
2810
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00002811* Python now can only be compiled with C89 compilers (after 19
2812 years!). This means that the Python source tree can now drop its
2813 own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
2814 are in the C89 standard library.
2815
Georg Brandle152a772008-05-24 18:31:28 +00002816* The BerkeleyDB module now has a C API object, available as
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002817 ``bsddb.db.api``. This object can be used by other C extensions
2818 that wish to use the :mod:`bsddb` module for their own purposes.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002819 (Contributed by Duncan Grisby; :issue:`1551895`.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002820
Georg Brandle152a772008-05-24 18:31:28 +00002821* The new buffer interface, previously described in
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002822 `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__,
2823 adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyObject_ReleaseBuffer`,
2824 as well as a few other functions.
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002825
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002826* Python's use of the C stdio library is now thread-safe, or at least
2827 as thread-safe as the underlying library is. A long-standing potential
Georg Brandle152a772008-05-24 18:31:28 +00002828 bug occurred if one thread closed a file object while another thread
2829 was reading from or writing to the object. In 2.6 file objects
2830 have a reference count, manipulated by the
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002831 :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount`
Georg Brandle152a772008-05-24 18:31:28 +00002832 functions. File objects can't be closed unless the reference count
2833 is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL
2834 is still held, before carrying out an I/O operation using the
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002835 ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called
2836 immediately after the GIL is re-acquired.
2837 (Contributed by Antoine Pitrou and Gregory P. Smith.)
2838
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002839* Importing modules simultaneously in two different threads no longer
2840 deadlocks; it will now raise an :exc:`ImportError`. A new API
2841 function, :cfunc:`PyImport_ImportModuleNoBlock`, will look for a
2842 module in ``sys.modules`` first, then try to import it after
2843 acquiring an import lock. If the import lock is held by another
2844 thread, the :exc:`ImportError` is raised.
2845 (Contributed by Christian Heimes.)
2846
Georg Brandle152a772008-05-24 18:31:28 +00002847* Several functions return information about the platform's
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002848 floating-point support. :cfunc:`PyFloat_GetMax` returns
2849 the maximum representable floating point value,
Georg Brandle152a772008-05-24 18:31:28 +00002850 and :cfunc:`PyFloat_GetMin` returns the minimum
2851 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002852 containing more information from the :file:`float.h` file, such as
2853 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
2854 (smallest difference between 1.0 and the next largest value
2855 representable), and several others.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002856 (Contributed by Christian Heimes; :issue:`1534`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002857
Andrew M. Kuchlingd6b1eaf2008-06-20 02:05:57 +00002858* C functions and methods that use
2859 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
2860 have a :meth:`__complex__` method. In particular, the functions in the
2861 :mod:`cmath` module will now accept objects with this method.
2862 This is a backport of a Python 3.0 change.
2863 (Contributed by Mark Dickinson; :issue:`1675423`.)
2864
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002865* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00002866 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002867 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002868 (Contributed by Christian Heimes; :issue:`1635`.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002869
Georg Brandle152a772008-05-24 18:31:28 +00002870* Many C extensions define their own little macro for adding
2871 integers and strings to the module's dictionary in the
2872 ``init*`` function. Python 2.6 finally defines standard macros
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002873 for adding values to a module, :cmacro:`PyModule_AddStringMacro`
Georg Brandle152a772008-05-24 18:31:28 +00002874 and :cmacro:`PyModule_AddIntMacro()`. (Contributed by
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002875 Christian Heimes.)
2876
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002877* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
2878 they are macros,
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00002879 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002880 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
Georg Brandle152a772008-05-24 18:31:28 +00002881 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002882 The mixed-case macros are still available
2883 in Python 2.6 for backward compatibility.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002884 (:issue:`1629`)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002885
Georg Brandle152a772008-05-24 18:31:28 +00002886* Distutils now places C extensions it builds in a
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002887 different directory when running on a debug version of Python.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002888 (Contributed by Collin Winter; :issue:`1530959`.)
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002889
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002890* Several basic data types, such as integers and strings, maintain
2891 internal free lists of objects that can be re-used. The data
2892 structures for these free lists now follow a naming convention: the
2893 variable is always named ``free_list``, the counter is always named
2894 ``numfree``, and a macro :cmacro:`Py<typename>_MAXFREELIST` is
2895 always defined.
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002896
Andrew M. Kuchlingf68b5532008-04-09 01:08:32 +00002897* A new Makefile target, "make check", prepares the Python source tree
Georg Brandle152a772008-05-24 18:31:28 +00002898 for making a patch: it fixes trailing whitespace in all modified
Andrew M. Kuchlingf68b5532008-04-09 01:08:32 +00002899 ``.py`` files, checks whether the documentation has been changed,
2900 and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files
2901 have been updated.
2902 (Contributed by Brett Cannon.)
2903
Andrew M. Kuchling57ce0542008-04-21 02:14:24 +00002904 Another new target, "make profile-opt", compiles a Python binary
2905 using GCC's profile-guided optimization. It compiles Python with
2906 profiling enabled, runs the test suite to obtain a set of profiling
2907 results, and then compiles using these results for optimization.
2908 (Contributed by Gregory P. Smith.)
2909
Georg Brandlb19be572007-12-29 10:57:00 +00002910.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002911
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002912Port-Specific Changes: Windows
2913-----------------------------------
2914
Christian Heimes7e3ab452008-05-04 11:50:53 +00002915* The support for Windows 95, 98, ME and NT4 has been dropped.
2916 Python 2.6 requires at least Windows 2000 SP4.
2917
Georg Brandle152a772008-05-24 18:31:28 +00002918* The :mod:`msvcrt` module now supports
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002919 both the normal and wide char variants of the console I/O
Georg Brandle152a772008-05-24 18:31:28 +00002920 API. The :func:`getwch` function reads a keypress and returns a Unicode
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002921 value, as does the :func:`getwche` function. The :func:`putwch` function
2922 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00002923 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002924
Georg Brandle152a772008-05-24 18:31:28 +00002925* :func:`os.path.expandvars` will now expand environment variables
2926 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00002927 user's home directory path. (Contributed by Josiah Carlson.)
2928
Georg Brandle152a772008-05-24 18:31:28 +00002929* The :mod:`socket` module's socket objects now have an
2930 :meth:`ioctl` method that provides a limited interface to the
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00002931 :cfunc:`WSAIoctl` system interface.
2932
Georg Brandle152a772008-05-24 18:31:28 +00002933* The :mod:`_winreg` module now has a function,
2934 :func:`ExpandEnvironmentStrings`,
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002935 that expands environment variable references such as ``%NAME%``
2936 in an input string. The handle objects provided by this
Georg Brandle152a772008-05-24 18:31:28 +00002937 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00002938 in :keyword:`with` statements. (Contributed by Christian Heimes.)
2939
Georg Brandle152a772008-05-24 18:31:28 +00002940 :mod:`_winreg` also has better support for x64 systems,
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002941 exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`,
2942 and :func:`QueryReflectionKey` functions, which enable and disable
2943 registry reflection for 32-bit processes running on 64-bit systems.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00002944 (:issue:`1753245`)
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002945
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002946* The :mod:`msilib` module's :class:`Record` object
2947 gained :meth:`GetInteger` and :meth:`GetString` methods that
2948 return field values as an integer or a string.
Andrew M. Kuchling6ba873c2008-06-20 23:43:12 +00002949 (Contributed by Floris Bruynooghe; :issue:`2125`.)
Andrew M. Kuchling7b2e2df2008-06-20 11:39:54 +00002950
Georg Brandle152a772008-05-24 18:31:28 +00002951* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
Christian Heimesff6cc6b2008-01-17 23:01:44 +00002952 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
2953 were moved into the PC/ directory. The new PCbuild directory supports
2954 cross compilation for X64, debug builds and Profile Guided Optimization
2955 (PGO). PGO builds are roughly 10% faster than normal builds.
2956 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
2957 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002958
Georg Brandlb19be572007-12-29 10:57:00 +00002959.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002960
Andrew M. Kuchlingb5a40dd2008-06-05 23:35:31 +00002961Port-Specific Changes: MacOS X
2962-----------------------------------
2963
2964* When compiling a framework build of Python, you can now specify the
2965 framework name to be used by providing the
2966 :option:`--with-framework-name=` option to the
2967 :program:`configure` script.
2968
2969.. ======================================================================
2970
Georg Brandl8ec7f652007-08-15 14:28:01 +00002971
2972.. _section-other:
2973
2974Other Changes and Fixes
2975=======================
2976
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002977As usual, there were a bunch of other improvements and bugfixes
2978scattered throughout the source tree. A search through the change
2979logs finds there were XXX patches applied and YYY bugs fixed between
2980Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002981
2982Some of the more notable changes are:
2983
Georg Brandle152a772008-05-24 18:31:28 +00002984* It's now possible to prevent Python from writing any :file:`.pyc`
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002985 or :file:`.pyo` files by either supplying the :option:`-B` switch
2986 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
2987 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00002988 are also used to set the :data:`sys.dont_write_bytecode` attribute;
2989 Python code can change this variable to control whether bytecode
2990 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002991 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002992
Georg Brandlb19be572007-12-29 10:57:00 +00002993.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002994
2995
2996Porting to Python 2.6
2997=====================
2998
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002999This section lists previously described changes and other bugfixes
3000that may require changes to your code:
Georg Brandl8ec7f652007-08-15 14:28:01 +00003001
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00003002* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00003003 now clears any existing contents of the deque
3004 before adding elements from the iterable. This change makes the
Georg Brandle152a772008-05-24 18:31:28 +00003005 behavior match that of ``list.__init__()``.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00003006
Georg Brandle152a772008-05-24 18:31:28 +00003007* The :class:`Decimal` constructor now accepts leading and trailing
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00003008 whitespace when passed a string. Previously it would raise an
3009 :exc:`InvalidOperation` exception. On the other hand, the
3010 :meth:`create_decimal` method of :class:`Context` objects now
Georg Brandle152a772008-05-24 18:31:28 +00003011 explicitly disallows extra whitespace, raising a
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00003012 :exc:`ConversionSyntax` exception.
3013
Georg Brandle152a772008-05-24 18:31:28 +00003014* Due to an implementation accident, if you passed a file path to
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00003015 the built-in :func:`__import__` function, it would actually import
Georg Brandle152a772008-05-24 18:31:28 +00003016 the specified file. This was never intended to work, however, and
3017 the implementation now explicitly checks for this case and raises
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00003018 an :exc:`ImportError`.
3019
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00003020* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule`
Georg Brandle152a772008-05-24 18:31:28 +00003021 functions now default to absolute imports, not relative imports.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00003022 This will affect C extensions that import other modules.
3023
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00003024* The :mod:`socket` module exception :exc:`socket.error` now inherits
3025 from :exc:`IOError`. Previously it wasn't a subclass of
3026 :exc:`StandardError` but now it is, through :exc:`IOError`.
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00003027 (Implemented by Gregory P. Smith; :issue:`1706815`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00003028
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00003029* The :mod:`xmlrpclib` module no longer automatically converts
Georg Brandle152a772008-05-24 18:31:28 +00003030 :class:`datetime.date` and :class:`datetime.time` to the
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00003031 :class:`xmlrpclib.DateTime` type; the conversion semantics were
3032 not necessarily correct for all applications. Code using
Georg Brandle152a772008-05-24 18:31:28 +00003033 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00003034 instances. (:issue:`1330538`)
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00003035
Georg Brandle152a772008-05-24 18:31:28 +00003036* (3.0-warning mode) The :class:`Exception` class now warns
3037 when accessed using slicing or index access; having
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00003038 :class:`Exception` behave like a tuple is being phased out.
3039
3040* (3.0-warning mode) inequality comparisons between two dictionaries
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00003041 or two objects that don't implement comparison methods are reported
3042 as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2``
3043 is being phased out.
Georg Brandle152a772008-05-24 18:31:28 +00003044
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00003045 Comparisons between cells, which are an implementation detail of Python's
3046 scoping rules, also cause warnings because such comparisons are forbidden
3047 entirely in 3.0.
3048
Georg Brandlb19be572007-12-29 10:57:00 +00003049.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00003050
3051
3052.. _acks:
3053
3054Acknowledgements
3055================
3056
3057The author would like to thank the following people for offering suggestions,
Georg Brandle152a772008-05-24 18:31:28 +00003058corrections and assistance with various drafts of this article:
Andrew M. Kuchling17f84292008-04-10 21:29:01 +00003059Georg Brandl, Jim Jewett.
Georg Brandl8ec7f652007-08-15 14:28:01 +00003060