blob: d4b903991ecf62f7c0ffaa5b572c593db146b9bb [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001****************************
2 What's New in Python 2.6
3****************************
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:
13
14 * 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.
17
18 * 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.
21
22 * 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.)
27
28 * 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.
31
32 * 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.
36
37 * You can comment out your additions if you like, but it's not
38 necessary (especially when a final release is some months away).
39
40 * Credit the author of a patch or bugfix. Just the name is
41 sufficient; the e-mail address isn't necessary.
42
43 * It's helpful to add the bug/patch number as a comment:
44
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +000045 .. Patch 12345
Georg Brandlb19be572007-12-29 10:57:00 +000046 XXX Describe the transmogrify() function added to the socket
47 module.
48 (Contributed by P.Y. Developer.)
49
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +000050 This saves the maintainer the effort of going through the SVN logs
Georg Brandlb19be572007-12-29 10:57:00 +000051 when researching a change.
Georg Brandl8ec7f652007-08-15 14:28:01 +000052
53This article explains the new features in Python 2.6. No release date for
54Python 2.6 has been set; it will probably be released in mid 2008.
55
56This article doesn't attempt to provide a complete specification of the new
57features, but instead provides a convenient overview. For full details, you
58should refer to the documentation for Python 2.6. If you want to understand the
59complete implementation and design rationale, refer to the PEP for a particular
60new feature.
61
Georg Brandlb19be572007-12-29 10:57:00 +000062.. Compare with previous release in 2 - 3 sentences here.
63 add hyperlink when the documentation becomes available online.
Georg Brandl8ec7f652007-08-15 14:28:01 +000064
Georg Brandlb19be572007-12-29 10:57:00 +000065.. ========================================================================
66.. Large, PEP-level features and changes should be described here.
67.. Should there be a new section here for 3k migration?
68.. Or perhaps a more general section describing module changes/deprecation?
69.. ========================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +000070
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000071Python 3.0
72================
73
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000074The development cycle for Python 2.6 also saw the release of the first
75alphas of Python 3.0, and the development of 3.0 has influenced
76a number of features in 2.6.
77
78Python 3.0 is a far-ranging redesign of Python that breaks
79compatibility with the 2.x series. This means that existing Python
80code will need a certain amount of conversion in order to run on
81Python 3.0. However, not all the changes in 3.0 necessarily break
82compatibility. In cases where new features won't cause existing code
83to break, they've been backported to 2.6 and are described in this
84document in the appropriate place. Some of the 3.0-derived features
85are:
86
87* A :meth:`__complex__` method for converting objects to a complex number.
88* Alternate syntax for catching exceptions: ``except TypeError as exc``.
89* The addition of :func:`functools.reduce` as a synonym for the built-in
90 :func:`reduce` function.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000091
92A new command-line switch, :option:`-3`, enables warnings
93about features that will be removed in Python 3.0. You can run code
94with this switch to see how much work will be necessary to port
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000095code to 3.0. The value of this switch is available
Georg Brandld5b635f2008-03-25 08:29:14 +000096to Python code as the boolean variable :data:`sys.py3kwarning`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000097and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000098
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +000099Python 3.0 adds several new built-in functions and change the
100semantics of some existing built-ins. Entirely new functions such as
101:func:`bin` have simply been added to Python 2.6, but existing
102built-ins haven't been changed; instead, the :mod:`future_builtins`
103module has versions with the new 3.0 semantics. Code written to be
104compatible with 3.0 can do ``from future_builtins import hex, map``
105as necessary.
106
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000107.. seealso::
108
109 The 3xxx series of PEPs, which describes the development process for
110 Python 3.0 and various features that have been accepted, rejected,
111 or are still under consideration.
112
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000113
114Development Changes
115==================================================
116
117While 2.6 was being developed, the Python development process
118underwent two significant changes: the developer group
119switched from SourceForge's issue tracker to a customized
120Roundup installation, and the documentation was converted from
121LaTeX to reStructured Text.
122
123
124New Issue Tracker: Roundup
125--------------------------------------------------
126
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000127For a long time, the Python developers have been growing increasingly
128annoyed by SourceForge's bug tracker. SourceForge's hosted solution
129doesn't permit much customization; for example, it wasn't possible to
130customize the life cycle of issues.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000131
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000132The infrastructure committee of the Python Software Foundation
133therefore posted a call for issue trackers, asking volunteers to set
134up different products and import some of the bugs and patches from
135SourceForge. Four different trackers were examined: Atlassian's `Jira
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000136<http://www.atlassian.com/software/jira/>`__,
137`Launchpad <http://www.launchpad.net>`__,
138`Roundup <http://roundup.sourceforge.net/>`__, and
139Trac <http://trac.edgewall.org/>`__.
140The committee eventually settled on Jira
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000141and Roundup as the two candidates. Jira is a commercial product that
142offers a no-cost hosted instance to free-software projects; Roundup
143is an open-source project that requires volunteers
144to administer it and a server to host it.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000145
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000146After posting a call for volunteers, a new Roundup installation was
147set up at http://bugs.python.org. One installation of Roundup can
148host multiple trackers, and this server now also hosts issue trackers
149for Jython and for the Python web site. It will surely find
150other uses in the future.
151
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000152Hosting is kindly provided by `Upfront Systems <http://www.upfrontsystems.co.za/>`__ of Stellenbosch, South Africa. Martin von Loewis put a
153lot of effort into importing existing bugs and patches from
154SourceForge; his scripts for this import operation are at
155http://svn.python.org/view/tracker/importer/.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000156
157.. seealso::
158
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000159 http://bugs.python.org
160 The Python bug tracker.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000161
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000162 http://bugs.jython.org:
163 The Jython bug tracker.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000164
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000165 http://roundup.sourceforge.net/
166 Roundup downloads and documentation.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000167
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000168
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000169New Documentation Format: ReStructured Text Using Sphinx
170-----------------------------------------------------------
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000171
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000172Since the Python project's inception around 1989, the documentation
173had been written using LaTeX. At that time, most documentation was
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000174printed out for later study, not viewed online. LaTeX was widely used
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000175because it provided attractive printed output while remaining
176straightforward to write, once the basic rules of the markup have been
177learned.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000178
179LaTeX is still used today for writing technical publications destined
180for printing, but the landscape for programming tools has shifted. We
181no longer print out reams of documentation; instead, we browse through
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000182it online and HTML has become the most important format to support.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000183Unfortunately, converting LaTeX to HTML is fairly complicated, and
184Fred L. Drake Jr., the Python documentation editor for many years,
185spent a lot of time wrestling the conversion process into shape.
186Occasionally people would suggest converting the documentation into
187SGML or, later, XML, but performing a good conversion is a major task
188and no one pursued the task to completion.
189
190During the 2.6 development cycle, Georg Brandl put a substantial
191effort into building a new toolchain called Sphinx
192for processing the documentation.
193The input format is reStructured Text,
194a markup commonly used in the Python community that supports
195custom extensions and directives. Sphinx concentrates
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000196on HTML output, producing attractively styled
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000197and modern HTML, though printed output is still supported through
198conversion to LaTeX. Sphinx is a standalone package that
199can be used in documenting other projects.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000200
201.. seealso::
202
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000203 :ref:`documenting-index`
204 Describes how to write for Python's documentation.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000205
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000206 `Sphinx <http://sphinx.pocoo.org/>`__
207 Documentation and code for the Sphinx toolchain.
208
209 `Docutils <http://docutils.sf.net>`__
210 The underlying reStructured Text parser and toolset.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000211
212
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000213PEP 343: The 'with' statement
214=============================
215
216The previous version, Python 2.5, added the ':keyword:`with`'
217statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000218import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000219be specially enabled; this means that :keyword:`with` is now always a
220keyword. The rest of this section is a copy of the corresponding
221section from "What's New in Python 2.5" document; if you read
222it back when Python 2.5 came out, you can skip the rest of this
223section.
224
225The ':keyword:`with`' statement clarifies code that previously would use
226``try...finally`` blocks to ensure that clean-up code is executed. In this
227section, I'll discuss the statement as it will commonly be used. In the next
228section, I'll examine the implementation details and show how to write objects
229for use with this statement.
230
231The ':keyword:`with`' statement is a new control-flow structure whose basic
232structure is::
233
234 with expression [as variable]:
235 with-block
236
237The expression is evaluated, and it should result in an object that supports the
238context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
239methods.
240
241The object's :meth:`__enter__` is called before *with-block* is executed and
242therefore can run set-up code. It also may return a value that is bound to the
243name *variable*, if given. (Note carefully that *variable* is *not* assigned
244the result of *expression*.)
245
246After execution of the *with-block* is finished, the object's :meth:`__exit__`
247method is called, even if the block raised an exception, and can therefore run
248clean-up code.
249
250Some standard Python objects now support the context management protocol and can
251be used with the ':keyword:`with`' statement. File objects are one example::
252
253 with open('/etc/passwd', 'r') as f:
254 for line in f:
255 print line
256 ... more processing code ...
257
258After this statement has executed, the file object in *f* will have been
259automatically closed, even if the :keyword:`for` loop raised an exception part-
260way through the block.
261
262.. note::
263
264 In this case, *f* is the same object created by :func:`open`, because
265 :meth:`file.__enter__` returns *self*.
266
267The :mod:`threading` module's locks and condition variables also support the
268':keyword:`with`' statement::
269
270 lock = threading.Lock()
271 with lock:
272 # Critical section of code
273 ...
274
275The lock is acquired before the block is executed and always released once the
276block is complete.
277
278The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
279to save and restore the current decimal context, which encapsulates the desired
280precision and rounding characteristics for computations::
281
282 from decimal import Decimal, Context, localcontext
283
284 # Displays with default precision of 28 digits
285 v = Decimal('578')
286 print v.sqrt()
287
288 with localcontext(Context(prec=16)):
289 # All code in this block uses a precision of 16 digits.
290 # The original context is restored on exiting the block.
291 print v.sqrt()
292
293
294.. _new-26-context-managers:
295
296Writing Context Managers
297------------------------
298
299Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
300people will only use ':keyword:`with`' in company with existing objects and
301don't need to know these details, so you can skip the rest of this section if
302you like. Authors of new objects will need to understand the details of the
303underlying implementation and should keep reading.
304
305A high-level explanation of the context management protocol is:
306
307* The expression is evaluated and should result in an object called a "context
308 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
309 methods.
310
311* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000312 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000313 discarded.
314
315* The code in *BLOCK* is executed.
316
317* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
318 is called with the exception details, the same values returned by
319 :func:`sys.exc_info`. The method's return value controls whether the exception
320 is re-raised: any false value re-raises the exception, and ``True`` will result
321 in suppressing it. You'll only rarely want to suppress the exception, because
322 if you do the author of the code containing the ':keyword:`with`' statement will
323 never realize anything went wrong.
324
325* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
326 called, but *type*, *value*, and *traceback* are all ``None``.
327
328Let's think through an example. I won't present detailed code but will only
329sketch the methods necessary for a database that supports transactions.
330
331(For people unfamiliar with database terminology: a set of changes to the
332database are grouped into a transaction. Transactions can be either committed,
333meaning that all the changes are written into the database, or rolled back,
334meaning that the changes are all discarded and the database is unchanged. See
335any database textbook for more information.)
336
337Let's assume there's an object representing a database connection. Our goal will
338be to let the user write code like this::
339
340 db_connection = DatabaseConnection()
341 with db_connection as cursor:
342 cursor.execute('insert into ...')
343 cursor.execute('delete from ...')
344 # ... more operations ...
345
346The transaction should be committed if the code in the block runs flawlessly or
347rolled back if there's an exception. Here's the basic interface for
348:class:`DatabaseConnection` that I'll assume::
349
350 class DatabaseConnection:
351 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000352 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000353 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000354 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000355 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000356 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000357 "Rolls back current transaction"
358
359The :meth:`__enter__` method is pretty easy, having only to start a new
360transaction. For this application the resulting cursor object would be a useful
361result, so the method will return it. The user can then add ``as cursor`` to
362their ':keyword:`with`' statement to bind the cursor to a variable name. ::
363
364 class DatabaseConnection:
365 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000366 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000367 # Code to start a new transaction
368 cursor = self.cursor()
369 return cursor
370
371The :meth:`__exit__` method is the most complicated because it's where most of
372the work has to be done. The method has to check if an exception occurred. If
373there was no exception, the transaction is committed. The transaction is rolled
374back if there was an exception.
375
376In the code below, execution will just fall off the end of the function,
377returning the default value of ``None``. ``None`` is false, so the exception
378will be re-raised automatically. If you wished, you could be more explicit and
379add a :keyword:`return` statement at the marked location. ::
380
381 class DatabaseConnection:
382 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000383 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000384 if tb is None:
385 # No exception, so commit
386 self.commit()
387 else:
388 # Exception occurred, so rollback.
389 self.rollback()
390 # return False
391
392
393.. _module-contextlib:
394
395The contextlib module
396---------------------
397
398The new :mod:`contextlib` module provides some functions and a decorator that
399are useful for writing objects for use with the ':keyword:`with`' statement.
400
401The decorator is called :func:`contextmanager`, and lets you write a single
402generator function instead of defining a new class. The generator should yield
403exactly one value. The code up to the :keyword:`yield` will be executed as the
404:meth:`__enter__` method, and the value yielded will be the method's return
405value that will get bound to the variable in the ':keyword:`with`' statement's
406:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
407executed in the :meth:`__exit__` method. Any exception raised in the block will
408be raised by the :keyword:`yield` statement.
409
410Our database example from the previous section could be written using this
411decorator as::
412
413 from contextlib import contextmanager
414
415 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000416 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000417 cursor = connection.cursor()
418 try:
419 yield cursor
420 except:
421 connection.rollback()
422 raise
423 else:
424 connection.commit()
425
426 db = DatabaseConnection()
427 with db_transaction(db) as cursor:
428 ...
429
430The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
431that combines a number of context managers so you don't need to write nested
432':keyword:`with`' statements. In this example, the single ':keyword:`with`'
433statement both starts a database transaction and acquires a thread lock::
434
435 lock = threading.Lock()
436 with nested (db_transaction(db), lock) as (cursor, locked):
437 ...
438
439Finally, the :func:`closing(object)` function returns *object* so that it can be
440bound to a variable, and calls ``object.close`` at the end of the block. ::
441
442 import urllib, sys
443 from contextlib import closing
444
445 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
446 for line in f:
447 sys.stdout.write(line)
448
449
450.. seealso::
451
452 :pep:`343` - The "with" statement
453 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
454 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
455 ':keyword:`with`' statement, which can be helpful in learning how the statement
456 works.
457
458 The documentation for the :mod:`contextlib` module.
459
Georg Brandlb19be572007-12-29 10:57:00 +0000460.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000461
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000462.. _pep-0366:
463
464PEP 366: Explicit Relative Imports From a Main Module
465============================================================
466
467Python's :option:`-m` switch allows running a module as a script.
468When you ran a module that was located inside a package, relative
469imports didn't work correctly.
470
471The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
472When present, relative imports will be relative to the value of this
473attribute instead of the :attr:`__name__` attribute. PEP 302-style
474importers can then set :attr:`__package__`. The :mod:`runpy` module
475that implements the :option:`-m` switch now does this, so relative imports
476can now be used in scripts running from inside a package.
477
Georg Brandlb19be572007-12-29 10:57:00 +0000478.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000479
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000480.. ::
481
482 .. _pep-0370:
483
484 PEP 370: XXX
485 =====================================================
486
487 When you run Python, the module search page ``sys.modules`` usually
488 includes a directory whose path ends in ``"site-packages"``. This
489 directory is intended to hold locally-installed packages available to
490 all users on a machine or using a particular site installation.
491
492 Python 2.6 introduces a convention for user-specific site directories.
493
494 .. seealso::
495
496 :pep:`370` - XXX
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000497 PEP written by XXX; implemented by Christian Heimes.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000498
499
500.. ======================================================================
501
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000502.. _pep-3101:
503
504PEP 3101: Advanced String Formatting
505=====================================================
506
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000507In Python 3.0, the `%` operator is supplemented by a more powerful
508string formatting method, :meth:`format`. Support for the
509:meth:`format` method has been backported to Python 2.6.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000510
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000511In 2.6, both 8-bit and Unicode strings have a `.format()` method that
512treats the string as a template and takes the arguments to be formatted.
513The formatting template uses curly brackets (`{`, `}`) as special characters::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000514
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000515 # Substitute positional argument 0 into the string.
516 "User ID: {0}".format("root") -> "User ID: root"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000517
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000518 # Use the named keyword arguments
519 uid = 'root'
520
521 'User ID: {uid} Last seen: {last_login}'.format(uid='root',
522 last_login = '5 Mar 2008 07:20') ->
523 'User ID: root Last seen: 5 Mar 2008 07:20'
524
525Curly brackets can be escaped by doubling them::
526
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000527 format("Empty dict: {{}}") -> "Empty dict: {}"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000528
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000529Field names can be integers indicating positional arguments, such as
530``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
531supply compound field names that read attributes or access dictionary keys::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000532
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000533 import sys
534 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) ->
535 'Platform: darwin\n
536 Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) \n
537 [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
538
539 import mimetypes
540 'Content-type: {0[.mp4]}'.format(mimetypes.types_map) ->
541 'Content-type: video/mp4'
542
543Note that when using dictionary-style notation such as ``[.mp4]``, you
544don't need to put any quotation marks around the string; it will look
545up the value using ``.mp4`` as the key. Strings beginning with a
546number will be converted to an integer. You can't write more
547complicated expressions inside a format string.
548
549So far we've shown how to specify which field to substitute into the
550resulting string. The precise formatting used is also controllable by
Georg Brandl859043c2008-03-21 17:19:29 +0000551adding a colon followed by a format specifier. For example::
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000552
553 # Field 0: left justify, pad to 15 characters
554 # Field 1: right justify, pad to 6 characters
555 fmt = '{0:15} ${1:>6}'
556 fmt.format('Registration', 35) ->
557 'Registration $ 35'
558 fmt.format('Tutorial', 50) ->
559 'Tutorial $ 50'
560 fmt.format('Banquet', 125) ->
561 'Banquet $ 125'
562
Georg Brandl859043c2008-03-21 17:19:29 +0000563Format specifiers can reference other fields through nesting::
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000564
565 fmt = '{0:{1}}'
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000566 fmt.format('Invoice #1234', 15) ->
567 'Invoice #1234 '
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000568 width = 35
569 fmt.format('Invoice #1234', width) ->
570 'Invoice #1234 '
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000571
572The alignment of a field within the desired width can be specified:
573
574================ ============================================
575Character Effect
576================ ============================================
577< (default) Left-align
578> Right-align
579^ Center
580= (For numeric types only) Pad after the sign.
581================ ============================================
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000582
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000583Format specifiers can also include a presentation type, which
584controls how the value is formatted. For example, floating-point numbers
585can be formatted as a general number or in exponential notation:
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000586
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000587 >>> '{0:g}'.format(3.75)
588 '3.75'
589 >>> '{0:e}'.format(3.75)
590 '3.750000e+00'
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000591
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000592A variety of presentation types are available. Consult the 2.6
593documentation for a complete list (XXX add link, once it's in the 2.6
594docs), but here's a sample::
595
596 'b' - Binary. Outputs the number in base 2.
597 'c' - Character. Converts the integer to the corresponding
598 Unicode character before printing.
599 'd' - Decimal Integer. Outputs the number in base 10.
600 'o' - Octal format. Outputs the number in base 8.
601 'x' - Hex format. Outputs the number in base 16, using lower-
602 case letters for the digits above 9.
603 'e' - Exponent notation. Prints the number in scientific
604 notation using the letter 'e' to indicate the exponent.
605 'g' - General format. This prints the number as a fixed-point
606 number, unless the number is too large, in which case
607 it switches to 'e' exponent notation.
608 'n' - Number. This is the same as 'g', except that it uses the
609 current locale setting to insert the appropriate
610 number separator characters.
611 '%' - Percentage. Multiplies the number by 100 and displays
612 in fixed ('f') format, followed by a percent sign.
613
614Classes and types can define a __format__ method to control how they're
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000615formatted. It receives a single argument, the format specifier::
616
617 def __format__(self, format_spec):
618 if isinstance(format_spec, unicode):
619 return unicode(str(self))
620 else:
621 return str(self)
622
623There's also a format() built-in that will format a single value. It calls
624the type's :meth:`__format__` method with the provided specifier::
625
626 >>> format(75.6564, '.2f')
627 '75.66'
628
629.. seealso::
630
631 :pep:`3101` - Advanced String Formatting
632 PEP written by Talin.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000633
634.. ======================================================================
635
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000636.. _pep-3105:
637
638PEP 3105: ``print`` As a Function
639=====================================================
640
641The ``print`` statement becomes the :func:`print` function in Python 3.0.
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000642Making :func:`print` a function makes it easier to change
643by doing 'def print(...)' or importing a new function from somewhere else.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000644
645Python 2.6 has a ``__future__`` import that removes ``print`` as language
646syntax, letting you use the functional form instead. For example::
647
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000648 from __future__ import print_function
649 print('# of entries', len(dictionary), file=sys.stderr)
650
651The signature of the new function is::
652
653 def print(*args, sep=' ', end='\n', file=None)
654
655The parameters are:
656
657 * **args**: positional arguments whose values will be printed out.
658 * **sep**: the separator, which will be printed between arguments.
659 * **end**: the ending text, which will be printed after all of the
660 arguments have been output.
661 * **file**: the file object to which the output will be sent.
662
663.. seealso::
664
Eric Smith33dd0942008-03-20 23:04:04 +0000665 :pep:`3105` - Make print a function
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000666 PEP written by Georg Brandl.
667
668.. ======================================================================
669
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000670.. _pep-3110:
671
672PEP 3110: Exception-Handling Changes
673=====================================================
674
675One error that Python programmers occasionally make
676is the following::
677
678 try:
679 ...
680 except TypeError, ValueError:
681 ...
682
683The author is probably trying to catch both
684:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
685actually does something different: it will catch
686:exc:`TypeError` and bind the resulting exception object
687to the local name ``"ValueError"``. The correct code
688would have specified a tuple::
689
690 try:
691 ...
692 except (TypeError, ValueError):
693 ...
694
695This error is possible because the use of the comma here is ambiguous:
696does it indicate two different nodes in the parse tree, or a single
697node that's a tuple.
698
699Python 3.0 changes the syntax to make this unambiguous by replacing
700the comma with the word "as". To catch an exception and store the
701exception object in the variable ``exc``, you must write::
702
703 try:
704 ...
705 except TypeError as exc:
706 ...
707
708Python 3.0 will only support the use of "as", and therefore interprets
709the first example as catching two different exceptions. Python 2.6
710supports both the comma and "as", so existing code will continue to
711work.
712
713.. seealso::
714
715 :pep:`3110` - Catching Exceptions in Python 3000
716 PEP written and implemented by Collin Winter.
717
Georg Brandlb19be572007-12-29 10:57:00 +0000718.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000719
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000720.. _pep-3112:
721
722PEP 3112: Byte Literals
723=====================================================
724
725Python 3.0 adopts Unicode as the language's fundamental string type, and
726denotes 8-bit literals differently, either as ``b'string'``
727or using a :class:`bytes` constructor. For future compatibility,
728Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
729and it also supports the ``b''`` notation.
730
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +0000731There's also a ``__future__`` import that causes all string literals
732to become Unicode strings. This means that ``\u`` escape sequences
733can be used to include Unicode characters.
734
735XXX give example
736
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000737.. seealso::
738
739 :pep:`3112` - Bytes literals in Python 3000
740 PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
741
742.. ======================================================================
743
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000744.. _pep-3116:
745
746PEP 3116: New I/O Library
747=====================================================
748
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +0000749Python's built-in file objects support a number of methods, but
750file-like objects don't necessarily support all of them. Objects that
751imitate files usually support :meth:`read` and :meth:`write`, but they
752may not support :meth:`readline`. Python 3.0 introduces a layered I/O
753library in the :mod:`io` module that separates buffering and
754text-handling features from the fundamental read and write operations.
755
756There are three levels of abstract base classes provided by
757the :mod:`io` module:
758
759* :class:`RawIOBase`: defines raw I/O operations: :meth:`read`,
760 :meth:`readinto`,
761 :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
762 and :meth:`close`.
763 Most of the methods of this class will often map to a single system call.
764 There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable`
765 methods for determining what operations a given object will allow.
766
767 Python 3.0 has concrete implementations of this class for files and
768 sockets, but Python 2.6 hasn't restructured its file and socket objects
769 in this way.
770
771 .. XXX should 2.6 register them in io.py?
772
773* :class:`BufferedIOBase`: is an abstract base class that
774 buffers data in memory to reduce the number of
775 system calls used, making I/O processing more efficient.
776 It supports all of the methods of :class:`RawIOBase`,
777 and adds a :attr:`raw` attribute holding the underlying raw object.
778
779 There are four concrete classes implementing this ABC:
780 :class:`BufferedWriter` and
781 :class:`BufferedReader` for objects that only support
782 writing or reading and don't support random access,
783 :class:`BufferedRandom` for objects that support the :meth:`seek` method
784 for random access,
785 and :class:`BufferedRWPair` for objects such as TTYs that have
786 both read and write operations that act upon unconnected streams of data.
787
788* :class:`TextIOBase`: Provides functions for reading and writing
789 strings (remember, strings will be Unicode in Python 3.0),
790 and supporting universal newlines. :class:`TextIOBase` defines
791 the :meth:`readline` method and supports iteration upon
792 objects.
793
794 There are two concrete implementations. :class:`TextIOWrapper`
795 wraps a buffered I/O object, supporting all of the methods for
796 text I/O and adding a :attr:`buffer` attribute for access
797 to the underlying object. :class:`StringIO` simply buffers
798 everything in memory without ever writing anything to disk.
799
800 (In current 2.6 alpha releases, :class:`io.StringIO` is implemented in
801 pure Python, so it's pretty slow. You should therefore stick with the
802 existing :mod:`StringIO` module or :mod:`cStringIO` for now. At some
803 point Python 3.0's :mod:`io` module will be rewritten into C for speed,
804 and perhaps the C implementation will be backported to the 2.x releases.)
805
806 .. XXX check before final release: is io.py still written in Python?
807
808In Python 2.6, the underlying implementations haven't been
809restructured to build on top of the :mod:`io` module's classes. The
810module is being provided to make it easier to write code that's
811forward-compatible with 3.0, and to save developers the effort of writing
812their own implementations of buffering and text I/O.
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000813
814.. seealso::
815
816 :pep:`3116` - New I/O
817 PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
818 XXX code written by who?
819
820.. ======================================================================
821
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000822.. _pep-3118:
823
824PEP 3118: Revised Buffer Protocol
825=====================================================
826
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000827The buffer protocol is a C-level API that lets Python types
828exchange pointers into their internal representations. A
829memory-mapped file can be viewed as a buffer of characters, for
830example, and this lets another module such as :mod:`re`
831treat memory-mapped files as a string of characters to be searched.
832
833The primary users of the buffer protocol are numeric-processing
834packages such as NumPy, which can expose the internal representation
835of arrays so that callers can write data directly into an array instead
836of going through a slower API. This PEP updates the buffer protocol in light of experience
837from NumPy development, adding a number of new features
838such as indicating the shape of an array,
839locking memory .
840
841The most important new C API function is
842``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which
843takes an object and a set of flags, and fills in the
844``Py_buffer`` structure with information
845about the object's memory representation. Objects
846can use this operation to lock memory in place
847while an external caller could be modifying the contents,
848so there's a corresponding
849``PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)`` to
850indicate that the external caller is done.
851
852The **flags** argument to :cfunc:`PyObject_GetBuffer` specifies
853constraints upon the memory returned. Some examples are:
854
855 * :const:`PyBUF_WRITABLE` indicates that the memory must be writable.
856
857 * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory.
858
859 * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS`
860 requests a C-contiguous (last dimension varies the fastest) or
861 Fortran-contiguous (first dimension varies the fastest) layout.
862
863.. XXX this feature is not in 2.6 docs yet
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000864
865.. seealso::
866
867 :pep:`3118` - Revising the buffer protocol
Andrew M. Kuchling217057f2008-04-05 15:57:46 +0000868 PEP written by Travis Oliphant and Carl Banks; implemented by
869 Travis Oliphant.
870
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000871
872.. ======================================================================
873
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000874.. _pep-3119:
875
876PEP 3119: Abstract Base Classes
877=====================================================
878
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000879Some object-oriented languages such as Java support interfaces: declarations
880that a class has a given set of methods or supports a given access protocol.
881Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC
882support consists of an :mod:`abc` module containing a metaclass called
883:class:`ABCMeta`, special handling
884of this metaclass by the :func:`isinstance` and :func:`issubclass` built-ins,
885and a collection of basic ABCs that the Python developers think will be widely
886useful.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000887
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000888Let's say you have a particular class and wish to know whether it supports
889dictionary-style access. The phrase "dictionary-style" is vague, however.
890It probably means that accessing items with ``obj[1]`` works.
891Does it imply that setting items with ``obj[2] = value`` works?
892Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items`
893methods? What about the iterative variants such as :meth:`iterkeys`? :meth:`copy`
894and :meth:`update`? Iterating over the object with :func:`iter`?
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000895
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000896Python 2.6 includes a number of different ABCs in the :mod:`collections`
897module. :class:`Iterable` indicates that a class defines :meth:`__iter__`,
898and :class:`Container` means the class supports ``x in y`` expressions
899by defining a :meth:`__contains__` method. The basic dictionary interface of
900getting items, setting items, and
901:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
902:class:`MutableMapping` ABC.
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000903
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000904You can derive your own classes from a particular ABC
905to indicate they support that ABC's interface::
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000906
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000907 import collections
908
909 class Storage(collections.MutableMapping):
910 ...
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000911
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000912
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000913Alternatively, you could write the class without deriving from
914the desired ABC and instead register the class by
915calling the ABC's :meth:`register` method::
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000916
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000917 import collections
918
919 class Storage:
920 ...
921
922 collections.MutableMapping.register(Storage)
923
924For classes that you write, deriving from the ABC is probably clearer.
925The :meth:`register` method is useful when you've written a new
926ABC that can describe an existing type or class, or if you want
927to declare that some third-party class implements an ABC.
928For example, if you defined a :class:`PrintableType` ABC,
929it's legal to do:
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000930
Andrew M. Kuchling21852412008-04-05 18:15:30 +0000931 # Register Python's types
932 PrintableType.register(int)
933 PrintableType.register(float)
934 PrintableType.register(str)
935
936Classes should obey the semantics specified by an ABC, but
937Python can't check this; it's up to the class author to
938understand the ABC's requirements and to implement the code accordingly.
939
940To check whether an object supports a particular interface, you can
941now write::
942
943 def func(d):
944 if not isinstance(d, collections.MutableMapping):
945 raise ValueError("Mapping object expected, not %r" % d)
946
947(Don't feel that you must now begin writing lots of checks as in the
948above example. Python has a strong tradition of duck-typing, where
949explicit type-checking isn't done and code simply calls methods on
950an object, trusting that those methods will be there and raising an
951exception if they aren't. Be judicious in checking for ABCs
952and only do it where it helps.)
953
954You can write your own ABCs by using ``abc.ABCMeta`` as the
955metaclass in a class definition::
956
957 from abc import ABCMeta
958
959 class Drawable():
960 __metaclass__ = ABCMeta
961
962 def draw(self, x, y, scale=1.0):
963 pass
964
965 def draw_doubled(self, x, y):
966 self.draw(x, y, scale=2.0)
967
968
969 class Square(Drawable):
970 def draw(self, x, y, scale):
971 ...
972
973
974In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
975renders the object at twice its size and can be implemented in terms
976of other methods described in :class:`Drawable`. Classes implementing
977this ABC therefore don't need to provide their own implementation
978of :meth:`draw_doubled`, though they can do so. An implementation
979of :meth:`draw` is necessary, though; the ABC can't provide
980a useful generic implementation. You
981can apply the ``@abstractmethod`` decorator to methods such as
982:meth:`draw` that must be implemented; Python will
983then raise an exception for classes that
984don't define the method::
985
986 class Drawable():
987 __metaclass__ = ABCMeta
988
989 @abstractmethod
990 def draw(self, x, y, scale):
991 pass
992
993Note that the exception is only raised when you actually
994try to create an instance of a subclass without the method::
995
996 >>> s=Square()
997 Traceback (most recent call last):
998 File "<stdin>", line 1, in <module>
999 TypeError: Can't instantiate abstract class Square with abstract methods draw
1000 >>>
1001
1002Abstract data attributes can be declared using the ``@abstractproperty`` decorator::
1003
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001004 @abstractproperty
1005 def readonly(self):
1006 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001007
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001008Subclasses must then define a :meth:`readonly` property
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001009
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001010.. seealso::
1011
1012 :pep:`3119` - Introducing Abstract Base Classes
1013 PEP written by Guido van Rossum and Talin.
Andrew M. Kuchling21852412008-04-05 18:15:30 +00001014 Implemented by Guido van Rossum.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001015 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001016
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001017.. ======================================================================
1018
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001019.. _pep-3127:
1020
1021PEP 3127: Integer Literal Support and Syntax
1022=====================================================
1023
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001024Python 3.0 changes the syntax for octal (base-8) integer literals,
1025which are now prefixed by "0o" or "0O" instead of a leading zero, and
1026adds support for binary (base-2) integer literals, signalled by a "0b"
1027or "0B" prefix.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001028
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001029Python 2.6 doesn't drop support for a leading 0 signalling
1030an octal number, but it does add support for "0o" and "0b"::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001031
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001032 >>> 0o21, 2*8 + 1
1033 (17, 17)
1034 >>> 0b101111
1035 47
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001036
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001037The :func:`oct` built-in still returns numbers
1038prefixed with a leading zero, and a new :func:`bin`
1039built-in returns the binary representation for a number::
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001040
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001041 >>> oct(42)
1042 '052'
1043 >>> bin(173)
1044 '0b10101101'
1045
1046The :func:`int` and :func:`long` built-ins will now accept the "0o"
1047and "0b" prefixes when base-8 or base-2 are requested, or when the
1048**base** argument is zero (meaning the base used is determined from
1049the string):
1050
1051 >>> int ('0o52', 0)
1052 42
1053 >>> int('1101', 2)
1054 13
1055 >>> int('0b1101', 2)
1056 13
1057 >>> int('0b1101', 0)
1058 13
1059
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001060
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001061.. seealso::
1062
1063 :pep:`3127` - Integer Literal Support and Syntax
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001064 PEP written by Patrick Maupin; backported to 2.6 by
1065 Eric Smith.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001066
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001067.. ======================================================================
1068
1069.. _pep-3129:
1070
1071PEP 3129: Class Decorators
1072=====================================================
1073
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001074Decorators have been extended from functions to classes. It's now legal to
1075write::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001076
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001077 @foo
1078 @bar
1079 class A:
1080 pass
1081
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001082This is equivalent to::
1083
1084 class A:
1085 pass
1086
1087 A = foo(bar(A))
1088
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001089XXX need to find a good motivating example.
1090
1091.. seealso::
1092
1093 :pep:`3129` - Class Decorators
1094 PEP written by Collin Winter.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001095
1096.. ======================================================================
1097
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001098.. _pep-3141:
1099
1100PEP 3141: A Type Hierarchy for Numbers
1101=====================================================
1102
1103In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001104inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001105This change was backported to 2.6 as the :mod:`numbers` module.
1106
1107The most general ABC is :class:`Number`. It defines no operations at
1108all, and only exists to allow checking if an object is a number by
1109doing ``isinstance(obj, Number)``.
1110
1111Numbers are further divided into :class:`Exact` and :class:`Inexact`.
1112Exact numbers can represent values precisely and operations never
1113round off the results or introduce tiny errors that may break the
Georg Brandl907a7202008-02-22 12:31:45 +00001114commutativity and associativity properties; inexact numbers may
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001115perform such rounding or introduce small errors. Integers, long
1116integers, and rational numbers are exact, while floating-point
1117and complex numbers are inexact.
1118
1119:class:`Complex` is a subclass of :class:`Number`. Complex numbers
1120can undergo the basic operations of addition, subtraction,
1121multiplication, division, and exponentiation, and you can retrieve the
1122real and imaginary parts and obtain a number's conjugate. Python's built-in
1123complex type is an implementation of :class:`Complex`.
1124
1125:class:`Real` further derives from :class:`Complex`, and adds
1126operations that only work on real numbers: :func:`floor`, :func:`trunc`,
1127rounding, taking the remainder mod N, floor division,
1128and comparisons.
1129
1130:class:`Rational` numbers derive from :class:`Real`, have
1131:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +00001132converted to floats. Python 2.6 adds a simple rational-number class,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001133:class:`Fraction`, in the :mod:`fractions` module. (It's called
1134:class:`Fraction` instead of :class:`Rational` to avoid
1135a name clash with :class:`numbers.Rational`.)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001136
1137:class:`Integral` numbers derive from :class:`Rational`, and
1138can be shifted left and right with ``<<`` and ``>>``,
1139combined using bitwise operations such as ``&`` and ``|``,
1140and can be used as array indexes and slice boundaries.
1141
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001142In Python 3.0, the PEP slightly redefines the existing built-ins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001143:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
1144one, :func:`math.trunc`, that's been backported to Python 2.6.
1145:func:`math.trunc` rounds toward zero, returning the closest
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001146:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001147
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001148.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001149
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001150 :pep:`3141` - A Type Hierarchy for Numbers
1151 PEP written by Jeffrey Yasskin.
1152
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001153 `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 +00001154
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001155 `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001156
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001157
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001158The :mod:`fractions` Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001159--------------------------------------------------
1160
1161To fill out the hierarchy of numeric types, a rational-number class
Mark Dickinsond058cd22008-02-10 21:29:51 +00001162has been added as the :mod:`fractions` module. Rational numbers are
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001163represented as a fraction, and can exactly represent
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001164numbers such as two-thirds that floating-point numbers can only
1165approximate.
1166
Mark Dickinsond058cd22008-02-10 21:29:51 +00001167The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001168that will be the numerator and denominator of the resulting fraction. ::
1169
Mark Dickinsond058cd22008-02-10 21:29:51 +00001170 >>> from fractions import Fraction
1171 >>> a = Fraction(2, 3)
1172 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001173 >>> float(a), float(b)
1174 (0.66666666666666663, 0.40000000000000002)
1175 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +00001176 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001177 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +00001178 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001179
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001180To help in converting floating-point numbers to rationals,
1181the float type now has a :meth:`as_integer_ratio()` method that returns
1182the numerator and denominator for a fraction that evaluates to the same
1183floating-point value::
1184
1185 >>> (2.5) .as_integer_ratio()
1186 (5, 2)
1187 >>> (3.1415) .as_integer_ratio()
1188 (7074029114692207L, 2251799813685248L)
1189 >>> (1./3) .as_integer_ratio()
1190 (6004799503160661L, 18014398509481984L)
1191
1192Note that values that can only be approximated by floating-point
1193numbers, such as 1./3, are not simplified to the number being
1194approximated; the fraction attempts to match the floating-point value
1195**exactly**.
1196
Mark Dickinsond058cd22008-02-10 21:29:51 +00001197The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001198Mullender that was in Python's :file:`Demo/classes/` directory for a
1199long time. This implementation was significantly updated by Jeffrey
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001200Yasskin.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +00001201
Georg Brandl8ec7f652007-08-15 14:28:01 +00001202Other Language Changes
1203======================
1204
1205Here are all of the changes that Python 2.6 makes to the core Python language.
1206
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001207* When calling a function using the ``**`` syntax to provide keyword
1208 arguments, you are no longer required to use a Python dictionary;
1209 any mapping will now work::
1210
1211 >>> def f(**kw):
1212 ... print sorted(kw)
1213 ...
1214 >>> ud=UserDict.UserDict()
1215 >>> ud['a'] = 1
1216 >>> ud['b'] = 'string'
1217 >>> f(**ud)
1218 ['a', 'b']
1219
Georg Brandlb19be572007-12-29 10:57:00 +00001220 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001221
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001222* Tuples now have an :meth:`index` method matching the list type's
1223 :meth:`index` method::
1224
1225 >>> t = (0,1,2,3,4)
1226 >>> t.index(3)
1227 3
1228
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001229* The built-in types now have improved support for extended slicing syntax,
1230 where various combinations of ``(start, stop, step)`` are supplied.
1231 Previously, the support was partial and certain corner cases wouldn't work.
1232 (Implemented by Thomas Wouters.)
1233
Georg Brandlb19be572007-12-29 10:57:00 +00001234 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001235
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001236* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001237 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001238 adding or modifying a getter, setter or deleter function to an
1239 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001240
1241 class C(object):
1242 @property
1243 def x(self):
1244 return self._x
1245
1246 @x.setter
1247 def x(self, value):
1248 self._x = value
1249
1250 @x.deleter
1251 def x(self):
1252 del self._x
1253
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001254 class D(C):
1255 @C.x.getter
1256 def x(self):
1257 return self._x * 2
1258
1259 @x.setter
1260 def x(self, value):
1261 self._x = value / 2
1262
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001263
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001264* C functions and methods that use
1265 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
1266 have a :meth:`__complex__` method. In particular, the functions in the
1267 :mod:`cmath` module will now accept objects with this method.
1268 This is a backport of a Python 3.0 change.
1269 (Contributed by Mark Dickinson.)
1270
Georg Brandlb19be572007-12-29 10:57:00 +00001271 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001272
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001273 A numerical nicety: when creating a complex number from two floats
1274 on systems that support signed zeros (-0 and +0), the
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001275 :func:`complex` constructor will now preserve the sign
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001276 of the zero.
1277
Georg Brandlb19be572007-12-29 10:57:00 +00001278 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001279
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001280* More floating-point features were also added. The :func:`float` function
1281 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001282 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001283 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +00001284 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001285
Georg Brandl225163d2008-03-05 07:10:35 +00001286 .. Patch 1635
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001287
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001288 Other functions in the :mod:`math` module, :func:`isinf` and
1289 :func:`isnan`, return true if their floating-point argument is
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001290 infinite or Not A Number.
1291
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001292 .. Patch 1640
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001293
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001294 The ``math.copysign(x, y)`` function
1295 copies the sign bit of an IEEE 754 number, returning the absolute
1296 value of *x* combined with the sign bit of *y*. For example,
1297 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
1298 Heimes.)
1299
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001300* Changes to the :class:`Exception` interface
1301 as dictated by :pep:`352` continue to be made. For 2.6,
1302 the :attr:`message` attribute is being deprecated in favor of the
1303 :attr:`args` attribute.
1304
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001305* The :exc:`GeneratorExit` exception now subclasses
1306 :exc:`BaseException` instead of :exc:`Exception`. This means
1307 that an exception handler that does ``except Exception:``
1308 will not inadvertently catch :exc:`GeneratorExit`.
1309 (Contributed by Chad Austin.)
1310
Georg Brandlb19be572007-12-29 10:57:00 +00001311 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001312
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001313* Generator objects now have a :attr:`gi_code` attribute that refers to
1314 the original code object backing the generator.
1315 (Contributed by Collin Winter.)
1316
1317 .. Patch #1473257
1318
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001319* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001320 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001321
Georg Brandlb19be572007-12-29 10:57:00 +00001322 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001323
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001324* The :func:`complex` constructor now accepts strings containing
1325 parenthesized complex numbers, letting ``complex(repr(cmplx))``
1326 will now round-trip values. For example, ``complex('(3+4j)')``
1327 now returns the value (3+4j).
1328
Georg Brandlb19be572007-12-29 10:57:00 +00001329 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001330
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001331* The string :meth:`translate` method now accepts ``None`` as the
1332 translation table parameter, which is treated as the identity
1333 transformation. This makes it easier to carry out operations
1334 that only delete characters. (Contributed by Bengt Richter.)
1335
Georg Brandlb19be572007-12-29 10:57:00 +00001336 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001337
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001338* The built-in :func:`dir` function now checks for a :meth:`__dir__`
1339 method on the objects it receives. This method must return a list
1340 of strings containing the names of valid attributes for the object,
1341 and lets the object control the value that :func:`dir` produces.
1342 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +00001343 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001344
Georg Brandlb19be572007-12-29 10:57:00 +00001345 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001346
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001347* Instance method objects have new attributes for the object and function
1348 comprising the method; the new synonym for :attr:`im_self` is
1349 :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`.
1350 The old names are still supported in Python 2.6; they're gone in 3.0.
1351
Georg Brandl8ec7f652007-08-15 14:28:01 +00001352* An obscure change: when you use the the :func:`locals` function inside a
1353 :keyword:`class` statement, the resulting dictionary no longer returns free
1354 variables. (Free variables, in this case, are variables referred to in the
1355 :keyword:`class` statement that aren't attributes of the class.)
1356
Georg Brandlb19be572007-12-29 10:57:00 +00001357.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001358
1359
1360Optimizations
1361-------------
1362
Georg Brandlaf30b282008-01-15 06:55:56 +00001363* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001364 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +00001365 for a particular class; once cached, the interpreter doesn't need to
1366 traverse base classes to figure out the right method to call.
1367 The cache is cleared if a base class or the class itself is modified,
1368 so the cache should remain correct even in the face of Python's dynamic
1369 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001370 (Original optimization implemented by Armin Rigo, updated for
1371 Python 2.6 by Kevin Jacobs.)
1372
Georg Brandl225163d2008-03-05 07:10:35 +00001373 .. Patch 1700288
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001374
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001375* All of the functions in the :mod:`struct` module have been rewritten in
1376 C, thanks to work at the Need For Speed sprint.
1377 (Contributed by Raymond Hettinger.)
1378
Georg Brandl8ec7f652007-08-15 14:28:01 +00001379* Internally, a bit is now set in type objects to indicate some of the standard
1380 built-in types. This speeds up checking if an object is a subclass of one of
1381 these types. (Contributed by Neal Norwitz.)
1382
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001383* Unicode strings now uses faster code for detecting
1384 whitespace and line breaks; this speeds up the :meth:`split` method
1385 by about 25% and :meth:`splitlines` by 35%.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001386 (Contributed by Antoine Pitrou.) Memory usage is reduced
1387 by using pymalloc for the Unicode string's data.
1388
1389* The ``with`` statement now stores the :meth:`__exit__` method on the stack,
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001390 producing a small speedup. (Implemented by Jeffrey Yasskin.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001391
1392* To reduce memory usage, the garbage collector will now clear internal
1393 free lists when garbage-collecting the highest generation of objects.
1394 This may return memory to the OS sooner.
1395
Georg Brandl8ec7f652007-08-15 14:28:01 +00001396The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
1397benchmark around XX% faster than Python 2.5.
1398
Georg Brandlb19be572007-12-29 10:57:00 +00001399.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001400
1401
1402New, Improved, and Deprecated Modules
1403=====================================
1404
1405As usual, Python's standard library received a number of enhancements and bug
1406fixes. Here's a partial list of the most notable changes, sorted alphabetically
1407by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
1408complete list of changes, or look through the CVS logs for all the details.
1409
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001410* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
1411 available, instead of restricting itself to protocol 1.
1412 (Contributed by W. Barnes.)
1413
Georg Brandlb19be572007-12-29 10:57:00 +00001414 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001415
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001416* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001417 fieldnames)` is a factory function that creates subclasses of the standard tuple
1418 whose fields are accessible by name as well as index. For example::
1419
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001420 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001421 ... 'id name type size')
1422 # Names are separated by spaces or commas.
1423 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +00001424 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001425 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001426
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001427 >>> var = var_type(1, 'frequency', 'int', 4)
1428 >>> print var[0], var.id # Equivalent
1429 1 1
1430 >>> print var[2], var.type # Equivalent
1431 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +00001432 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001433 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +00001434 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001435 >>> v2
1436 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001437
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001438 Where the new :class:`namedtuple` type proved suitable, the standard
1439 library has been modified to return them. For example,
1440 the :meth:`Decimal.as_tuple` method now returns a named tuple with
1441 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1442
Georg Brandl8ec7f652007-08-15 14:28:01 +00001443 (Contributed by Raymond Hettinger.)
1444
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001445* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +00001446 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001447 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +00001448 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001449 old items to be discarded.
1450
1451 ::
1452
1453 >>> from collections import deque
1454 >>> dq=deque(maxlen=3)
1455 >>> dq
1456 deque([], maxlen=3)
1457 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
1458 >>> dq
1459 deque([1, 2, 3], maxlen=3)
1460 >>> dq.append(4)
1461 >>> dq
1462 deque([2, 3, 4], maxlen=3)
1463
1464 (Contributed by Raymond Hettinger.)
1465
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001466* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
1467 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
1468
Georg Brandlb19be572007-12-29 10:57:00 +00001469 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001470
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001471 The :mod:`ctypes` string, buffer and array types also have improved
1472 support for extended slicing syntax,
1473 where various combinations of ``(start, stop, step)`` are supplied.
1474 (Implemented by Thomas Wouters.)
1475
Georg Brandlb19be572007-12-29 10:57:00 +00001476 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001477
Georg Brandl8ec7f652007-08-15 14:28:01 +00001478* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001479 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001480 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001481 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001482
1483 # Boldface text starting at y=0,x=21
1484 # and affecting the rest of the line.
1485 stdscr.chgat(0,21, curses.A_BOLD)
1486
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001487 The :class:`Textbox` class in the :mod:`curses.textpad` module
1488 now supports editing in insert mode as well as overwrite mode.
1489 Insert mode is enabled by supplying a true value for the *insert_mode*
1490 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001491
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001492* The :mod:`datetime` module's :meth:`strftime` methods now support a
1493 ``%f`` format code that expands to the number of microseconds in the
1494 object, zero-padded on
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001495 the left to six places. (Contributed by Skip Montanaro.)
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001496
1497 .. Patch 1158
1498
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001499* The :mod:`decimal` module was updated to version 1.66 of
1500 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
1501 include some methods for some basic mathematical functions such as
1502 :meth:`exp` and :meth:`log10`::
1503
1504 >>> Decimal(1).exp()
1505 Decimal("2.718281828459045235360287471")
1506 >>> Decimal("2.7182818").ln()
1507 Decimal("0.9999999895305022877376682436")
1508 >>> Decimal(1000).log10()
1509 Decimal("3")
1510
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001511 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
1512 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1513
1514 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
1515 support added by Raymond Hettinger.)
1516
1517* The :mod:`difflib` module's :class:`SequenceMatcher` class
1518 now returns named tuples representing matches.
1519 In addition to behaving like tuples, the returned values
1520 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
1521 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001522
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001523* An optional ``timeout`` parameter was added to the
1524 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
1525 method, specifying a timeout measured in seconds. (Added by Facundo
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001526 Batista.) Also, the :class:`FTP` class's
1527 :meth:`storbinary` and :meth:`storlines`
1528 now take an optional *callback* parameter that will be called with
1529 each block of data after the data has been sent.
1530 (Contributed by Phil Schwartz.)
1531
1532 .. Patch 1221598
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001533
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001534* The :func:`reduce` built-in function is also available in the
1535 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
1536 only available from :mod:`functools`; currently there are no plans
1537 to drop the built-in in the 2.x series. (Patched by
1538 Christian Heimes.)
1539
Georg Brandlb19be572007-12-29 10:57:00 +00001540 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001541
Georg Brandl8ec7f652007-08-15 14:28:01 +00001542* The :func:`glob.glob` function can now return Unicode filenames if
1543 a Unicode path was used and Unicode filenames are matched within the directory.
1544
Georg Brandlb19be572007-12-29 10:57:00 +00001545 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +00001546
1547* The :mod:`gopherlib` module has been removed.
1548
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001549* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
1550 takes any number of iterables that return data *in sorted
1551 order*, and returns a new iterator that returns the contents of all
1552 the iterators, also in sorted order. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001553
1554 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
1555 [1, 2, 3, 5, 8, 9, 16]
1556
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001557 Another new function, ``heappushpop(heap, item)``,
1558 pushes *item* onto *heap*, then pops off and returns the smallest item.
1559 This is more efficient than making a call to :func:`heappush` and then
1560 :func:`heappop`.
1561
Georg Brandl8ec7f652007-08-15 14:28:01 +00001562 (Contributed by Raymond Hettinger.)
1563
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001564* An optional ``timeout`` parameter was added to the
1565 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
1566 class constructors, specifying a timeout measured in seconds.
1567 (Added by Facundo Batista.)
1568
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001569* Most of the :mod:`inspect` module's functions, such as
1570 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
1571 In addition to behaving like tuples, the elements of the return value
1572 can also be accessed as attributes.
1573 (Contributed by Raymond Hettinger.)
1574
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001575 Some new functions in the module include
1576 :func:`isgenerator`, :func:`isgeneratorfunction`,
1577 and :func:`isabstract`.
1578
1579* The :mod:`itertools` module gained several new functions.
1580
1581 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
1582 each of the elements; if some of the iterables are shorter than
1583 others, the missing values are set to *fillvalue*. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001584
1585 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
1586 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
1587
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001588 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
1589 of the supplied iterables, a set of tuples containing
1590 every possible combination of the elements returned from each iterable. ::
1591
1592 itertools.product([1,2,3], [4,5,6]) ->
1593 [(1, 4), (1, 5), (1, 6),
1594 (2, 4), (2, 5), (2, 6),
1595 (3, 4), (3, 5), (3, 6)]
1596
1597 The optional *repeat* keyword argument is used for taking the
1598 product of an iterable or a set of iterables with themselves,
1599 repeated *N* times. With a single iterable argument, *N*-tuples
1600 are returned::
1601
1602 itertools.product([1,2], repeat=3)) ->
1603 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
1604 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
1605
1606 With two iterables, *2N*-tuples are returned. ::
1607
1608 itertools(product([1,2], [3,4], repeat=2) ->
1609 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
1610 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
1611 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
1612 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
1613
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001614 ``combinations(iterable, r)`` returns sub-sequences of length *r* from
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001615 the elements of *iterable*. ::
1616
1617 itertools.combinations('123', 2) ->
1618 [('1', '2'), ('1', '3'), ('2', '3')]
1619
1620 itertools.combinations('123', 3) ->
1621 [('1', '2', '3')]
1622
1623 itertools.combinations('1234', 3) ->
1624 [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
1625 ('2', '3', '4')]
1626
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001627 ``permutations(iter[, r])`` returns all the permutations of length *r* of
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001628 the iterable's elements. If *r* is not specified, it will default to the
1629 number of elements produced by the iterable.
1630
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001631 itertools.permutations([1,2,3,4], 2) ->
1632 [(1, 2), (1, 3), (1, 4),
1633 (2, 1), (2, 3), (2, 4),
1634 (3, 1), (3, 2), (3, 4),
1635 (4, 1), (4, 2), (4, 3)]
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001636
Andrew M. Kuchlingabf8e012008-04-08 21:22:53 +00001637 ``itertools.chain(*iterables)`` is an existing function in
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001638 :mod:`itertools` that gained a new constructor in Python 2.6.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001639 ``itertools.chain.from_iterable(iterable)`` takes a single
1640 iterable that should return other iterables. :func:`chain` will
1641 then return all the elements of the first iterable, then
1642 all the elements of the second, and so on. ::
1643
1644 chain.from_iterable([[1,2,3], [4,5,6]]) ->
1645 [1, 2, 3, 4, 5, 6]
1646
1647 (All contributed by Raymond Hettinger.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001648
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001649* The :mod:`logging` module's :class:`FileHandler` class
1650 and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
1651 and :class:`TimedRotatingFileHandler` now
1652 have an optional *delay* parameter to its constructor. If *delay*
1653 is true, opening of the log file is deferred until the first
1654 :meth:`emit` call is made. (Contributed by Vinay Sajip.)
1655
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656* The :mod:`macfs` module has been removed. This in turn required the
1657 :func:`macostools.touched` function to be removed because it depended on the
1658 :mod:`macfs` module.
1659
Georg Brandlb19be572007-12-29 10:57:00 +00001660 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +00001661
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001662* :class:`mmap` objects now have a :meth:`rfind` method that finds
1663 a substring, beginning at the end of the string and searching
1664 backwards. The :meth:`find` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001665 also gained an *end* parameter containing the index at which to stop
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001666 the forward search.
1667 (Contributed by John Lenton.)
1668
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001669* (3.0-warning mode) The :mod:`new` module has been removed from
1670 Python 3.0. Importing it therefore triggers a warning message.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001671
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001672* The :mod:`operator` module gained a
1673 :func:`methodcaller` function that takes a name and an optional
1674 set of arguments, returning a callable that will call
1675 the named function on any arguments passed to it. For example::
1676
1677 >>> # Equivalent to lambda s: s.replace('old', 'new')
1678 >>> replacer = operator.methodcaller('replace', 'old', 'new')
1679 >>> replacer('old wine in old bottles')
1680 'new wine in new bottles'
1681
Georg Brandl27504da2008-03-04 07:25:54 +00001682 (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001683
1684 The :func:`attrgetter` function now accepts dotted names and performs
1685 the corresponding attribute lookups::
1686
1687 >>> inst_name = operator.attrgetter('__class__.__name__')
1688 >>> inst_name('')
1689 'str'
1690 >>> inst_name(help)
1691 '_Helper'
1692
Georg Brandl27504da2008-03-04 07:25:54 +00001693 (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001694
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001695* New functions in the :mod:`os` module include
1696 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
1697 and ``lchmod(path, mode)``, on operating systems that support these
1698 functions. :func:`fchmod` and :func:`fchown` let you change the mode
1699 and ownership of an opened file, and :func:`lchmod` changes the mode
1700 of a symlink.
1701
1702 (Contributed by Georg Brandl and Christian Heimes.)
1703
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001704* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001705 set to True, it will follow symlinks pointing to directories and
1706 visit the directory's contents. For backward compatibility, the
1707 parameter's default value is false. Note that the function can fall
1708 into an infinite recursion if there's a symlink that points to a
1709 parent directory.
1710
Georg Brandlb19be572007-12-29 10:57:00 +00001711 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001712
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001713* The ``os.environ`` object's :meth:`clear` method will now unset the
1714 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001715 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001716
Georg Brandlb19be572007-12-29 10:57:00 +00001717 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001718
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001719* In the :mod:`os.path` module, the :func:`splitext` function
1720 has been changed to not split on leading period characters.
1721 This produces better results when operating on Unix's dot-files.
1722 For example, ``os.path.splitext('.ipython')``
1723 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
1724
Georg Brandlb19be572007-12-29 10:57:00 +00001725 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001726
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001727 A new function, :func:`relpath(path, start)` returns a relative path
1728 from the ``start`` path, if it's supplied, or from the current
1729 working directory to the destination ``path``. (Contributed by
1730 Richard Barran.)
1731
Georg Brandlb19be572007-12-29 10:57:00 +00001732 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001733
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001734 On Windows, :func:`os.path.expandvars` will now expand environment variables
1735 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001736 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001737
Georg Brandlb19be572007-12-29 10:57:00 +00001738 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001739
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001740* The Python debugger provided by the :mod:`pdb` module
1741 gained a new command: "run" restarts the Python program being debugged,
1742 and can optionally take new command-line arguments for the program.
1743 (Contributed by Rocky Bernstein.)
1744
Georg Brandlb19be572007-12-29 10:57:00 +00001745 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001746
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001747 The :func:`post_mortem` function, used to enter debugging of a
1748 traceback, will now use the traceback returned by :func:`sys.exc_info`
1749 if no traceback is supplied. (Contributed by Facundo Batista.)
1750
1751 .. Patch #1106316
1752
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001753* The :mod:`pickletools` module now has an :func:`optimize` function
1754 that takes a string containing a pickle and removes some unused
1755 opcodes, returning a shorter pickle that contains the same data structure.
1756 (Contributed by Raymond Hettinger.)
1757
Georg Brandl8ec7f652007-08-15 14:28:01 +00001758* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
1759 are wrappers for the corresponding system calls (where they're available).
1760 Constants for the flag values are defined in the :mod:`stat` module; some
1761 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
1762 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
1763 file. (Contributed by M. Levinson.)
1764
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001765 ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors
1766 from *low* to *high*, ignoring any errors and not including *high* itself.
1767 This function is now used by the :mod:`subprocess` module to make starting
1768 processes faster. (Contributed by Georg Brandl.)
1769
1770 .. Patch #1663329
1771
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00001772* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
1773 their :attr:`buffer_size` attribute to change the size of the buffer
1774 used to hold character data.
1775 (Contributed by Achim Gaedke.)
1776
1777 .. Patch 1137
1778
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001779* The :mod:`Queue` module now provides queue classes that retrieve entries
1780 in different orders. The :class:`PriorityQueue` class stores
1781 queued items in a heap and retrieves them in priority order,
1782 and :class:`LifoQueue` retrieves the most recently added entries first,
1783 meaning that it behaves like a stack.
1784 (Contributed by Raymond Hettinger.)
1785
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001786* The :mod:`random` module's :class:`Random` objects can
1787 now be pickled on a 32-bit system and unpickled on a 64-bit
1788 system, and vice versa. Unfortunately, this change also means
1789 that Python 2.6's :class:`Random` objects can't be unpickled correctly
1790 on earlier versions of Python.
1791 (Contributed by Shawn Ligocki.)
1792
Georg Brandlb19be572007-12-29 10:57:00 +00001793 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001794
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001795 The new ``triangular(low, high, mode)`` function returns random
1796 numbers following a triangular distribution. The returned values
1797 are between *low* and *high*, not including *high* itself, and
1798 with *mode* as the mode, the most frequently occurring value
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001799 in the distribution. (Contributed by Wladmir van der Laan and
1800 Raymond Hettinger.)
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001801
1802 .. Patch 1681432
1803
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001804* Long regular expression searches carried out by the :mod:`re`
1805 module will now check for signals being delivered, so especially
1806 long searches can now be interrupted.
1807 (Contributed by Josh Hoyt and Ralf Schmitt.)
1808
Georg Brandl225163d2008-03-05 07:10:35 +00001809 .. Patch 846388
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001810
Georg Brandl8ec7f652007-08-15 14:28:01 +00001811* The :mod:`rgbimg` module has been removed.
1812
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001813* The :mod:`sched` module's :class:`scheduler` instances now
1814 have a read-only :attr:`queue` attribute that returns the
1815 contents of the scheduler's queue, represented as a list of
Georg Brandl225163d2008-03-05 07:10:35 +00001816 named tuples with the fields ``(time, priority, action, argument)``.
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001817 (Contributed by Raymond Hettinger.)
Georg Brandl225163d2008-03-05 07:10:35 +00001818
1819 .. Patch 1861
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001820
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001821* The :mod:`select` module now has wrapper functions
1822 for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls.
1823 Also, a :meth:`modify` method was added to the existing :class:`poll`
1824 objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
1825 or file object and an event mask,
1826
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001827 (Contributed by Christian Heimes.)
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001828
1829 .. Patch 1657
1830
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00001831 .. XXX
1832
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001833* The :mod:`sets` module has been deprecated; it's better to
1834 use the built-in :class:`set` and :class:`frozenset` types.
1835
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001836* Integrating signal handling with GUI handling event loops
1837 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001838 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001839 The :mod:`signal` module can now make this more efficient.
1840 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
1841 to be used; when a signal is received, a byte is written to that
1842 file descriptor. There's also a C-level function,
1843 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
1844
1845 Event loops will use this by opening a pipe to create two descriptors,
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001846 one for reading and one for writing. The writable descriptor
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001847 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
1848 will be added to the list of descriptors monitored by the event loop via
1849 :cfunc:`select` or :cfunc:`poll`.
1850 On receiving a signal, a byte will be written and the main event loop
1851 will be woken up, without the need to poll.
1852
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001853 (Contributed by Adam Olsen.)
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001854
Georg Brandl225163d2008-03-05 07:10:35 +00001855 .. Patch 1583
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001856
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001857 The :func:`siginterrupt` function is now available from Python code,
1858 and allows changing whether signals can interrupt system calls or not.
1859 (Contributed by Ralf Schmitt.)
1860
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001861 The :func:`setitimer` and :func:`getitimer` functions have also been
1862 added on systems that support these system calls. :func:`setitimer`
1863 allows setting interval timers that will cause a signal to be
1864 delivered to the process after a specified time, measured in
1865 wall-clock time, consumed process time, or combined process+system
1866 time. (Contributed by Guilherme Polo.)
1867
1868 .. Patch 2240
1869
1870
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001871* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
1872 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001873 interface identical to the existing :class:`SMTP` class. Both
1874 class constructors also have an optional ``timeout`` parameter
1875 that specifies a timeout for the initial connection attempt, measured in
1876 seconds.
1877
1878 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001879 the module. LMTP is used in place of SMTP when transferring e-mail
1880 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001881
1882 (SMTP over SSL contributed by Monty Taylor; timeout parameter
1883 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001884 Hedstrom.)
1885
Georg Brandlb19be572007-12-29 10:57:00 +00001886 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +00001887
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001888* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
1889 and forgets any knowledge obtained from the server not obtained from
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001890 the TLS negotiation itself. (Patch contributed by Bill Fenner.)
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001891
1892 .. Issue 829951
1893
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001894* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1895 a high-performance non-IP-based protocol designed for use in clustered
1896 environments. TIPC addresses are 4- or 5-tuples.
1897 (Contributed by Alberto Bertogli.)
1898
1899 .. Patch #1646
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00001900
1901* The base classes in the :mod:`SocketServer` module now support
1902 calling a :meth:`handle_timeout` method after a span of inactivity
1903 specified by the server's :attr:`timeout` attribute. (Contributed
1904 by Michael Pomraning.)
1905
1906 .. Patch #742598
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001907
1908* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
1909 using the format character ``'?'``.
1910 (Contributed by David Remahl.)
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001911
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001912* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001913 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001914 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001915 derived from the :file:`float.h` file. Attributes of this object
1916 include
1917 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001918 (smallest difference between 1.0 and the next largest value
1919 representable), and several others. (Contributed by Christian Heimes.)
1920
Georg Brandlb19be572007-12-29 10:57:00 +00001921 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001922
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00001923 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
1924 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1925 If this variable is true, the compiled files are not written. The
1926 variable is initially set on start-up by supplying the :option:`-B`
1927 switch to the Python interpreter, or by setting the
1928 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
1929 running the interpreter. Python code can subsequently
1930 change the value of this variable to control whether bytecode files
1931 are written or not.
1932 (Contributed by Neal Norwitz and Georg Brandl.)
1933
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001934 Information about the command-line arguments supplied to the Python
1935 interpreter are available as attributes of a ``sys.flags`` named
1936 tuple. For example, the :attr:`verbose` attribute is true if Python
1937 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1938 These attributes are all read-only.
1939 (Contributed by Christian Heimes.)
1940
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001941 It's now possible to determine the current profiler and tracer functions
1942 by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
1943 (Contributed by Georg Brandl.)
1944
1945 .. Patch #1648
1946
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001947* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1948 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1949 format that was already supported. The default format
1950 is GNU tar; specify the ``format`` parameter to open a file
1951 using a different format::
1952
1953 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1954
1955 The new ``errors`` parameter lets you specify an error handling
1956 scheme for character conversions: the three standard ways Python can
1957 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1958 special value ``'utf-8'``, which replaces bad characters with their
1959 UTF-8 representation. Character conversions occur because the PAX
1960 format supports Unicode filenames, defaulting to UTF-8 encoding.
1961
1962 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1963 a function that can be used to exclude certain filenames from
1964 an archive.
1965 The function must take a filename and return true if the file
1966 should be excluded or false if it should be archived.
1967 The function is applied to both the name initially passed to :meth:`add`
1968 and to the names of files in recursively-added directories.
1969
1970 (All changes contributed by Lars Gustäbel).
1971
1972* An optional ``timeout`` parameter was added to the
1973 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1974 measured in seconds. (Added by Facundo Batista.)
1975
1976* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1977 the temporary file it created when the file is closed. This
1978 behaviour can now be changed by passing ``delete=False`` to the
1979 constructor. (Contributed by Damien Miller.)
1980
Georg Brandlb19be572007-12-29 10:57:00 +00001981 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001982
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001983 A new class, :class:`SpooledTemporaryFile`, behaves like
1984 a temporary file but stores its data in memory until a maximum size is
1985 exceeded. On reaching that limit, the contents will be written to
1986 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
1987
1988 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
1989 both work as context managers, so you can write
1990 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
1991 (Contributed by Alexander Belopolsky.)
1992
1993 .. Issue #2021
1994
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001995* The :mod:`test.test_support` module now contains a
1996 :func:`EnvironmentVarGuard`
1997 context manager that supports temporarily changing environment variables and
1998 automatically restores them to their old values.
1999
2000 Another context manager, :class:`TransientResource`, can surround calls
2001 to resources that may or may not be available; it will catch and
2002 ignore a specified list of exceptions. For example,
2003 a network test may ignore certain failures when connecting to an
2004 external web site::
2005
2006 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
2007 f = urllib.urlopen('https://sf.net')
2008 ...
2009
2010 (Contributed by Brett Cannon.)
2011
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002012* The :mod:`textwrap` module can now preserve existing whitespace
2013 at the beginnings and ends of the newly-created lines
2014 by specifying ``drop_whitespace=False``
2015 as an argument::
2016
2017 >>> S = """This sentence has a bunch of extra whitespace."""
2018 >>> print textwrap.fill(S, width=15)
2019 This sentence
2020 has a bunch
2021 of extra
2022 whitespace.
2023 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
2024 This sentence
2025 has a bunch
2026 of extra
2027 whitespace.
2028 >>>
2029
Georg Brandl27504da2008-03-04 07:25:54 +00002030 (Contributed by Dwayne Bailey.)
2031
Georg Brandlb19be572007-12-29 10:57:00 +00002032 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002033
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002034* The :mod:`timeit` module now accepts callables as well as strings
2035 for the statement being timed and for the setup code.
2036 Two convenience functions were added for creating
2037 :class:`Timer` instances:
2038 ``repeat(stmt, setup, time, repeat, number)`` and
2039 ``timeit(stmt, setup, time, number)`` create an instance and call
2040 the corresponding method. (Contributed by Erik Demaine.)
2041
Georg Brandlb19be572007-12-29 10:57:00 +00002042 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00002043
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00002044* An optional ``timeout`` parameter was added to the
2045 :func:`urllib.urlopen` function and the
2046 :class:`urllib.ftpwrapper` class constructor, as well as the
2047 :func:`urllib2.urlopen` function. The parameter specifies a timeout
2048 measured in seconds. For example::
2049
2050 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
2051 Traceback (most recent call last):
2052 ...
2053 urllib2.URLError: <urlopen error timed out>
2054 >>>
2055
2056 (Added by Facundo Batista.)
2057
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002058* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002059 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002060 their socket by passing True as the ``bind_and_activate``
2061 constructor parameter. This can be used to modify the instance's
2062 :attr:`allow_reuse_address` attribute before calling the
2063 :meth:`server_bind` and :meth:`server_activate` methods to
2064 open the socket and begin listening for connections.
2065 (Contributed by Peter Parente.)
2066
Georg Brandlb19be572007-12-29 10:57:00 +00002067 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00002068
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002069 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
2070 attribute; if true, the exception and formatted traceback are returned
2071 as HTTP headers "X-Exception" and "X-Traceback". This feature is
2072 for debugging purposes only and should not be used on production servers
2073 because the tracebacks could possibly reveal passwords or other sensitive
2074 information. (Contributed by Alan McIntyre as part of his
2075 project for Google's Summer of Code 2007.)
2076
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002077* The :mod:`zipfile` module's :class:`ZipFile` class now has
2078 :meth:`extract` and :meth:`extractall` methods that will unpack
2079 a single file or all the files in the archive to the current directory, or
2080 to a specified directory::
2081
2082 z = zipfile.ZipFile('python-251.zip')
2083
2084 # Unpack a single file, writing it relative to the /tmp directory.
2085 z.extract('Python/sysmodule.c', '/tmp')
2086
2087 # Unpack all the files in the archive.
2088 z.extractall()
2089
2090 (Contributed by Alan McIntyre.)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00002091
2092 .. Patch 467924
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002093
Georg Brandlb19be572007-12-29 10:57:00 +00002094.. ======================================================================
2095.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002096
2097Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00002098--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002099
2100Bill Janssen made extensive improvements to Python 2.6's support for
2101SSL.
2102
2103XXX use ssl.sslsocket - subclass of socket.socket.
2104
2105XXX Can specify if certificate is required, and obtain certificate info
2106by calling getpeercert method.
2107
2108XXX sslwrap() behaves like socket.ssl
2109
2110XXX Certain features require the OpenSSL package to be installed, notably
2111 the 'openssl' binary.
2112
2113.. seealso::
2114
2115 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002116
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002117
2118.. ======================================================================
2119
2120plistlib: A Property-List Parser
2121--------------------------------------------------
2122
2123A commonly-used format on MacOS X is the ``.plist`` format,
2124which stores basic data types (numbers, strings, lists,
2125and dictionaries) and serializes them into an XML-based format.
2126(It's a lot like the XML-RPC serialization of data types.)
2127
2128Despite being primarily used on MacOS X, the format
2129has nothing Mac-specific about it and the Python implementation works
2130on any platform that Python supports, so the :mod:`plistlib` module
2131has been promoted to the standard library.
2132
2133Using the module is simple::
2134
2135 import sys
2136 import plistlib
2137 import datetime
2138
2139 # Create data structure
2140 data_struct = dict(lastAccessed=datetime.datetime.now(),
2141 version=1,
2142 categories=('Personal', 'Shared', 'Private'))
2143
2144 # Create string containing XML.
2145 plist_str = plistlib.writePlistToString(data_struct)
2146 new_struct = plistlib.readPlistFromString(plist_str)
2147 print data_struct
2148 print new_struct
2149
2150 # Write data structure to a file and read it back.
2151 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
2152 new_struct = plistlib.readPlist('/tmp/customizations.plist')
2153
2154 # read/writePlist accepts file-like objects as well as paths.
2155 plistlib.writePlist(data_struct, sys.stdout)
2156
2157
Georg Brandlb19be572007-12-29 10:57:00 +00002158.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002159
2160
2161Build and C API Changes
2162=======================
2163
2164Changes to Python's build process and to the C API include:
2165
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00002166* Python 2.6 can be built with Microsoft Visual Studio 2008.
2167 See the :file:`PCbuild9` directory for the build files.
2168 (Implemented by Christian Heimes.)
2169
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00002170* Python now can only be compiled with C89 compilers (after 19
2171 years!). This means that the Python source tree can now drop its
2172 own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
2173 are in the C89 standard library.
2174
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002175* The BerkeleyDB module now has a C API object, available as
2176 ``bsddb.db.api``. This object can be used by other C extensions
2177 that wish to use the :mod:`bsddb` module for their own purposes.
2178 (Contributed by Duncan Grisby.)
2179
Georg Brandlb19be572007-12-29 10:57:00 +00002180 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00002181
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002182* Python's use of the C stdio library is now thread-safe, or at least
2183 as thread-safe as the underlying library is. A long-standing potential
2184 bug occurred if one thread closed a file object while another thread
2185 was reading from or writing to the object. In 2.6 file objects
2186 have a reference count, manipulated by the
2187 :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount`
2188 functions. File objects can't be closed unless the reference count
2189 is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL
2190 is still held, before carrying out an I/O operation using the
2191 ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called
2192 immediately after the GIL is re-acquired.
2193 (Contributed by Antoine Pitrou and Gregory P. Smith.)
2194
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002195* Several functions return information about the platform's
2196 floating-point support. :cfunc:`PyFloat_GetMax` returns
2197 the maximum representable floating point value,
2198 and :cfunc:`PyFloat_GetMin` returns the minimum
2199 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
2200 containing more information from the :file:`float.h` file, such as
2201 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
2202 (smallest difference between 1.0 and the next largest value
2203 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00002204 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00002205
Georg Brandlb19be572007-12-29 10:57:00 +00002206 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00002207
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002208* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00002209 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002210 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00002211 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002212
2213 .. Issue 1635
2214
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002215* Many C extensions define their own little macro for adding
2216 integers and strings to the module's dictionary in the
2217 ``init*`` function. Python 2.6 finally defines standard macros
2218 for adding values to a module, :cmacro:`PyModule_AddStringMacro`
2219 and :cmacro:`PyModule_AddIntMacro()`. (Contributed by
2220 Christian Heimes.)
2221
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002222* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
2223 they are macros,
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00002224 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002225 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00002226 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
2227 The mixed-case macros are still available
2228 in Python 2.6 for backward compatibility.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002229
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00002230 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002231
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002232* Distutils now places C extensions it builds in a
2233 different directory when running on a debug version of Python.
2234 (Contributed by Collin Winter.)
2235
2236 .. Patch 1530959
2237
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00002238* Several basic data types, such as integers and strings, maintain
2239 internal free lists of objects that can be re-used. The data
2240 structures for these free lists now follow a naming convention: the
2241 variable is always named ``free_list``, the counter is always named
2242 ``numfree``, and a macro :cmacro:`Py<typename>_MAXFREELIST` is
2243 always defined.
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00002244
Georg Brandlb19be572007-12-29 10:57:00 +00002245.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002246
2247
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002248Port-Specific Changes: Windows
2249-----------------------------------
2250
2251* The :mod:`msvcrt` module now supports
2252 both the normal and wide char variants of the console I/O
2253 API. The :func:`getwch` function reads a keypress and returns a Unicode
2254 value, as does the :func:`getwche` function. The :func:`putwch` function
2255 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00002256 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002257
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00002258* :func:`os.path.expandvars` will now expand environment variables
2259 in the form "%var%", and "~user" will be expanded into the
2260 user's home directory path. (Contributed by Josiah Carlson.)
2261
2262* The :mod:`socket` module's socket objects now have an
2263 :meth:`ioctl` method that provides a limited interface to the
2264 :cfunc:`WSAIoctl` system interface.
2265
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002266* The :mod:`_winreg` module now has a function,
2267 :func:`ExpandEnvironmentStrings`,
2268 that expands environment variable references such as ``%NAME%``
2269 in an input string. The handle objects provided by this
2270 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00002271 in :keyword:`with` statements. (Contributed by Christian Heimes.)
2272
Andrew M. Kuchling34be7ce2008-04-07 23:57:07 +00002273 :mod:`_winreg` also has better support for x64 systems,
2274 exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`,
2275 and :func:`QueryReflectionKey` functions, which enable and disable
2276 registry reflection for 32-bit processes running on 64-bit systems.
2277
2278 .. Patch 1753245
2279
Christian Heimesff6cc6b2008-01-17 23:01:44 +00002280* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
2281 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
2282 were moved into the PC/ directory. The new PCbuild directory supports
2283 cross compilation for X64, debug builds and Profile Guided Optimization
2284 (PGO). PGO builds are roughly 10% faster than normal builds.
2285 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
2286 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002287
Georg Brandlb19be572007-12-29 10:57:00 +00002288.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002289
2290
2291.. _section-other:
2292
2293Other Changes and Fixes
2294=======================
2295
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002296As usual, there were a bunch of other improvements and bugfixes
2297scattered throughout the source tree. A search through the change
2298logs finds there were XXX patches applied and YYY bugs fixed between
2299Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002300
2301Some of the more notable changes are:
2302
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002303* It's now possible to prevent Python from writing any :file:`.pyc`
2304 or :file:`.pyo` files by either supplying the :option:`-B` switch
2305 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
2306 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00002307 are also used to set the :data:`sys.dont_write_bytecode` attribute;
2308 Python code can change this variable to control whether bytecode
2309 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002310 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002311
Georg Brandlb19be572007-12-29 10:57:00 +00002312.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002313
2314
2315Porting to Python 2.6
2316=====================
2317
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002318This section lists previously described changes and other bugfixes
2319that may require changes to your code:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002320
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00002321* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002322 now clears any existing contents of the deque
2323 before adding elements from the iterable. This change makes the
2324 behavior match that of ``list.__init__()``.
2325
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002326* The :class:`Decimal` constructor now accepts leading and trailing
2327 whitespace when passed a string. Previously it would raise an
2328 :exc:`InvalidOperation` exception. On the other hand, the
2329 :meth:`create_decimal` method of :class:`Context` objects now
2330 explicitly disallows extra whitespace, raising a
2331 :exc:`ConversionSyntax` exception.
2332
2333* Due to an implementation accident, if you passed a file path to
2334 the built-in :func:`__import__` function, it would actually import
2335 the specified file. This was never intended to work, however, and
2336 the implementation now explicitly checks for this case and raises
2337 an :exc:`ImportError`.
2338
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002339* The :mod:`socket` module exception :exc:`socket.error` now inherits
2340 from :exc:`IOError`. Previously it wasn't a subclass of
2341 :exc:`StandardError` but now it is, through :exc:`IOError`.
2342 (Implemented by Gregory P. Smith.)
2343
Georg Brandlb19be572007-12-29 10:57:00 +00002344 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00002345
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00002346* The :mod:`xmlrpclib` module no longer automatically converts
2347 :class:`datetime.date` and :class:`datetime.time` to the
2348 :class:`xmlrpclib.DateTime` type; the conversion semantics were
2349 not necessarily correct for all applications. Code using
2350 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
2351 instances.
2352
2353 .. Issue 1330538
2354
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002355* (3.0-warning mode) The :class:`Exception` class now warns
2356 when accessed using slicing or index access; having
2357 :class:`Exception` behave like a tuple is being phased out.
2358
2359* (3.0-warning mode) inequality comparisons between two dictionaries
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00002360 or two objects that don't implement comparison methods are reported
2361 as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2``
2362 is being phased out.
2363
2364 Comparisons between cells, which are an implementation detail of Python's
2365 scoping rules, also cause warnings because such comparisons are forbidden
2366 entirely in 3.0.
2367
Georg Brandlb19be572007-12-29 10:57:00 +00002368.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002369
2370
2371.. _acks:
2372
2373Acknowledgements
2374================
2375
2376The author would like to thank the following people for offering suggestions,
2377corrections and assistance with various drafts of this article: .
2378