blob: 28916e84b7d6e8dcf8852a2a39290d30e515ca76 [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
75.. % XXX add general comment about Python 3.0 features in 2.6
76
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000077The development cycle for Python 2.6 also saw the release of the first
78alphas of Python 3.0, and the development of 3.0 has influenced
79a number of features in 2.6.
80
81Python 3.0 is a far-ranging redesign of Python that breaks
82compatibility with the 2.x series. This means that existing Python
83code will need a certain amount of conversion in order to run on
84Python 3.0. However, not all the changes in 3.0 necessarily break
85compatibility. In cases where new features won't cause existing code
86to break, they've been backported to 2.6 and are described in this
87document in the appropriate place. Some of the 3.0-derived features
88are:
89
90* A :meth:`__complex__` method for converting objects to a complex number.
91* Alternate syntax for catching exceptions: ``except TypeError as exc``.
92* The addition of :func:`functools.reduce` as a synonym for the built-in
93 :func:`reduce` function.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000094
95A new command-line switch, :option:`-3`, enables warnings
96about features that will be removed in Python 3.0. You can run code
97with this switch to see how much work will be necessary to port
98code to 3.0.
99
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
106PEP 343: The 'with' statement
107=============================
108
109The previous version, Python 2.5, added the ':keyword:`with`'
110statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000111import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000112be specially enabled; this means that :keyword:`with` is now always a
113keyword. The rest of this section is a copy of the corresponding
114section from "What's New in Python 2.5" document; if you read
115it back when Python 2.5 came out, you can skip the rest of this
116section.
117
118The ':keyword:`with`' statement clarifies code that previously would use
119``try...finally`` blocks to ensure that clean-up code is executed. In this
120section, I'll discuss the statement as it will commonly be used. In the next
121section, I'll examine the implementation details and show how to write objects
122for use with this statement.
123
124The ':keyword:`with`' statement is a new control-flow structure whose basic
125structure is::
126
127 with expression [as variable]:
128 with-block
129
130The expression is evaluated, and it should result in an object that supports the
131context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
132methods.
133
134The object's :meth:`__enter__` is called before *with-block* is executed and
135therefore can run set-up code. It also may return a value that is bound to the
136name *variable*, if given. (Note carefully that *variable* is *not* assigned
137the result of *expression*.)
138
139After execution of the *with-block* is finished, the object's :meth:`__exit__`
140method is called, even if the block raised an exception, and can therefore run
141clean-up code.
142
143Some standard Python objects now support the context management protocol and can
144be used with the ':keyword:`with`' statement. File objects are one example::
145
146 with open('/etc/passwd', 'r') as f:
147 for line in f:
148 print line
149 ... more processing code ...
150
151After this statement has executed, the file object in *f* will have been
152automatically closed, even if the :keyword:`for` loop raised an exception part-
153way through the block.
154
155.. note::
156
157 In this case, *f* is the same object created by :func:`open`, because
158 :meth:`file.__enter__` returns *self*.
159
160The :mod:`threading` module's locks and condition variables also support the
161':keyword:`with`' statement::
162
163 lock = threading.Lock()
164 with lock:
165 # Critical section of code
166 ...
167
168The lock is acquired before the block is executed and always released once the
169block is complete.
170
171The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
172to save and restore the current decimal context, which encapsulates the desired
173precision and rounding characteristics for computations::
174
175 from decimal import Decimal, Context, localcontext
176
177 # Displays with default precision of 28 digits
178 v = Decimal('578')
179 print v.sqrt()
180
181 with localcontext(Context(prec=16)):
182 # All code in this block uses a precision of 16 digits.
183 # The original context is restored on exiting the block.
184 print v.sqrt()
185
186
187.. _new-26-context-managers:
188
189Writing Context Managers
190------------------------
191
192Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
193people will only use ':keyword:`with`' in company with existing objects and
194don't need to know these details, so you can skip the rest of this section if
195you like. Authors of new objects will need to understand the details of the
196underlying implementation and should keep reading.
197
198A high-level explanation of the context management protocol is:
199
200* The expression is evaluated and should result in an object called a "context
201 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
202 methods.
203
204* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000205 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000206 discarded.
207
208* The code in *BLOCK* is executed.
209
210* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
211 is called with the exception details, the same values returned by
212 :func:`sys.exc_info`. The method's return value controls whether the exception
213 is re-raised: any false value re-raises the exception, and ``True`` will result
214 in suppressing it. You'll only rarely want to suppress the exception, because
215 if you do the author of the code containing the ':keyword:`with`' statement will
216 never realize anything went wrong.
217
218* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
219 called, but *type*, *value*, and *traceback* are all ``None``.
220
221Let's think through an example. I won't present detailed code but will only
222sketch the methods necessary for a database that supports transactions.
223
224(For people unfamiliar with database terminology: a set of changes to the
225database are grouped into a transaction. Transactions can be either committed,
226meaning that all the changes are written into the database, or rolled back,
227meaning that the changes are all discarded and the database is unchanged. See
228any database textbook for more information.)
229
230Let's assume there's an object representing a database connection. Our goal will
231be to let the user write code like this::
232
233 db_connection = DatabaseConnection()
234 with db_connection as cursor:
235 cursor.execute('insert into ...')
236 cursor.execute('delete from ...')
237 # ... more operations ...
238
239The transaction should be committed if the code in the block runs flawlessly or
240rolled back if there's an exception. Here's the basic interface for
241:class:`DatabaseConnection` that I'll assume::
242
243 class DatabaseConnection:
244 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000245 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000246 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000247 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000248 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000249 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000250 "Rolls back current transaction"
251
252The :meth:`__enter__` method is pretty easy, having only to start a new
253transaction. For this application the resulting cursor object would be a useful
254result, so the method will return it. The user can then add ``as cursor`` to
255their ':keyword:`with`' statement to bind the cursor to a variable name. ::
256
257 class DatabaseConnection:
258 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000259 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000260 # Code to start a new transaction
261 cursor = self.cursor()
262 return cursor
263
264The :meth:`__exit__` method is the most complicated because it's where most of
265the work has to be done. The method has to check if an exception occurred. If
266there was no exception, the transaction is committed. The transaction is rolled
267back if there was an exception.
268
269In the code below, execution will just fall off the end of the function,
270returning the default value of ``None``. ``None`` is false, so the exception
271will be re-raised automatically. If you wished, you could be more explicit and
272add a :keyword:`return` statement at the marked location. ::
273
274 class DatabaseConnection:
275 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000276 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000277 if tb is None:
278 # No exception, so commit
279 self.commit()
280 else:
281 # Exception occurred, so rollback.
282 self.rollback()
283 # return False
284
285
286.. _module-contextlib:
287
288The contextlib module
289---------------------
290
291The new :mod:`contextlib` module provides some functions and a decorator that
292are useful for writing objects for use with the ':keyword:`with`' statement.
293
294The decorator is called :func:`contextmanager`, and lets you write a single
295generator function instead of defining a new class. The generator should yield
296exactly one value. The code up to the :keyword:`yield` will be executed as the
297:meth:`__enter__` method, and the value yielded will be the method's return
298value that will get bound to the variable in the ':keyword:`with`' statement's
299:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
300executed in the :meth:`__exit__` method. Any exception raised in the block will
301be raised by the :keyword:`yield` statement.
302
303Our database example from the previous section could be written using this
304decorator as::
305
306 from contextlib import contextmanager
307
308 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000309 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000310 cursor = connection.cursor()
311 try:
312 yield cursor
313 except:
314 connection.rollback()
315 raise
316 else:
317 connection.commit()
318
319 db = DatabaseConnection()
320 with db_transaction(db) as cursor:
321 ...
322
323The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
324that combines a number of context managers so you don't need to write nested
325':keyword:`with`' statements. In this example, the single ':keyword:`with`'
326statement both starts a database transaction and acquires a thread lock::
327
328 lock = threading.Lock()
329 with nested (db_transaction(db), lock) as (cursor, locked):
330 ...
331
332Finally, the :func:`closing(object)` function returns *object* so that it can be
333bound to a variable, and calls ``object.close`` at the end of the block. ::
334
335 import urllib, sys
336 from contextlib import closing
337
338 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
339 for line in f:
340 sys.stdout.write(line)
341
342
343.. seealso::
344
345 :pep:`343` - The "with" statement
346 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
347 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
348 ':keyword:`with`' statement, which can be helpful in learning how the statement
349 works.
350
351 The documentation for the :mod:`contextlib` module.
352
353.. % ======================================================================
354
355.. _pep-3110:
356
357PEP 3110: Exception-Handling Changes
358=====================================================
359
360One error that Python programmers occasionally make
361is the following::
362
363 try:
364 ...
365 except TypeError, ValueError:
366 ...
367
368The author is probably trying to catch both
369:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
370actually does something different: it will catch
371:exc:`TypeError` and bind the resulting exception object
372to the local name ``"ValueError"``. The correct code
373would have specified a tuple::
374
375 try:
376 ...
377 except (TypeError, ValueError):
378 ...
379
380This error is possible because the use of the comma here is ambiguous:
381does it indicate two different nodes in the parse tree, or a single
382node that's a tuple.
383
384Python 3.0 changes the syntax to make this unambiguous by replacing
385the comma with the word "as". To catch an exception and store the
386exception object in the variable ``exc``, you must write::
387
388 try:
389 ...
390 except TypeError as exc:
391 ...
392
393Python 3.0 will only support the use of "as", and therefore interprets
394the first example as catching two different exceptions. Python 2.6
395supports both the comma and "as", so existing code will continue to
396work.
397
398.. seealso::
399
400 :pep:`3110` - Catching Exceptions in Python 3000
401 PEP written and implemented by Collin Winter.
402
403.. % ======================================================================
404
405.. _pep-3119:
406
407PEP 3119: Abstract Base Classes
408=====================================================
409
410XXX
411
412.. seealso::
413
414 :pep:`3119` - Introducing Abstract Base Classes
415 PEP written by Guido van Rossum and Talin.
416 Implemented by XXX.
417 Backported to 2.6 by Benjamin Aranguren (with Alex Martelli).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000418
419Other Language Changes
420======================
421
422Here are all of the changes that Python 2.6 makes to the core Python language.
423
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000424* When calling a function using the ``**`` syntax to provide keyword
425 arguments, you are no longer required to use a Python dictionary;
426 any mapping will now work::
427
428 >>> def f(**kw):
429 ... print sorted(kw)
430 ...
431 >>> ud=UserDict.UserDict()
432 >>> ud['a'] = 1
433 >>> ud['b'] = 'string'
434 >>> f(**ud)
435 ['a', 'b']
436
437 .. % Patch 1686487
438
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000439* The built-in types now have improved support for extended slicing syntax,
440 where various combinations of ``(start, stop, step)`` are supplied.
441 Previously, the support was partial and certain corner cases wouldn't work.
442 (Implemented by Thomas Wouters.)
443
444 .. % Revision 57619
445
446* C functions and methods that use
447 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
448 have a :meth:`__complex__` method. In particular, the functions in the
449 :mod:`cmath` module will now accept objects with this method.
450 This is a backport of a Python 3.0 change.
451 (Contributed by Mark Dickinson.)
452
453 .. % Patch #1675423
454
455* Changes to the :class:`Exception` interface
456 as dictated by :pep:`352` continue to be made. For 2.6,
457 the :attr:`message` attribute is being deprecated in favor of the
458 :attr:`args` attribute.
459
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000460* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000461 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000462
463 .. % Patch 1444529
464
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000465* The :func:`complex` constructor now accepts strings containing
466 parenthesized complex numbers, letting ``complex(repr(cmplx))``
467 will now round-trip values. For example, ``complex('(3+4j)')``
468 now returns the value (3+4j).
469
470 .. % Patch 1491866
471
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000472* The string :meth:`translate` method now accepts ``None`` as the
473 translation table parameter, which is treated as the identity
474 transformation. This makes it easier to carry out operations
475 that only delete characters. (Contributed by Bengt Richter.)
476
477 .. % Patch 1193128
478
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000479* The built-in :func:`dir` function now checks for a :meth:`__dir__`
480 method on the objects it receives. This method must return a list
481 of strings containing the names of valid attributes for the object,
482 and lets the object control the value that :func:`dir` produces.
483 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +0000484 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000485
486 .. % Patch 1591665
487
Georg Brandl8ec7f652007-08-15 14:28:01 +0000488* An obscure change: when you use the the :func:`locals` function inside a
489 :keyword:`class` statement, the resulting dictionary no longer returns free
490 variables. (Free variables, in this case, are variables referred to in the
491 :keyword:`class` statement that aren't attributes of the class.)
492
493.. % ======================================================================
494
495
496Optimizations
497-------------
498
499* Internally, a bit is now set in type objects to indicate some of the standard
500 built-in types. This speeds up checking if an object is a subclass of one of
501 these types. (Contributed by Neal Norwitz.)
502
503The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
504benchmark around XX% faster than Python 2.5.
505
506.. % ======================================================================
507
508
509New, Improved, and Deprecated Modules
510=====================================
511
512As usual, Python's standard library received a number of enhancements and bug
513fixes. Here's a partial list of the most notable changes, sorted alphabetically
514by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
515complete list of changes, or look through the CVS logs for all the details.
516
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000517* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
518 available, instead of restricting itself to protocol 1.
519 (Contributed by W. Barnes.)
520
521 .. % Patch 1551443
522
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000523* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000524 fieldnames)` is a factory function that creates subclasses of the standard tuple
525 whose fields are accessible by name as well as index. For example::
526
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000527 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000528 ... 'id name type size')
529 # Names are separated by spaces or commas.
530 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +0000531 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000532 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000533
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000534 >>> var = var_type(1, 'frequency', 'int', 4)
535 >>> print var[0], var.id # Equivalent
536 1 1
537 >>> print var[2], var.type # Equivalent
538 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +0000539 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000540 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettinger366523c2007-12-14 18:12:21 +0000541 >>> v2 = var._replace('name', 'amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000542 >>> v2
543 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000544
545 (Contributed by Raymond Hettinger.)
546
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000547* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +0000548 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000549 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +0000550 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000551 old items to be discarded.
552
553 ::
554
555 >>> from collections import deque
556 >>> dq=deque(maxlen=3)
557 >>> dq
558 deque([], maxlen=3)
559 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
560 >>> dq
561 deque([1, 2, 3], maxlen=3)
562 >>> dq.append(4)
563 >>> dq
564 deque([2, 3, 4], maxlen=3)
565
566 (Contributed by Raymond Hettinger.)
567
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000568* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
569 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
570
571 .. % Patch 1649190
572
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000573 The :mod:`ctypes` string, buffer and array types also have improved
574 support for extended slicing syntax,
575 where various combinations of ``(start, stop, step)`` are supplied.
576 (Implemented by Thomas Wouters.)
577
578 .. % Revision 57769
579
580
Georg Brandl8ec7f652007-08-15 14:28:01 +0000581* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000582 the display characters for a certain number of characters on a single line.
583 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000584
585 # Boldface text starting at y=0,x=21
586 # and affecting the rest of the line.
587 stdscr.chgat(0,21, curses.A_BOLD)
588
589 (Contributed by Fabian Kreutz.)
590
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000591* The :mod:`decimal` module was updated to version 1.66 of
592 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
593 include some methods for some basic mathematical functions such as
594 :meth:`exp` and :meth:`log10`::
595
596 >>> Decimal(1).exp()
597 Decimal("2.718281828459045235360287471")
598 >>> Decimal("2.7182818").ln()
599 Decimal("0.9999999895305022877376682436")
600 >>> Decimal(1000).log10()
601 Decimal("3")
602
603 (Implemented by Facundo Batista and Mark Dickinson.)
604
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000605* An optional ``timeout`` parameter was added to the
606 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
607 method, specifying a timeout measured in seconds. (Added by Facundo
608 Batista.)
609
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000610* The :func:`reduce` built-in function is also available in the
611 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
612 only available from :mod:`functools`; currently there are no plans
613 to drop the built-in in the 2.x series. (Patched by
614 Christian Heimes.)
615
616 .. % Patch 1739906
617
Georg Brandl8ec7f652007-08-15 14:28:01 +0000618* The :func:`glob.glob` function can now return Unicode filenames if
619 a Unicode path was used and Unicode filenames are matched within the directory.
620
621 .. % Patch #1001604
622
623* The :mod:`gopherlib` module has been removed.
624
625* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
626 takes any number of iterables that return data *in sorted order*, and returns
627 a new iterator that returns the contents of all the iterators, also in sorted
628 order. For example::
629
630 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
631 [1, 2, 3, 5, 8, 9, 16]
632
633 (Contributed by Raymond Hettinger.)
634
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000635* An optional ``timeout`` parameter was added to the
636 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
637 class constructors, specifying a timeout measured in seconds.
638 (Added by Facundo Batista.)
639
Georg Brandl8ec7f652007-08-15 14:28:01 +0000640* A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2,
641 ...[, fillvalue])`` makes tuples from each of the elements; if some of the
642 iterables are shorter than others, the missing values are set to *fillvalue*.
643 For example::
644
645 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
646 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
647
648 (Contributed by Raymond Hettinger.)
649
650* The :mod:`macfs` module has been removed. This in turn required the
651 :func:`macostools.touched` function to be removed because it depended on the
652 :mod:`macfs` module.
653
654 .. % Patch #1490190
655
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000656* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000657 set to True, it will follow symlinks pointing to directories and
658 visit the directory's contents. For backward compatibility, the
659 parameter's default value is false. Note that the function can fall
660 into an infinite recursion if there's a symlink that points to a
661 parent directory.
662
663 .. % Patch 1273829
664
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000665* The ``os.environ`` object's :meth:`clear` method will now unset the
666 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000667 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000668
669 .. % Patch #1181
670
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000671* In the :mod:`os.path` module, the :func:`splitext` function
672 has been changed to not split on leading period characters.
673 This produces better results when operating on Unix's dot-files.
674 For example, ``os.path.splitext('.ipython')``
675 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
676
677 .. % Bug #115886
678
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000679 A new function, :func:`relpath(path, start)` returns a relative path
680 from the ``start`` path, if it's supplied, or from the current
681 working directory to the destination ``path``. (Contributed by
682 Richard Barran.)
683
684 .. % Patch 1339796
685
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000686 On Windows, :func:`os.path.expandvars` will now expand environment variables
687 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000688 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000689
690 .. % Patch 957650
691
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000692* The Python debugger provided by the :mod:`pdb` module
693 gained a new command: "run" restarts the Python program being debugged,
694 and can optionally take new command-line arguments for the program.
695 (Contributed by Rocky Bernstein.)
696
697 .. % Patch #1393667
698
Georg Brandl8ec7f652007-08-15 14:28:01 +0000699* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
700 are wrappers for the corresponding system calls (where they're available).
701 Constants for the flag values are defined in the :mod:`stat` module; some
702 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
703 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
704 file. (Contributed by M. Levinson.)
705
706* The :mod:`rgbimg` module has been removed.
707
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000708* The :mod:`sets` module has been deprecated; it's better to
709 use the built-in :class:`set` and :class:`frozenset` types.
710
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000711* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
712 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000713 interface identical to the existing :class:`SMTP` class. Both
714 class constructors also have an optional ``timeout`` parameter
715 that specifies a timeout for the initial connection attempt, measured in
716 seconds.
717
718 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000719 the module. LMTP is used in place of SMTP when transferring e-mail
720 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000721
722 (SMTP over SSL contributed by Monty Taylor; timeout parameter
723 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000724 Hedstrom.)
725
726 .. % Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +0000728* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
729 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
730 format that was already supported. The default format
731 is GNU tar; specify the ``format`` parameter to open a file
732 using a different format::
733
734 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
735
736 The new ``errors`` parameter lets you specify an error handling
737 scheme for character conversions: the three standard ways Python can
738 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
739 special value ``'utf-8'``, which replaces bad characters with their
740 UTF-8 representation. Character conversions occur because the PAX
741 format supports Unicode filenames, defaulting to UTF-8 encoding.
742
743 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
744 a function that can be used to exclude certain filenames from
745 an archive.
746 The function must take a filename and return true if the file
747 should be excluded or false if it should be archived.
748 The function is applied to both the name initially passed to :meth:`add`
749 and to the names of files in recursively-added directories.
750
751 (All changes contributed by Lars Gustäbel).
752
753* An optional ``timeout`` parameter was added to the
754 :class:`telnetlib.Telnet` class constructor, specifying a timeout
755 measured in seconds. (Added by Facundo Batista.)
756
757* The :class:`tempfile.NamedTemporaryFile` class usually deletes
758 the temporary file it created when the file is closed. This
759 behaviour can now be changed by passing ``delete=False`` to the
760 constructor. (Contributed by Damien Miller.)
761
762 .. % Patch #1537850
763
764* The :mod:`test.test_support` module now contains a
765 :func:`EnvironmentVarGuard`
766 context manager that supports temporarily changing environment variables and
767 automatically restores them to their old values.
768
769 Another context manager, :class:`TransientResource`, can surround calls
770 to resources that may or may not be available; it will catch and
771 ignore a specified list of exceptions. For example,
772 a network test may ignore certain failures when connecting to an
773 external web site::
774
775 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
776 f = urllib.urlopen('https://sf.net')
777 ...
778
779 (Contributed by Brett Cannon.)
780
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000781* The :mod:`textwrap` module can now preserve existing whitespace
782 at the beginnings and ends of the newly-created lines
783 by specifying ``drop_whitespace=False``
784 as an argument::
785
786 >>> S = """This sentence has a bunch of extra whitespace."""
787 >>> print textwrap.fill(S, width=15)
788 This sentence
789 has a bunch
790 of extra
791 whitespace.
792 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
793 This sentence
794 has a bunch
795 of extra
796 whitespace.
797 >>>
798
799 .. % Patch #1581073
800
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000801* The :mod:`timeit` module now accepts callables as well as strings
802 for the statement being timed and for the setup code.
803 Two convenience functions were added for creating
804 :class:`Timer` instances:
805 ``repeat(stmt, setup, time, repeat, number)`` and
806 ``timeit(stmt, setup, time, number)`` create an instance and call
807 the corresponding method. (Contributed by Erik Demaine.)
808
809 .. % Patch #1533909
810
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000811* An optional ``timeout`` parameter was added to the
812 :func:`urllib.urlopen` function and the
813 :class:`urllib.ftpwrapper` class constructor, as well as the
814 :func:`urllib2.urlopen` function. The parameter specifies a timeout
815 measured in seconds. For example::
816
817 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
818 Traceback (most recent call last):
819 ...
820 urllib2.URLError: <urlopen error timed out>
821 >>>
822
823 (Added by Facundo Batista.)
824
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000825* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000826 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000827 their socket by passing True as the ``bind_and_activate``
828 constructor parameter. This can be used to modify the instance's
829 :attr:`allow_reuse_address` attribute before calling the
830 :meth:`server_bind` and :meth:`server_activate` methods to
831 open the socket and begin listening for connections.
832 (Contributed by Peter Parente.)
833
834 .. % Patch 1599845
835
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000836 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
837 attribute; if true, the exception and formatted traceback are returned
838 as HTTP headers "X-Exception" and "X-Traceback". This feature is
839 for debugging purposes only and should not be used on production servers
840 because the tracebacks could possibly reveal passwords or other sensitive
841 information. (Contributed by Alan McIntyre as part of his
842 project for Google's Summer of Code 2007.)
843
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844.. % ======================================================================
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000845.. % whole new modules get described in subsections here
846
847Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +0000848--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000849
850Bill Janssen made extensive improvements to Python 2.6's support for
851SSL.
852
853XXX use ssl.sslsocket - subclass of socket.socket.
854
855XXX Can specify if certificate is required, and obtain certificate info
856by calling getpeercert method.
857
858XXX sslwrap() behaves like socket.ssl
859
860XXX Certain features require the OpenSSL package to be installed, notably
861 the 'openssl' binary.
862
863.. seealso::
864
865 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866
867.. % ======================================================================
868
869
870Build and C API Changes
871=======================
872
873Changes to Python's build process and to the C API include:
874
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +0000875* Python 2.6 can be built with Microsoft Visual Studio 2008.
876 See the :file:`PCbuild9` directory for the build files.
877 (Implemented by Christian Heimes.)
878
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000879* The BerkeleyDB module now has a C API object, available as
880 ``bsddb.db.api``. This object can be used by other C extensions
881 that wish to use the :mod:`bsddb` module for their own purposes.
882 (Contributed by Duncan Grisby.)
883
884 .. % Patch 1551895
885
Georg Brandl8ec7f652007-08-15 14:28:01 +0000886
887.. % ======================================================================
888
889
890Port-Specific Changes
891---------------------
892
893Platform-specific changes go here.
894
895.. % ======================================================================
896
897
898.. _section-other:
899
900Other Changes and Fixes
901=======================
902
903As usual, there were a bunch of other improvements and bugfixes scattered
904throughout the source tree. A search through the change logs finds there were
905XXX patches applied and YYY bugs fixed between Python 2.5 and 2.6. Both figures
906are likely to be underestimates.
907
908Some of the more notable changes are:
909
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000910* Details will go here.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000911
912.. % ======================================================================
913
914
915Porting to Python 2.6
916=====================
917
918This section lists previously described changes that may require changes to your
919code:
920
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000921* The :mod:`socket` module exception :exc:`socket.error` now inherits
922 from :exc:`IOError`. Previously it wasn't a subclass of
923 :exc:`StandardError` but now it is, through :exc:`IOError`.
924 (Implemented by Gregory P. Smith.)
925
926 .. % http://bugs.python.org/issue1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +0000927
928.. % ======================================================================
929
930
931.. _acks:
932
933Acknowledgements
934================
935
936The author would like to thank the following people for offering suggestions,
937corrections and assistance with various drafts of this article: .
938