blob: 45eadf191520cae8fa72f93ce718ad5407fe7e4c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001****************************
2 What's New in Python 2.6
3****************************
4
Georg Brandlb19be572007-12-29 10:57:00 +00005.. XXX mention switch to Roundup for bug tracking
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
45 % Patch 12345
46 XXX Describe the transmogrify() function added to the socket
47 module.
48 (Contributed by P.Y. Developer.)
49
50 This saves the maintainer the effort of going through the SVN log
51 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
96to Python code as the boolean variable ``sys.py3kwarning``,
97and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000098
99.. seealso::
100
101 The 3xxx series of PEPs, which describes the development process for
102 Python 3.0 and various features that have been accepted, rejected,
103 or are still under consideration.
104
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000105
106Development Changes
107==================================================
108
109While 2.6 was being developed, the Python development process
110underwent two significant changes: the developer group
111switched from SourceForge's issue tracker to a customized
112Roundup installation, and the documentation was converted from
113LaTeX to reStructured Text.
114
115
116New Issue Tracker: Roundup
117--------------------------------------------------
118
119XXX write this.
120
121
122New Documentation Format: ReStructured Text
123--------------------------------------------------
124
125Python's documentation had been written using LaTeX since the
126project's inception around 1989. At that time, most documentation was
127printed out for later study, not viewed online. LaTeX was widely used
128because it provided attractive printed output while
129remaining straightforward to write, once the basic rules
130of the markup have been learned.
131
132LaTeX is still used today for writing technical publications destined
133for printing, but the landscape for programming tools has shifted. We
134no longer print out reams of documentation; instead, we browse through
135it online and HTML is the most important format to support.
136Unfortunately, converting LaTeX to HTML is fairly complicated, and
137Fred L. Drake Jr., the Python documentation editor for many years,
138spent a lot of time wrestling the conversion process into shape.
139Occasionally people would suggest converting the documentation into
140SGML or, later, XML, but performing a good conversion is a major task
141and no one pursued the task to completion.
142
143During the 2.6 development cycle, Georg Brandl put a substantial
144effort into building a new toolchain called Sphinx
145for processing the documentation.
146The input format is reStructured Text,
147a markup commonly used in the Python community that supports
148custom extensions and directives. Sphinx concentrates
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000149on HTML output, producing attractively styled
150and modern HTML, but printed output is still supported through
151conversion to LaTeX as an output format.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000152
153.. seealso::
154
155 `Docutils <http://docutils.sf.net>`__: The fundamental
156 reStructured Text parser and toolset.
157
Georg Brandlb19be572007-12-29 10:57:00 +0000158 :ref:`documenting-index`: Describes how to write for
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000159 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
Georg Brandlb19be572007-12-29 10:57:00 +0000409.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000410
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
Georg Brandlb19be572007-12-29 10:57:00 +0000427.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000428
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000429.. ::
430
431 .. _pep-0370:
432
433 PEP 370: XXX
434 =====================================================
435
436 When you run Python, the module search page ``sys.modules`` usually
437 includes a directory whose path ends in ``"site-packages"``. This
438 directory is intended to hold locally-installed packages available to
439 all users on a machine or using a particular site installation.
440
441 Python 2.6 introduces a convention for user-specific site directories.
442
443 .. seealso::
444
445 :pep:`370` - XXX
446
447 PEP written by XXX; implemented by Christian Heimes.
448
449
450.. ======================================================================
451
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000452.. _pep-3110:
453
454PEP 3110: Exception-Handling Changes
455=====================================================
456
457One error that Python programmers occasionally make
458is the following::
459
460 try:
461 ...
462 except TypeError, ValueError:
463 ...
464
465The author is probably trying to catch both
466:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
467actually does something different: it will catch
468:exc:`TypeError` and bind the resulting exception object
469to the local name ``"ValueError"``. The correct code
470would have specified a tuple::
471
472 try:
473 ...
474 except (TypeError, ValueError):
475 ...
476
477This error is possible because the use of the comma here is ambiguous:
478does it indicate two different nodes in the parse tree, or a single
479node that's a tuple.
480
481Python 3.0 changes the syntax to make this unambiguous by replacing
482the comma with the word "as". To catch an exception and store the
483exception object in the variable ``exc``, you must write::
484
485 try:
486 ...
487 except TypeError as exc:
488 ...
489
490Python 3.0 will only support the use of "as", and therefore interprets
491the first example as catching two different exceptions. Python 2.6
492supports both the comma and "as", so existing code will continue to
493work.
494
495.. seealso::
496
497 :pep:`3110` - Catching Exceptions in Python 3000
498 PEP written and implemented by Collin Winter.
499
Georg Brandlb19be572007-12-29 10:57:00 +0000500.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000501
502.. _pep-3119:
503
504PEP 3119: Abstract Base Classes
505=====================================================
506
507XXX
508
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000509How to identify a file object?
510
511ABCs are a collection of classes describing various interfaces.
512Classes can derive from an ABC to indicate they support that ABC's
513interface. Concrete classes should obey the semantics specified by
514an ABC, but Python can't check this; it's up to the implementor.
515
516A metaclass lets you declare that an existing class or type
517derives from a particular ABC. You can even
518
519class AppendableSequence:
520 __metaclass__ = ABCMeta
521
522AppendableSequence.register(list)
523assert issubclass(list, AppendableSequence)
524assert isinstance([], AppendableSequence)
525
526@abstractmethod decorator -- you can't instantiate classes w/
527an abstract method.
528
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000529::
530
531 @abstractproperty decorator
532 @abstractproperty
533 def readonly(self):
534 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000535
536
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000537.. seealso::
538
539 :pep:`3119` - Introducing Abstract Base Classes
540 PEP written by Guido van Rossum and Talin.
541 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000542 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543
544Other Language Changes
545======================
546
547Here are all of the changes that Python 2.6 makes to the core Python language.
548
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000549* When calling a function using the ``**`` syntax to provide keyword
550 arguments, you are no longer required to use a Python dictionary;
551 any mapping will now work::
552
553 >>> def f(**kw):
554 ... print sorted(kw)
555 ...
556 >>> ud=UserDict.UserDict()
557 >>> ud['a'] = 1
558 >>> ud['b'] = 'string'
559 >>> f(**ud)
560 ['a', 'b']
561
Georg Brandlb19be572007-12-29 10:57:00 +0000562 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000563
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000564* The built-in types now have improved support for extended slicing syntax,
565 where various combinations of ``(start, stop, step)`` are supplied.
566 Previously, the support was partial and certain corner cases wouldn't work.
567 (Implemented by Thomas Wouters.)
568
Georg Brandlb19be572007-12-29 10:57:00 +0000569 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000570
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000571* Properties now have two attributes,
572 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
573 adding a setter or deleter function to an existing property.
574 You would use them like this::
575
576 class C(object):
577 @property
578 def x(self):
579 return self._x
580
581 @x.setter
582 def x(self, value):
583 self._x = value
584
585 @x.deleter
586 def x(self):
587 del self._x
588
589
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000590* C functions and methods that use
591 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
592 have a :meth:`__complex__` method. In particular, the functions in the
593 :mod:`cmath` module will now accept objects with this method.
594 This is a backport of a Python 3.0 change.
595 (Contributed by Mark Dickinson.)
596
Georg Brandlb19be572007-12-29 10:57:00 +0000597 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000598
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000599 A numerical nicety: when creating a complex number from two floats
600 on systems that support signed zeros (-0 and +0), the
601 :func:`complex()` constructor will now preserve the sign
602 of the zero.
603
Georg Brandlb19be572007-12-29 10:57:00 +0000604 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000605
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000606* More floating-point features were also added. The :func:`float` function
607 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000608 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000609 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +0000610 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000611
612 .. Patch 1635.
613
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000614 Other functions in the :mod:`math` module, :func:`isinf` and
615 :func:`isnan`, return true if their floating-point argument is
616 infinite or Not A Number.
617 .. Patch 1640
618 The ``math.copysign(x, y)`` function
619 copies the sign bit of an IEEE 754 number, returning the absolute
620 value of *x* combined with the sign bit of *y*. For example,
621 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
622 Heimes.)
623
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000624* Changes to the :class:`Exception` interface
625 as dictated by :pep:`352` continue to be made. For 2.6,
626 the :attr:`message` attribute is being deprecated in favor of the
627 :attr:`args` attribute.
628
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000629* The :exc:`GeneratorExit` exception now subclasses
630 :exc:`BaseException` instead of :exc:`Exception`. This means
631 that an exception handler that does ``except Exception:``
632 will not inadvertently catch :exc:`GeneratorExit`.
633 (Contributed by Chad Austin.)
634
Georg Brandlb19be572007-12-29 10:57:00 +0000635 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000636
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000637* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000638 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000639
Georg Brandlb19be572007-12-29 10:57:00 +0000640 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000641
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000642* The :func:`complex` constructor now accepts strings containing
643 parenthesized complex numbers, letting ``complex(repr(cmplx))``
644 will now round-trip values. For example, ``complex('(3+4j)')``
645 now returns the value (3+4j).
646
Georg Brandlb19be572007-12-29 10:57:00 +0000647 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000648
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000649* The string :meth:`translate` method now accepts ``None`` as the
650 translation table parameter, which is treated as the identity
651 transformation. This makes it easier to carry out operations
652 that only delete characters. (Contributed by Bengt Richter.)
653
Georg Brandlb19be572007-12-29 10:57:00 +0000654 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000655
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000656* The built-in :func:`dir` function now checks for a :meth:`__dir__`
657 method on the objects it receives. This method must return a list
658 of strings containing the names of valid attributes for the object,
659 and lets the object control the value that :func:`dir` produces.
660 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +0000661 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000662
Georg Brandlb19be572007-12-29 10:57:00 +0000663 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000664
Georg Brandl8ec7f652007-08-15 14:28:01 +0000665* An obscure change: when you use the the :func:`locals` function inside a
666 :keyword:`class` statement, the resulting dictionary no longer returns free
667 variables. (Free variables, in this case, are variables referred to in the
668 :keyword:`class` statement that aren't attributes of the class.)
669
Georg Brandlb19be572007-12-29 10:57:00 +0000670.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000671
672
673Optimizations
674-------------
675
Georg Brandlaf30b282008-01-15 06:55:56 +0000676* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000677 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +0000678 for a particular class; once cached, the interpreter doesn't need to
679 traverse base classes to figure out the right method to call.
680 The cache is cleared if a base class or the class itself is modified,
681 so the cache should remain correct even in the face of Python's dynamic
682 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000683 (Original optimization implemented by Armin Rigo, updated for
684 Python 2.6 by Kevin Jacobs.)
685
686 .. % Patch 1700288
687
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000688* All of the functions in the :mod:`struct` module have been rewritten in
689 C, thanks to work at the Need For Speed sprint.
690 (Contributed by Raymond Hettinger.)
691
Georg Brandl8ec7f652007-08-15 14:28:01 +0000692* Internally, a bit is now set in type objects to indicate some of the standard
693 built-in types. This speeds up checking if an object is a subclass of one of
694 these types. (Contributed by Neal Norwitz.)
695
696The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
697benchmark around XX% faster than Python 2.5.
698
Georg Brandlb19be572007-12-29 10:57:00 +0000699.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
701
702New, Improved, and Deprecated Modules
703=====================================
704
705As usual, Python's standard library received a number of enhancements and bug
706fixes. Here's a partial list of the most notable changes, sorted alphabetically
707by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
708complete list of changes, or look through the CVS logs for all the details.
709
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000710* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
711 available, instead of restricting itself to protocol 1.
712 (Contributed by W. Barnes.)
713
Georg Brandlb19be572007-12-29 10:57:00 +0000714 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000715
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000716* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000717 fieldnames)` is a factory function that creates subclasses of the standard tuple
718 whose fields are accessible by name as well as index. For example::
719
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000720 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000721 ... 'id name type size')
722 # Names are separated by spaces or commas.
723 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +0000724 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000725 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000727 >>> var = var_type(1, 'frequency', 'int', 4)
728 >>> print var[0], var.id # Equivalent
729 1 1
730 >>> print var[2], var.type # Equivalent
731 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +0000732 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000733 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettinger366523c2007-12-14 18:12:21 +0000734 >>> v2 = var._replace('name', 'amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000735 >>> v2
736 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000737
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000738 Where the new :class:`namedtuple` type proved suitable, the standard
739 library has been modified to return them. For example,
740 the :meth:`Decimal.as_tuple` method now returns a named tuple with
741 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
742
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743 (Contributed by Raymond Hettinger.)
744
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000745* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +0000746 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000747 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +0000748 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000749 old items to be discarded.
750
751 ::
752
753 >>> from collections import deque
754 >>> dq=deque(maxlen=3)
755 >>> dq
756 deque([], maxlen=3)
757 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
758 >>> dq
759 deque([1, 2, 3], maxlen=3)
760 >>> dq.append(4)
761 >>> dq
762 deque([2, 3, 4], maxlen=3)
763
764 (Contributed by Raymond Hettinger.)
765
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000766* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
767 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
768
Georg Brandlb19be572007-12-29 10:57:00 +0000769 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000770
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000771 The :mod:`ctypes` string, buffer and array types also have improved
772 support for extended slicing syntax,
773 where various combinations of ``(start, stop, step)`` are supplied.
774 (Implemented by Thomas Wouters.)
775
Georg Brandlb19be572007-12-29 10:57:00 +0000776 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000777
778
Georg Brandl8ec7f652007-08-15 14:28:01 +0000779* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000780 the display characters for a certain number of characters on a single line.
781 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
783 # Boldface text starting at y=0,x=21
784 # and affecting the rest of the line.
785 stdscr.chgat(0,21, curses.A_BOLD)
786
787 (Contributed by Fabian Kreutz.)
788
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000789* The :mod:`decimal` module was updated to version 1.66 of
790 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
791 include some methods for some basic mathematical functions such as
792 :meth:`exp` and :meth:`log10`::
793
794 >>> Decimal(1).exp()
795 Decimal("2.718281828459045235360287471")
796 >>> Decimal("2.7182818").ln()
797 Decimal("0.9999999895305022877376682436")
798 >>> Decimal(1000).log10()
799 Decimal("3")
800
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000801 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
802 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
803
804 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
805 support added by Raymond Hettinger.)
806
807* The :mod:`difflib` module's :class:`SequenceMatcher` class
808 now returns named tuples representing matches.
809 In addition to behaving like tuples, the returned values
810 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
811 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000812
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000813* An optional ``timeout`` parameter was added to the
814 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
815 method, specifying a timeout measured in seconds. (Added by Facundo
816 Batista.)
817
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000818* The :func:`reduce` built-in function is also available in the
819 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
820 only available from :mod:`functools`; currently there are no plans
821 to drop the built-in in the 2.x series. (Patched by
822 Christian Heimes.)
823
Georg Brandlb19be572007-12-29 10:57:00 +0000824 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000825
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826* The :func:`glob.glob` function can now return Unicode filenames if
827 a Unicode path was used and Unicode filenames are matched within the directory.
828
Georg Brandlb19be572007-12-29 10:57:00 +0000829 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +0000830
831* The :mod:`gopherlib` module has been removed.
832
833* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
834 takes any number of iterables that return data *in sorted order*, and returns
835 a new iterator that returns the contents of all the iterators, also in sorted
836 order. For example::
837
838 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
839 [1, 2, 3, 5, 8, 9, 16]
840
841 (Contributed by Raymond Hettinger.)
842
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000843* An optional ``timeout`` parameter was added to the
844 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
845 class constructors, specifying a timeout measured in seconds.
846 (Added by Facundo Batista.)
847
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000848* Most of the :mod:`inspect` module's functions, such as
849 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
850 In addition to behaving like tuples, the elements of the return value
851 can also be accessed as attributes.
852 (Contributed by Raymond Hettinger.)
853
Georg Brandl8ec7f652007-08-15 14:28:01 +0000854* A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2,
855 ...[, fillvalue])`` makes tuples from each of the elements; if some of the
856 iterables are shorter than others, the missing values are set to *fillvalue*.
857 For example::
858
859 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
860 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
861
862 (Contributed by Raymond Hettinger.)
863
864* The :mod:`macfs` module has been removed. This in turn required the
865 :func:`macostools.touched` function to be removed because it depended on the
866 :mod:`macfs` module.
867
Georg Brandlb19be572007-12-29 10:57:00 +0000868 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +0000869
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000870* The :mod:`new` module has been removed from Python 3.0.
871 Importing it therefore
872 triggers a warning message when Python is running in 3.0-warning
873 mode.
874
875* New functions in the :mod:`os` module include
876 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
877 and ``lchmod(path, mode)``, on operating systems that support these
878 functions. :func:`fchmod` and :func:`fchown` let you change the mode
879 and ownership of an opened file, and :func:`lchmod` changes the mode
880 of a symlink.
881
882 (Contributed by Georg Brandl and Christian Heimes.)
883
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000884* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000885 set to True, it will follow symlinks pointing to directories and
886 visit the directory's contents. For backward compatibility, the
887 parameter's default value is false. Note that the function can fall
888 into an infinite recursion if there's a symlink that points to a
889 parent directory.
890
Georg Brandlb19be572007-12-29 10:57:00 +0000891 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000892
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000893* The ``os.environ`` object's :meth:`clear` method will now unset the
894 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000895 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000896
Georg Brandlb19be572007-12-29 10:57:00 +0000897 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000898
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000899* In the :mod:`os.path` module, the :func:`splitext` function
900 has been changed to not split on leading period characters.
901 This produces better results when operating on Unix's dot-files.
902 For example, ``os.path.splitext('.ipython')``
903 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
904
Georg Brandlb19be572007-12-29 10:57:00 +0000905 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000906
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000907 A new function, :func:`relpath(path, start)` returns a relative path
908 from the ``start`` path, if it's supplied, or from the current
909 working directory to the destination ``path``. (Contributed by
910 Richard Barran.)
911
Georg Brandlb19be572007-12-29 10:57:00 +0000912 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000913
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000914 On Windows, :func:`os.path.expandvars` will now expand environment variables
915 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000916 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000917
Georg Brandlb19be572007-12-29 10:57:00 +0000918 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000919
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000920* The Python debugger provided by the :mod:`pdb` module
921 gained a new command: "run" restarts the Python program being debugged,
922 and can optionally take new command-line arguments for the program.
923 (Contributed by Rocky Bernstein.)
924
Georg Brandlb19be572007-12-29 10:57:00 +0000925 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000926
Georg Brandl8ec7f652007-08-15 14:28:01 +0000927* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
928 are wrappers for the corresponding system calls (where they're available).
929 Constants for the flag values are defined in the :mod:`stat` module; some
930 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
931 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
932 file. (Contributed by M. Levinson.)
933
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +0000934* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
935 their :attr:`buffer_size` attribute to change the size of the buffer
936 used to hold character data.
937 (Contributed by Achim Gaedke.)
938
939 .. Patch 1137
940
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000941* The :mod:`random` module's :class:`Random` objects can
942 now be pickled on a 32-bit system and unpickled on a 64-bit
943 system, and vice versa. Unfortunately, this change also means
944 that Python 2.6's :class:`Random` objects can't be unpickled correctly
945 on earlier versions of Python.
946 (Contributed by Shawn Ligocki.)
947
Georg Brandlb19be572007-12-29 10:57:00 +0000948 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000949
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000950* Long regular expression searches carried out by the :mod:`re`
951 module will now check for signals being delivered, so especially
952 long searches can now be interrupted.
953 (Contributed by Josh Hoyt and Ralf Schmitt.)
954
955 .. % Patch 846388
956
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957* The :mod:`rgbimg` module has been removed.
958
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +0000959* The :mod:`sets` module has been deprecated; it's better to
960 use the built-in :class:`set` and :class:`frozenset` types.
961
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000962* Integrating signal handling with GUI handling event loops
963 like those used by Tkinter or GTk+ has long been a problem; most
964 software ends up polling, waking up every fraction of a second. Thi
965 The :mod:`signal` module can now make this more efficient.
966 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
967 to be used; when a signal is received, a byte is written to that
968 file descriptor. There's also a C-level function,
969 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
970
971 Event loops will use this by opening a pipe to create two descriptors,
972 one for reading and one for writing. The writeable descriptor
973 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
974 will be added to the list of descriptors monitored by the event loop via
975 :cfunc:`select` or :cfunc:`poll`.
976 On receiving a signal, a byte will be written and the main event loop
977 will be woken up, without the need to poll.
978
979 Contributed by Adam Olsen.
980
981 .. % Patch 1583
982
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000983* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
984 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000985 interface identical to the existing :class:`SMTP` class. Both
986 class constructors also have an optional ``timeout`` parameter
987 that specifies a timeout for the initial connection attempt, measured in
988 seconds.
989
990 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000991 the module. LMTP is used in place of SMTP when transferring e-mail
992 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000993
994 (SMTP over SSL contributed by Monty Taylor; timeout parameter
995 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000996 Hedstrom.)
997
Georg Brandlb19be572007-12-29 10:57:00 +0000998 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +0000999
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001000* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1001 a high-performance non-IP-based protocol designed for use in clustered
1002 environments. TIPC addresses are 4- or 5-tuples.
1003 (Contributed by Alberto Bertogli.)
1004
1005 .. Patch #1646
1006
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001007* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001008 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001009 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001010 derived from the :file:`float.h` file. Attributes of this object
1011 include
1012 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001013 (smallest difference between 1.0 and the next largest value
1014 representable), and several others. (Contributed by Christian Heimes.)
1015
Georg Brandlb19be572007-12-29 10:57:00 +00001016 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001017
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001018 Information about the command-line arguments supplied to the Python
1019 interpreter are available as attributes of a ``sys.flags`` named
1020 tuple. For example, the :attr:`verbose` attribute is true if Python
1021 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1022 These attributes are all read-only.
1023 (Contributed by Christian Heimes.)
1024
1025 The :attr:`dont_write_bytecode` variable controls whether Python
1026 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1027 If this variable is true, the compiled files are not written. The
1028 variable can be set by Python code, by supplying the :option:`-B`
1029 switch, or by setting the :envvar:`PYTHONDONTWRITEBYTECODE`
1030 environment variable to any non-empty string when running the Python
1031 interpreter.
1032
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001033* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1034 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1035 format that was already supported. The default format
1036 is GNU tar; specify the ``format`` parameter to open a file
1037 using a different format::
1038
1039 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1040
1041 The new ``errors`` parameter lets you specify an error handling
1042 scheme for character conversions: the three standard ways Python can
1043 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1044 special value ``'utf-8'``, which replaces bad characters with their
1045 UTF-8 representation. Character conversions occur because the PAX
1046 format supports Unicode filenames, defaulting to UTF-8 encoding.
1047
1048 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1049 a function that can be used to exclude certain filenames from
1050 an archive.
1051 The function must take a filename and return true if the file
1052 should be excluded or false if it should be archived.
1053 The function is applied to both the name initially passed to :meth:`add`
1054 and to the names of files in recursively-added directories.
1055
1056 (All changes contributed by Lars Gustäbel).
1057
1058* An optional ``timeout`` parameter was added to the
1059 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1060 measured in seconds. (Added by Facundo Batista.)
1061
1062* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1063 the temporary file it created when the file is closed. This
1064 behaviour can now be changed by passing ``delete=False`` to the
1065 constructor. (Contributed by Damien Miller.)
1066
Georg Brandlb19be572007-12-29 10:57:00 +00001067 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001068
1069* The :mod:`test.test_support` module now contains a
1070 :func:`EnvironmentVarGuard`
1071 context manager that supports temporarily changing environment variables and
1072 automatically restores them to their old values.
1073
1074 Another context manager, :class:`TransientResource`, can surround calls
1075 to resources that may or may not be available; it will catch and
1076 ignore a specified list of exceptions. For example,
1077 a network test may ignore certain failures when connecting to an
1078 external web site::
1079
1080 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
1081 f = urllib.urlopen('https://sf.net')
1082 ...
1083
1084 (Contributed by Brett Cannon.)
1085
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001086* The :mod:`textwrap` module can now preserve existing whitespace
1087 at the beginnings and ends of the newly-created lines
1088 by specifying ``drop_whitespace=False``
1089 as an argument::
1090
1091 >>> S = """This sentence has a bunch of extra whitespace."""
1092 >>> print textwrap.fill(S, width=15)
1093 This sentence
1094 has a bunch
1095 of extra
1096 whitespace.
1097 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
1098 This sentence
1099 has a bunch
1100 of extra
1101 whitespace.
1102 >>>
1103
Georg Brandlb19be572007-12-29 10:57:00 +00001104 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001105
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001106* The :mod:`timeit` module now accepts callables as well as strings
1107 for the statement being timed and for the setup code.
1108 Two convenience functions were added for creating
1109 :class:`Timer` instances:
1110 ``repeat(stmt, setup, time, repeat, number)`` and
1111 ``timeit(stmt, setup, time, number)`` create an instance and call
1112 the corresponding method. (Contributed by Erik Demaine.)
1113
Georg Brandlb19be572007-12-29 10:57:00 +00001114 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001115
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001116* An optional ``timeout`` parameter was added to the
1117 :func:`urllib.urlopen` function and the
1118 :class:`urllib.ftpwrapper` class constructor, as well as the
1119 :func:`urllib2.urlopen` function. The parameter specifies a timeout
1120 measured in seconds. For example::
1121
1122 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
1123 Traceback (most recent call last):
1124 ...
1125 urllib2.URLError: <urlopen error timed out>
1126 >>>
1127
1128 (Added by Facundo Batista.)
1129
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001130* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001131 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001132 their socket by passing True as the ``bind_and_activate``
1133 constructor parameter. This can be used to modify the instance's
1134 :attr:`allow_reuse_address` attribute before calling the
1135 :meth:`server_bind` and :meth:`server_activate` methods to
1136 open the socket and begin listening for connections.
1137 (Contributed by Peter Parente.)
1138
Georg Brandlb19be572007-12-29 10:57:00 +00001139 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001140
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001141 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
1142 attribute; if true, the exception and formatted traceback are returned
1143 as HTTP headers "X-Exception" and "X-Traceback". This feature is
1144 for debugging purposes only and should not be used on production servers
1145 because the tracebacks could possibly reveal passwords or other sensitive
1146 information. (Contributed by Alan McIntyre as part of his
1147 project for Google's Summer of Code 2007.)
1148
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001149* The :mod:`zipfile` module's :class:`ZipFile` class now has
1150 :meth:`extract` and :meth:`extractall` methods that will unpack
1151 a single file or all the files in the archive to the current directory, or
1152 to a specified directory::
1153
1154 z = zipfile.ZipFile('python-251.zip')
1155
1156 # Unpack a single file, writing it relative to the /tmp directory.
1157 z.extract('Python/sysmodule.c', '/tmp')
1158
1159 # Unpack all the files in the archive.
1160 z.extractall()
1161
1162 (Contributed by Alan McIntyre.)
1163 .. % Patch 467924
1164
Georg Brandlb19be572007-12-29 10:57:00 +00001165.. ======================================================================
1166.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001167
1168Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00001169--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001170
1171Bill Janssen made extensive improvements to Python 2.6's support for
1172SSL.
1173
1174XXX use ssl.sslsocket - subclass of socket.socket.
1175
1176XXX Can specify if certificate is required, and obtain certificate info
1177by calling getpeercert method.
1178
1179XXX sslwrap() behaves like socket.ssl
1180
1181XXX Certain features require the OpenSSL package to be installed, notably
1182 the 'openssl' binary.
1183
1184.. seealso::
1185
1186 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001187
Georg Brandlb19be572007-12-29 10:57:00 +00001188.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001189
1190
1191Build and C API Changes
1192=======================
1193
1194Changes to Python's build process and to the C API include:
1195
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001196* Python 2.6 can be built with Microsoft Visual Studio 2008.
1197 See the :file:`PCbuild9` directory for the build files.
1198 (Implemented by Christian Heimes.)
1199
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001200* The BerkeleyDB module now has a C API object, available as
1201 ``bsddb.db.api``. This object can be used by other C extensions
1202 that wish to use the :mod:`bsddb` module for their own purposes.
1203 (Contributed by Duncan Grisby.)
1204
Georg Brandlb19be572007-12-29 10:57:00 +00001205 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001206
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001207* Several functions return information about the platform's
1208 floating-point support. :cfunc:`PyFloat_GetMax` returns
1209 the maximum representable floating point value,
1210 and :cfunc:`PyFloat_GetMin` returns the minimum
1211 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1212 containing more information from the :file:`float.h` file, such as
1213 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1214 (smallest difference between 1.0 and the next largest value
1215 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001216 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001217
Georg Brandlb19be572007-12-29 10:57:00 +00001218 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001219
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001220* Python's C API now includes two functions for case-insensitive string
1221 comparisions, ``PyOS_stricmp(char*, char*)``
1222 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001223 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001224
1225 .. Issue 1635
1226
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001227* Some macros were renamed to make it clearer that they are macros,
1228 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001229 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
1230 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. Macros for backward
Christian Heimesd0d7d872008-01-04 02:03:25 +00001231 compatibility are still available for Python 2.6.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001232
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001233 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001234
Georg Brandlb19be572007-12-29 10:57:00 +00001235.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001236
1237
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001238Port-Specific Changes: Windows
1239-----------------------------------
1240
1241* The :mod:`msvcrt` module now supports
1242 both the normal and wide char variants of the console I/O
1243 API. The :func:`getwch` function reads a keypress and returns a Unicode
1244 value, as does the :func:`getwche` function. The :func:`putwch` function
1245 takes a Unicode character and writes it to the console.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001246
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001247* The :mod:`_winreg` module now has a function,
1248 :func:`ExpandEnvironmentStrings`,
1249 that expands environment variable references such as ``%NAME%``
1250 in an input string. The handle objects provided by this
1251 module now support the context protocol, so they can be used
1252 in :keyword:`with` statements.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001253
Georg Brandlb19be572007-12-29 10:57:00 +00001254.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001255
1256
1257.. _section-other:
1258
1259Other Changes and Fixes
1260=======================
1261
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001262As usual, there were a bunch of other improvements and bugfixes
1263scattered throughout the source tree. A search through the change
1264logs finds there were XXX patches applied and YYY bugs fixed between
1265Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001266
1267Some of the more notable changes are:
1268
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001269* It's now possible to prevent Python from writing any :file:`.pyc`
1270 or :file:`.pyo` files by either supplying the :option:`-B` switch
1271 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
1272 to any non-empty string when running the Python interpreter. These
1273 are used to set a :attr:`dont_write_bytecode` variable in the
1274 :mod:`sys` module. Python code can change this variable to
1275 control whether bytecode files are subsequently written.
1276 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001277
Georg Brandlb19be572007-12-29 10:57:00 +00001278.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001279
1280
1281Porting to Python 2.6
1282=====================
1283
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001284This section lists previously described changes, and a few
1285esoteric bugfixes, that may require changes to your
Georg Brandl8ec7f652007-08-15 14:28:01 +00001286code:
1287
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001288* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001289 now clears any existing contents of the deque
1290 before adding elements from the iterable. This change makes the
1291 behavior match that of ``list.__init__()``.
1292
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001293* The :class:`Decimal` constructor now accepts leading and trailing
1294 whitespace when passed a string. Previously it would raise an
1295 :exc:`InvalidOperation` exception. On the other hand, the
1296 :meth:`create_decimal` method of :class:`Context` objects now
1297 explicitly disallows extra whitespace, raising a
1298 :exc:`ConversionSyntax` exception.
1299
1300* Due to an implementation accident, if you passed a file path to
1301 the built-in :func:`__import__` function, it would actually import
1302 the specified file. This was never intended to work, however, and
1303 the implementation now explicitly checks for this case and raises
1304 an :exc:`ImportError`.
1305
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001306* The :mod:`socket` module exception :exc:`socket.error` now inherits
1307 from :exc:`IOError`. Previously it wasn't a subclass of
1308 :exc:`StandardError` but now it is, through :exc:`IOError`.
1309 (Implemented by Gregory P. Smith.)
1310
Georg Brandlb19be572007-12-29 10:57:00 +00001311 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00001312
Georg Brandlb19be572007-12-29 10:57:00 +00001313.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001314
1315
1316.. _acks:
1317
1318Acknowledgements
1319================
1320
1321The author would like to thank the following people for offering suggestions,
1322corrections and assistance with various drafts of this article: .
1323