blob: 4aa6f9f5bba413850b4a6b699268f1e203e93b15 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001****************************
2 What's New in Python 2.6
3****************************
4
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00005.. % XXX mention switch to reST for documentation
6.. % XXX mention switch to Roundup for bug tracking
7
Georg Brandl8ec7f652007-08-15 14:28:01 +00008:Author: A.M. Kuchling
9:Release: |release|
10:Date: |today|
11
12.. % $Id: whatsnew26.tex 55746 2007-06-02 18:33:53Z neal.norwitz $
13.. % Rules for maintenance:
14.. %
15.. % * Anyone can add text to this document. Do not spend very much time
16.. % on the wording of your changes, because your text will probably
17.. % get rewritten to some degree.
18.. %
19.. % * The maintainer will go through Misc/NEWS periodically and add
20.. % changes; it's therefore more important to add your changes to
21.. % Misc/NEWS than to this file.
22.. %
23.. % * This is not a complete list of every single change; completeness
24.. % is the purpose of Misc/NEWS. Some changes I consider too small
25.. % or esoteric to include. If such a change is added to the text,
26.. % I'll just remove it. (This is another reason you shouldn't spend
27.. % too much time on writing your addition.)
28.. %
29.. % * If you want to draw your new text to the attention of the
30.. % maintainer, add 'XXX' to the beginning of the paragraph or
31.. % section.
32.. %
33.. % * It's OK to just add a fragmentary note about a change. For
34.. % example: "XXX Describe the transmogrify() function added to the
35.. % socket module." The maintainer will research the change and
36.. % write the necessary text.
37.. %
38.. % * You can comment out your additions if you like, but it's not
39.. % necessary (especially when a final release is some months away).
40.. %
41.. % * Credit the author of a patch or bugfix. Just the name is
42.. % sufficient; the e-mail address isn't necessary.
43.. %
44.. % * It's helpful to add the bug/patch number as a comment:
45.. %
46.. % % Patch 12345
47.. % XXX Describe the transmogrify() function added to the socket
48.. % module.
49.. % (Contributed by P.Y. Developer.)
50.. %
51.. % This saves the maintainer the effort of going through the SVN log
52.. % when researching a change.
53
54This article explains the new features in Python 2.6. No release date for
55Python 2.6 has been set; it will probably be released in mid 2008.
56
57This article doesn't attempt to provide a complete specification of the new
58features, but instead provides a convenient overview. For full details, you
59should refer to the documentation for Python 2.6. If you want to understand the
60complete implementation and design rationale, refer to the PEP for a particular
61new feature.
62
63.. % Compare with previous release in 2 - 3 sentences here.
64.. % add hyperlink when the documentation becomes available online.
65
66.. % ======================================================================
67.. % Large, PEP-level features and changes should be described here.
68.. % Should there be a new section here for 3k migration?
69.. % Or perhaps a more general section describing module changes/deprecation?
Georg Brandl8ec7f652007-08-15 14:28:01 +000070.. % ======================================================================
71
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000072Python 3.0
73================
74
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000075The development cycle for Python 2.6 also saw the release of the first
76alphas of Python 3.0, and the development of 3.0 has influenced
77a number of features in 2.6.
78
79Python 3.0 is a far-ranging redesign of Python that breaks
80compatibility with the 2.x series. This means that existing Python
81code will need a certain amount of conversion in order to run on
82Python 3.0. However, not all the changes in 3.0 necessarily break
83compatibility. In cases where new features won't cause existing code
84to break, they've been backported to 2.6 and are described in this
85document in the appropriate place. Some of the 3.0-derived features
86are:
87
88* A :meth:`__complex__` method for converting objects to a complex number.
89* Alternate syntax for catching exceptions: ``except TypeError as exc``.
90* The addition of :func:`functools.reduce` as a synonym for the built-in
91 :func:`reduce` function.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000092
93A new command-line switch, :option:`-3`, enables warnings
94about features that will be removed in Python 3.0. You can run code
95with this switch to see how much work will be necessary to port
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000096code to 3.0. The value of this switch is available
97to Python code as the boolean variable ``sys.py3kwarning``,
98and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000099
100.. seealso::
101
102 The 3xxx series of PEPs, which describes the development process for
103 Python 3.0 and various features that have been accepted, rejected,
104 or are still under consideration.
105
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000106
107Development Changes
108==================================================
109
110While 2.6 was being developed, the Python development process
111underwent two significant changes: the developer group
112switched from SourceForge's issue tracker to a customized
113Roundup installation, and the documentation was converted from
114LaTeX to reStructured Text.
115
116
117New Issue Tracker: Roundup
118--------------------------------------------------
119
120XXX write this.
121
122
123New Documentation Format: ReStructured Text
124--------------------------------------------------
125
126Python's documentation had been written using LaTeX since the
127project's inception around 1989. At that time, most documentation was
128printed out for later study, not viewed online. LaTeX was widely used
129because it provided attractive printed output while
130remaining straightforward to write, once the basic rules
131of the markup have been learned.
132
133LaTeX is still used today for writing technical publications destined
134for printing, but the landscape for programming tools has shifted. We
135no longer print out reams of documentation; instead, we browse through
136it online and HTML is the most important format to support.
137Unfortunately, converting LaTeX to HTML is fairly complicated, and
138Fred L. Drake Jr., the Python documentation editor for many years,
139spent a lot of time wrestling the conversion process into shape.
140Occasionally people would suggest converting the documentation into
141SGML or, later, XML, but performing a good conversion is a major task
142and no one pursued the task to completion.
143
144During the 2.6 development cycle, Georg Brandl put a substantial
145effort into building a new toolchain called Sphinx
146for processing the documentation.
147The input format is reStructured Text,
148a markup commonly used in the Python community that supports
149custom extensions and directives. Sphinx concentrates
150on its HTML output, producing attractively styled
151and modern HTML. (XXX finish this -- mention new search feature)
152
153.. seealso::
154
155 `Docutils <http://docutils.sf.net>`__: The fundamental
156 reStructured Text parser and toolset.
157
158 `Documenting Python <XXX>`__: Describes how to write for
159 Python's documentation.
160
161
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000162PEP 343: The 'with' statement
163=============================
164
165The previous version, Python 2.5, added the ':keyword:`with`'
166statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000167import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000168be specially enabled; this means that :keyword:`with` is now always a
169keyword. The rest of this section is a copy of the corresponding
170section from "What's New in Python 2.5" document; if you read
171it back when Python 2.5 came out, you can skip the rest of this
172section.
173
174The ':keyword:`with`' statement clarifies code that previously would use
175``try...finally`` blocks to ensure that clean-up code is executed. In this
176section, I'll discuss the statement as it will commonly be used. In the next
177section, I'll examine the implementation details and show how to write objects
178for use with this statement.
179
180The ':keyword:`with`' statement is a new control-flow structure whose basic
181structure is::
182
183 with expression [as variable]:
184 with-block
185
186The expression is evaluated, and it should result in an object that supports the
187context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
188methods.
189
190The object's :meth:`__enter__` is called before *with-block* is executed and
191therefore can run set-up code. It also may return a value that is bound to the
192name *variable*, if given. (Note carefully that *variable* is *not* assigned
193the result of *expression*.)
194
195After execution of the *with-block* is finished, the object's :meth:`__exit__`
196method is called, even if the block raised an exception, and can therefore run
197clean-up code.
198
199Some standard Python objects now support the context management protocol and can
200be used with the ':keyword:`with`' statement. File objects are one example::
201
202 with open('/etc/passwd', 'r') as f:
203 for line in f:
204 print line
205 ... more processing code ...
206
207After this statement has executed, the file object in *f* will have been
208automatically closed, even if the :keyword:`for` loop raised an exception part-
209way through the block.
210
211.. note::
212
213 In this case, *f* is the same object created by :func:`open`, because
214 :meth:`file.__enter__` returns *self*.
215
216The :mod:`threading` module's locks and condition variables also support the
217':keyword:`with`' statement::
218
219 lock = threading.Lock()
220 with lock:
221 # Critical section of code
222 ...
223
224The lock is acquired before the block is executed and always released once the
225block is complete.
226
227The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
228to save and restore the current decimal context, which encapsulates the desired
229precision and rounding characteristics for computations::
230
231 from decimal import Decimal, Context, localcontext
232
233 # Displays with default precision of 28 digits
234 v = Decimal('578')
235 print v.sqrt()
236
237 with localcontext(Context(prec=16)):
238 # All code in this block uses a precision of 16 digits.
239 # The original context is restored on exiting the block.
240 print v.sqrt()
241
242
243.. _new-26-context-managers:
244
245Writing Context Managers
246------------------------
247
248Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
249people will only use ':keyword:`with`' in company with existing objects and
250don't need to know these details, so you can skip the rest of this section if
251you like. Authors of new objects will need to understand the details of the
252underlying implementation and should keep reading.
253
254A high-level explanation of the context management protocol is:
255
256* The expression is evaluated and should result in an object called a "context
257 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
258 methods.
259
260* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000261 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000262 discarded.
263
264* The code in *BLOCK* is executed.
265
266* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
267 is called with the exception details, the same values returned by
268 :func:`sys.exc_info`. The method's return value controls whether the exception
269 is re-raised: any false value re-raises the exception, and ``True`` will result
270 in suppressing it. You'll only rarely want to suppress the exception, because
271 if you do the author of the code containing the ':keyword:`with`' statement will
272 never realize anything went wrong.
273
274* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
275 called, but *type*, *value*, and *traceback* are all ``None``.
276
277Let's think through an example. I won't present detailed code but will only
278sketch the methods necessary for a database that supports transactions.
279
280(For people unfamiliar with database terminology: a set of changes to the
281database are grouped into a transaction. Transactions can be either committed,
282meaning that all the changes are written into the database, or rolled back,
283meaning that the changes are all discarded and the database is unchanged. See
284any database textbook for more information.)
285
286Let's assume there's an object representing a database connection. Our goal will
287be to let the user write code like this::
288
289 db_connection = DatabaseConnection()
290 with db_connection as cursor:
291 cursor.execute('insert into ...')
292 cursor.execute('delete from ...')
293 # ... more operations ...
294
295The transaction should be committed if the code in the block runs flawlessly or
296rolled back if there's an exception. Here's the basic interface for
297:class:`DatabaseConnection` that I'll assume::
298
299 class DatabaseConnection:
300 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000301 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000302 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000303 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000304 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000305 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000306 "Rolls back current transaction"
307
308The :meth:`__enter__` method is pretty easy, having only to start a new
309transaction. For this application the resulting cursor object would be a useful
310result, so the method will return it. The user can then add ``as cursor`` to
311their ':keyword:`with`' statement to bind the cursor to a variable name. ::
312
313 class DatabaseConnection:
314 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000315 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000316 # Code to start a new transaction
317 cursor = self.cursor()
318 return cursor
319
320The :meth:`__exit__` method is the most complicated because it's where most of
321the work has to be done. The method has to check if an exception occurred. If
322there was no exception, the transaction is committed. The transaction is rolled
323back if there was an exception.
324
325In the code below, execution will just fall off the end of the function,
326returning the default value of ``None``. ``None`` is false, so the exception
327will be re-raised automatically. If you wished, you could be more explicit and
328add a :keyword:`return` statement at the marked location. ::
329
330 class DatabaseConnection:
331 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000332 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000333 if tb is None:
334 # No exception, so commit
335 self.commit()
336 else:
337 # Exception occurred, so rollback.
338 self.rollback()
339 # return False
340
341
342.. _module-contextlib:
343
344The contextlib module
345---------------------
346
347The new :mod:`contextlib` module provides some functions and a decorator that
348are useful for writing objects for use with the ':keyword:`with`' statement.
349
350The decorator is called :func:`contextmanager`, and lets you write a single
351generator function instead of defining a new class. The generator should yield
352exactly one value. The code up to the :keyword:`yield` will be executed as the
353:meth:`__enter__` method, and the value yielded will be the method's return
354value that will get bound to the variable in the ':keyword:`with`' statement's
355:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
356executed in the :meth:`__exit__` method. Any exception raised in the block will
357be raised by the :keyword:`yield` statement.
358
359Our database example from the previous section could be written using this
360decorator as::
361
362 from contextlib import contextmanager
363
364 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000365 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000366 cursor = connection.cursor()
367 try:
368 yield cursor
369 except:
370 connection.rollback()
371 raise
372 else:
373 connection.commit()
374
375 db = DatabaseConnection()
376 with db_transaction(db) as cursor:
377 ...
378
379The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
380that combines a number of context managers so you don't need to write nested
381':keyword:`with`' statements. In this example, the single ':keyword:`with`'
382statement both starts a database transaction and acquires a thread lock::
383
384 lock = threading.Lock()
385 with nested (db_transaction(db), lock) as (cursor, locked):
386 ...
387
388Finally, the :func:`closing(object)` function returns *object* so that it can be
389bound to a variable, and calls ``object.close`` at the end of the block. ::
390
391 import urllib, sys
392 from contextlib import closing
393
394 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
395 for line in f:
396 sys.stdout.write(line)
397
398
399.. seealso::
400
401 :pep:`343` - The "with" statement
402 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
403 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
404 ':keyword:`with`' statement, which can be helpful in learning how the statement
405 works.
406
407 The documentation for the :mod:`contextlib` module.
408
409.. % ======================================================================
410
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000411.. _pep-0366:
412
413PEP 366: Explicit Relative Imports From a Main Module
414============================================================
415
416Python's :option:`-m` switch allows running a module as a script.
417When you ran a module that was located inside a package, relative
418imports didn't work correctly.
419
420The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
421When present, relative imports will be relative to the value of this
422attribute instead of the :attr:`__name__` attribute. PEP 302-style
423importers can then set :attr:`__package__`. The :mod:`runpy` module
424that implements the :option:`-m` switch now does this, so relative imports
425can now be used in scripts running from inside a package.
426
427.. % ======================================================================
428
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000429.. _pep-3110:
430
431PEP 3110: Exception-Handling Changes
432=====================================================
433
434One error that Python programmers occasionally make
435is the following::
436
437 try:
438 ...
439 except TypeError, ValueError:
440 ...
441
442The author is probably trying to catch both
443:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
444actually does something different: it will catch
445:exc:`TypeError` and bind the resulting exception object
446to the local name ``"ValueError"``. The correct code
447would have specified a tuple::
448
449 try:
450 ...
451 except (TypeError, ValueError):
452 ...
453
454This error is possible because the use of the comma here is ambiguous:
455does it indicate two different nodes in the parse tree, or a single
456node that's a tuple.
457
458Python 3.0 changes the syntax to make this unambiguous by replacing
459the comma with the word "as". To catch an exception and store the
460exception object in the variable ``exc``, you must write::
461
462 try:
463 ...
464 except TypeError as exc:
465 ...
466
467Python 3.0 will only support the use of "as", and therefore interprets
468the first example as catching two different exceptions. Python 2.6
469supports both the comma and "as", so existing code will continue to
470work.
471
472.. seealso::
473
474 :pep:`3110` - Catching Exceptions in Python 3000
475 PEP written and implemented by Collin Winter.
476
477.. % ======================================================================
478
479.. _pep-3119:
480
481PEP 3119: Abstract Base Classes
482=====================================================
483
484XXX
485
486.. seealso::
487
488 :pep:`3119` - Introducing Abstract Base Classes
489 PEP written by Guido van Rossum and Talin.
490 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000491 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000492
493Other Language Changes
494======================
495
496Here are all of the changes that Python 2.6 makes to the core Python language.
497
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000498* When calling a function using the ``**`` syntax to provide keyword
499 arguments, you are no longer required to use a Python dictionary;
500 any mapping will now work::
501
502 >>> def f(**kw):
503 ... print sorted(kw)
504 ...
505 >>> ud=UserDict.UserDict()
506 >>> ud['a'] = 1
507 >>> ud['b'] = 'string'
508 >>> f(**ud)
509 ['a', 'b']
510
511 .. % Patch 1686487
512
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000513* The built-in types now have improved support for extended slicing syntax,
514 where various combinations of ``(start, stop, step)`` are supplied.
515 Previously, the support was partial and certain corner cases wouldn't work.
516 (Implemented by Thomas Wouters.)
517
518 .. % Revision 57619
519
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000520* Properties now have two attributes,
521 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
522 adding a setter or deleter function to an existing property.
523 You would use them like this::
524
525 class C(object):
526 @property
527 def x(self):
528 return self._x
529
530 @x.setter
531 def x(self, value):
532 self._x = value
533
534 @x.deleter
535 def x(self):
536 del self._x
537
538
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000539* C functions and methods that use
540 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
541 have a :meth:`__complex__` method. In particular, the functions in the
542 :mod:`cmath` module will now accept objects with this method.
543 This is a backport of a Python 3.0 change.
544 (Contributed by Mark Dickinson.)
545
546 .. % Patch #1675423
547
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000548 A numerical nicety: when creating a complex number from two floats
549 on systems that support signed zeros (-0 and +0), the
550 :func:`complex()` constructor will now preserve the sign
551 of the zero.
552
553 .. % Patch 1507
554
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000555* Changes to the :class:`Exception` interface
556 as dictated by :pep:`352` continue to be made. For 2.6,
557 the :attr:`message` attribute is being deprecated in favor of the
558 :attr:`args` attribute.
559
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000560* The :exc:`GeneratorExit` exception now subclasses
561 :exc:`BaseException` instead of :exc:`Exception`. This means
562 that an exception handler that does ``except Exception:``
563 will not inadvertently catch :exc:`GeneratorExit`.
564 (Contributed by Chad Austin.)
565
566 .. % Patch #1537
567
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000568* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000569 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000570
571 .. % Patch 1444529
572
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000573* The :func:`complex` constructor now accepts strings containing
574 parenthesized complex numbers, letting ``complex(repr(cmplx))``
575 will now round-trip values. For example, ``complex('(3+4j)')``
576 now returns the value (3+4j).
577
578 .. % Patch 1491866
579
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000580* The string :meth:`translate` method now accepts ``None`` as the
581 translation table parameter, which is treated as the identity
582 transformation. This makes it easier to carry out operations
583 that only delete characters. (Contributed by Bengt Richter.)
584
585 .. % Patch 1193128
586
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000587* The built-in :func:`dir` function now checks for a :meth:`__dir__`
588 method on the objects it receives. This method must return a list
589 of strings containing the names of valid attributes for the object,
590 and lets the object control the value that :func:`dir` produces.
591 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +0000592 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000593
594 .. % Patch 1591665
595
Georg Brandl8ec7f652007-08-15 14:28:01 +0000596* An obscure change: when you use the the :func:`locals` function inside a
597 :keyword:`class` statement, the resulting dictionary no longer returns free
598 variables. (Free variables, in this case, are variables referred to in the
599 :keyword:`class` statement that aren't attributes of the class.)
600
601.. % ======================================================================
602
603
604Optimizations
605-------------
606
607* Internally, a bit is now set in type objects to indicate some of the standard
608 built-in types. This speeds up checking if an object is a subclass of one of
609 these types. (Contributed by Neal Norwitz.)
610
611The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
612benchmark around XX% faster than Python 2.5.
613
614.. % ======================================================================
615
616
617New, Improved, and Deprecated Modules
618=====================================
619
620As usual, Python's standard library received a number of enhancements and bug
621fixes. Here's a partial list of the most notable changes, sorted alphabetically
622by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
623complete list of changes, or look through the CVS logs for all the details.
624
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000625* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
626 available, instead of restricting itself to protocol 1.
627 (Contributed by W. Barnes.)
628
629 .. % Patch 1551443
630
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000631* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632 fieldnames)` is a factory function that creates subclasses of the standard tuple
633 whose fields are accessible by name as well as index. For example::
634
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000635 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000636 ... 'id name type size')
637 # Names are separated by spaces or commas.
638 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +0000639 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000640 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000642 >>> var = var_type(1, 'frequency', 'int', 4)
643 >>> print var[0], var.id # Equivalent
644 1 1
645 >>> print var[2], var.type # Equivalent
646 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +0000647 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000648 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettinger366523c2007-12-14 18:12:21 +0000649 >>> v2 = var._replace('name', 'amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000650 >>> v2
651 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000652
653 (Contributed by Raymond Hettinger.)
654
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000655* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +0000656 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000657 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +0000658 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000659 old items to be discarded.
660
661 ::
662
663 >>> from collections import deque
664 >>> dq=deque(maxlen=3)
665 >>> dq
666 deque([], maxlen=3)
667 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
668 >>> dq
669 deque([1, 2, 3], maxlen=3)
670 >>> dq.append(4)
671 >>> dq
672 deque([2, 3, 4], maxlen=3)
673
674 (Contributed by Raymond Hettinger.)
675
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000676* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
677 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
678
679 .. % Patch 1649190
680
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000681 The :mod:`ctypes` string, buffer and array types also have improved
682 support for extended slicing syntax,
683 where various combinations of ``(start, stop, step)`` are supplied.
684 (Implemented by Thomas Wouters.)
685
686 .. % Revision 57769
687
688
Georg Brandl8ec7f652007-08-15 14:28:01 +0000689* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000690 the display characters for a certain number of characters on a single line.
691 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000692
693 # Boldface text starting at y=0,x=21
694 # and affecting the rest of the line.
695 stdscr.chgat(0,21, curses.A_BOLD)
696
697 (Contributed by Fabian Kreutz.)
698
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000699* The :mod:`decimal` module was updated to version 1.66 of
700 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
701 include some methods for some basic mathematical functions such as
702 :meth:`exp` and :meth:`log10`::
703
704 >>> Decimal(1).exp()
705 Decimal("2.718281828459045235360287471")
706 >>> Decimal("2.7182818").ln()
707 Decimal("0.9999999895305022877376682436")
708 >>> Decimal(1000).log10()
709 Decimal("3")
710
711 (Implemented by Facundo Batista and Mark Dickinson.)
712
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000713* An optional ``timeout`` parameter was added to the
714 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
715 method, specifying a timeout measured in seconds. (Added by Facundo
716 Batista.)
717
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000718* The :func:`reduce` built-in function is also available in the
719 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
720 only available from :mod:`functools`; currently there are no plans
721 to drop the built-in in the 2.x series. (Patched by
722 Christian Heimes.)
723
724 .. % Patch 1739906
725
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726* The :func:`glob.glob` function can now return Unicode filenames if
727 a Unicode path was used and Unicode filenames are matched within the directory.
728
729 .. % Patch #1001604
730
731* The :mod:`gopherlib` module has been removed.
732
733* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
734 takes any number of iterables that return data *in sorted order*, and returns
735 a new iterator that returns the contents of all the iterators, also in sorted
736 order. For example::
737
738 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
739 [1, 2, 3, 5, 8, 9, 16]
740
741 (Contributed by Raymond Hettinger.)
742
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000743* An optional ``timeout`` parameter was added to the
744 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
745 class constructors, specifying a timeout measured in seconds.
746 (Added by Facundo Batista.)
747
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748* A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2,
749 ...[, fillvalue])`` makes tuples from each of the elements; if some of the
750 iterables are shorter than others, the missing values are set to *fillvalue*.
751 For example::
752
753 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
754 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
755
756 (Contributed by Raymond Hettinger.)
757
758* The :mod:`macfs` module has been removed. This in turn required the
759 :func:`macostools.touched` function to be removed because it depended on the
760 :mod:`macfs` module.
761
762 .. % Patch #1490190
763
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000764* The :mod:`new` module has been removed from Python 3.0.
765 Importing it therefore
766 triggers a warning message when Python is running in 3.0-warning
767 mode.
768
769* New functions in the :mod:`os` module include
770 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
771 and ``lchmod(path, mode)``, on operating systems that support these
772 functions. :func:`fchmod` and :func:`fchown` let you change the mode
773 and ownership of an opened file, and :func:`lchmod` changes the mode
774 of a symlink.
775
776 (Contributed by Georg Brandl and Christian Heimes.)
777
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000778* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000779 set to True, it will follow symlinks pointing to directories and
780 visit the directory's contents. For backward compatibility, the
781 parameter's default value is false. Note that the function can fall
782 into an infinite recursion if there's a symlink that points to a
783 parent directory.
784
785 .. % Patch 1273829
786
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000787* The ``os.environ`` object's :meth:`clear` method will now unset the
788 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000789 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000790
791 .. % Patch #1181
792
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000793* In the :mod:`os.path` module, the :func:`splitext` function
794 has been changed to not split on leading period characters.
795 This produces better results when operating on Unix's dot-files.
796 For example, ``os.path.splitext('.ipython')``
797 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
798
799 .. % Bug #115886
800
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000801 A new function, :func:`relpath(path, start)` returns a relative path
802 from the ``start`` path, if it's supplied, or from the current
803 working directory to the destination ``path``. (Contributed by
804 Richard Barran.)
805
806 .. % Patch 1339796
807
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000808 On Windows, :func:`os.path.expandvars` will now expand environment variables
809 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000810 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000811
812 .. % Patch 957650
813
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000814* The Python debugger provided by the :mod:`pdb` module
815 gained a new command: "run" restarts the Python program being debugged,
816 and can optionally take new command-line arguments for the program.
817 (Contributed by Rocky Bernstein.)
818
819 .. % Patch #1393667
820
Georg Brandl8ec7f652007-08-15 14:28:01 +0000821* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
822 are wrappers for the corresponding system calls (where they're available).
823 Constants for the flag values are defined in the :mod:`stat` module; some
824 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
825 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
826 file. (Contributed by M. Levinson.)
827
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000828* The :mod:`random` module's :class:`Random` objects can
829 now be pickled on a 32-bit system and unpickled on a 64-bit
830 system, and vice versa. Unfortunately, this change also means
831 that Python 2.6's :class:`Random` objects can't be unpickled correctly
832 on earlier versions of Python.
833 (Contributed by Shawn Ligocki.)
834
835 .. % Issue 1727780
836
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837* The :mod:`rgbimg` module has been removed.
838
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000839* The :mod:`sets` module has been deprecated; it's better to
840 use the built-in :class:`set` and :class:`frozenset` types.
841
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000842* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
843 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000844 interface identical to the existing :class:`SMTP` class. Both
845 class constructors also have an optional ``timeout`` parameter
846 that specifies a timeout for the initial connection attempt, measured in
847 seconds.
848
849 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000850 the module. LMTP is used in place of SMTP when transferring e-mail
851 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000852
853 (SMTP over SSL contributed by Monty Taylor; timeout parameter
854 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000855 Hedstrom.)
856
857 .. % Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +0000858
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000859* A new variable in the :mod:`sys` module,
860 :attr:`float_info`, is a dictionary
861 containing information about the platform's floating-point support
862 derived from the :file:`float.h` file. Key/value pairs
863 in this dictionary include
864 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
865 (smallest difference between 1.0 and the next largest value
866 representable), and several others. (Contributed by Christian Heimes.)
867
868 .. % Patch 1534
869
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +0000870* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
871 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
872 format that was already supported. The default format
873 is GNU tar; specify the ``format`` parameter to open a file
874 using a different format::
875
876 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
877
878 The new ``errors`` parameter lets you specify an error handling
879 scheme for character conversions: the three standard ways Python can
880 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
881 special value ``'utf-8'``, which replaces bad characters with their
882 UTF-8 representation. Character conversions occur because the PAX
883 format supports Unicode filenames, defaulting to UTF-8 encoding.
884
885 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
886 a function that can be used to exclude certain filenames from
887 an archive.
888 The function must take a filename and return true if the file
889 should be excluded or false if it should be archived.
890 The function is applied to both the name initially passed to :meth:`add`
891 and to the names of files in recursively-added directories.
892
893 (All changes contributed by Lars Gustäbel).
894
895* An optional ``timeout`` parameter was added to the
896 :class:`telnetlib.Telnet` class constructor, specifying a timeout
897 measured in seconds. (Added by Facundo Batista.)
898
899* The :class:`tempfile.NamedTemporaryFile` class usually deletes
900 the temporary file it created when the file is closed. This
901 behaviour can now be changed by passing ``delete=False`` to the
902 constructor. (Contributed by Damien Miller.)
903
904 .. % Patch #1537850
905
906* The :mod:`test.test_support` module now contains a
907 :func:`EnvironmentVarGuard`
908 context manager that supports temporarily changing environment variables and
909 automatically restores them to their old values.
910
911 Another context manager, :class:`TransientResource`, can surround calls
912 to resources that may or may not be available; it will catch and
913 ignore a specified list of exceptions. For example,
914 a network test may ignore certain failures when connecting to an
915 external web site::
916
917 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
918 f = urllib.urlopen('https://sf.net')
919 ...
920
921 (Contributed by Brett Cannon.)
922
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000923* The :mod:`textwrap` module can now preserve existing whitespace
924 at the beginnings and ends of the newly-created lines
925 by specifying ``drop_whitespace=False``
926 as an argument::
927
928 >>> S = """This sentence has a bunch of extra whitespace."""
929 >>> print textwrap.fill(S, width=15)
930 This sentence
931 has a bunch
932 of extra
933 whitespace.
934 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
935 This sentence
936 has a bunch
937 of extra
938 whitespace.
939 >>>
940
941 .. % Patch #1581073
942
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000943* The :mod:`timeit` module now accepts callables as well as strings
944 for the statement being timed and for the setup code.
945 Two convenience functions were added for creating
946 :class:`Timer` instances:
947 ``repeat(stmt, setup, time, repeat, number)`` and
948 ``timeit(stmt, setup, time, number)`` create an instance and call
949 the corresponding method. (Contributed by Erik Demaine.)
950
951 .. % Patch #1533909
952
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000953* An optional ``timeout`` parameter was added to the
954 :func:`urllib.urlopen` function and the
955 :class:`urllib.ftpwrapper` class constructor, as well as the
956 :func:`urllib2.urlopen` function. The parameter specifies a timeout
957 measured in seconds. For example::
958
959 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
960 Traceback (most recent call last):
961 ...
962 urllib2.URLError: <urlopen error timed out>
963 >>>
964
965 (Added by Facundo Batista.)
966
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000967* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000968 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000969 their socket by passing True as the ``bind_and_activate``
970 constructor parameter. This can be used to modify the instance's
971 :attr:`allow_reuse_address` attribute before calling the
972 :meth:`server_bind` and :meth:`server_activate` methods to
973 open the socket and begin listening for connections.
974 (Contributed by Peter Parente.)
975
976 .. % Patch 1599845
977
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000978 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
979 attribute; if true, the exception and formatted traceback are returned
980 as HTTP headers "X-Exception" and "X-Traceback". This feature is
981 for debugging purposes only and should not be used on production servers
982 because the tracebacks could possibly reveal passwords or other sensitive
983 information. (Contributed by Alan McIntyre as part of his
984 project for Google's Summer of Code 2007.)
985
Georg Brandl8ec7f652007-08-15 14:28:01 +0000986.. % ======================================================================
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000987.. % whole new modules get described in subsections here
988
989Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +0000990--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000991
992Bill Janssen made extensive improvements to Python 2.6's support for
993SSL.
994
995XXX use ssl.sslsocket - subclass of socket.socket.
996
997XXX Can specify if certificate is required, and obtain certificate info
998by calling getpeercert method.
999
1000XXX sslwrap() behaves like socket.ssl
1001
1002XXX Certain features require the OpenSSL package to be installed, notably
1003 the 'openssl' binary.
1004
1005.. seealso::
1006
1007 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001008
1009.. % ======================================================================
1010
1011
1012Build and C API Changes
1013=======================
1014
1015Changes to Python's build process and to the C API include:
1016
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001017* Python 2.6 can be built with Microsoft Visual Studio 2008.
1018 See the :file:`PCbuild9` directory for the build files.
1019 (Implemented by Christian Heimes.)
1020
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001021* The BerkeleyDB module now has a C API object, available as
1022 ``bsddb.db.api``. This object can be used by other C extensions
1023 that wish to use the :mod:`bsddb` module for their own purposes.
1024 (Contributed by Duncan Grisby.)
1025
1026 .. % Patch 1551895
1027
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001028* Several functions return information about the platform's
1029 floating-point support. :cfunc:`PyFloat_GetMax` returns
1030 the maximum representable floating point value,
1031 and :cfunc:`PyFloat_GetMin` returns the minimum
1032 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1033 containing more information from the :file:`float.h` file, such as
1034 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1035 (smallest difference between 1.0 and the next largest value
1036 representable), and several others.
1037
1038 .. % Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001039
1040.. % ======================================================================
1041
1042
1043Port-Specific Changes
1044---------------------
1045
1046Platform-specific changes go here.
1047
1048.. % ======================================================================
1049
1050
1051.. _section-other:
1052
1053Other Changes and Fixes
1054=======================
1055
1056As usual, there were a bunch of other improvements and bugfixes scattered
1057throughout the source tree. A search through the change logs finds there were
1058XXX patches applied and YYY bugs fixed between Python 2.5 and 2.6. Both figures
1059are likely to be underestimates.
1060
1061Some of the more notable changes are:
1062
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001063* Details will go here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001064
1065.. % ======================================================================
1066
1067
1068Porting to Python 2.6
1069=====================
1070
1071This section lists previously described changes that may require changes to your
1072code:
1073
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001074* The :mod:`socket` module exception :exc:`socket.error` now inherits
1075 from :exc:`IOError`. Previously it wasn't a subclass of
1076 :exc:`StandardError` but now it is, through :exc:`IOError`.
1077 (Implemented by Gregory P. Smith.)
1078
1079 .. % http://bugs.python.org/issue1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00001080
1081.. % ======================================================================
1082
1083
1084.. _acks:
1085
1086Acknowledgements
1087================
1088
1089The author would like to thank the following people for offering suggestions,
1090corrections and assistance with various drafts of this article: .
1091