blob: 0361255446b6fed2254f4392b3ca70a2aa7434ef [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001****************************
2 What's New in Python 2.6
3****************************
4
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00005.. XXX add trademark info for Apple, Microsoft, SourceForge.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00006
Georg Brandl8ec7f652007-08-15 14:28:01 +00007:Author: A.M. Kuchling
8:Release: |release|
9:Date: |today|
10
Georg Brandlb19be572007-12-29 10:57:00 +000011.. $Id: whatsnew26.tex 55746 2007-06-02 18:33:53Z neal.norwitz $
12 Rules for maintenance:
13
14 * Anyone can add text to this document. Do not spend very much time
15 on the wording of your changes, because your text will probably
16 get rewritten to some degree.
17
18 * The maintainer will go through Misc/NEWS periodically and add
19 changes; it's therefore more important to add your changes to
20 Misc/NEWS than to this file.
21
22 * This is not a complete list of every single change; completeness
23 is the purpose of Misc/NEWS. Some changes I consider too small
24 or esoteric to include. If such a change is added to the text,
25 I'll just remove it. (This is another reason you shouldn't spend
26 too much time on writing your addition.)
27
28 * If you want to draw your new text to the attention of the
29 maintainer, add 'XXX' to the beginning of the paragraph or
30 section.
31
32 * It's OK to just add a fragmentary note about a change. For
33 example: "XXX Describe the transmogrify() function added to the
34 socket module." The maintainer will research the change and
35 write the necessary text.
36
37 * You can comment out your additions if you like, but it's not
38 necessary (especially when a final release is some months away).
39
40 * Credit the author of a patch or bugfix. Just the name is
41 sufficient; the e-mail address isn't necessary.
42
43 * It's helpful to add the bug/patch number as a comment:
44
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +000045 .. Patch 12345
Georg Brandlb19be572007-12-29 10:57:00 +000046 XXX Describe the transmogrify() function added to the socket
47 module.
48 (Contributed by P.Y. Developer.)
49
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +000050 This saves the maintainer the effort of going through the SVN logs
Georg Brandlb19be572007-12-29 10:57:00 +000051 when researching a change.
Georg Brandl8ec7f652007-08-15 14:28:01 +000052
53This article explains the new features in Python 2.6. No release date for
54Python 2.6 has been set; it will probably be released in mid 2008.
55
56This article doesn't attempt to provide a complete specification of the new
57features, but instead provides a convenient overview. For full details, you
58should refer to the documentation for Python 2.6. If you want to understand the
59complete implementation and design rationale, refer to the PEP for a particular
60new feature.
61
Georg Brandlb19be572007-12-29 10:57:00 +000062.. Compare with previous release in 2 - 3 sentences here.
63 add hyperlink when the documentation becomes available online.
Georg Brandl8ec7f652007-08-15 14:28:01 +000064
Georg Brandlb19be572007-12-29 10:57:00 +000065.. ========================================================================
66.. Large, PEP-level features and changes should be described here.
67.. Should there be a new section here for 3k migration?
68.. Or perhaps a more general section describing module changes/deprecation?
69.. ========================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +000070
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000071Python 3.0
72================
73
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000074The development cycle for Python 2.6 also saw the release of the first
75alphas of Python 3.0, and the development of 3.0 has influenced
76a number of features in 2.6.
77
78Python 3.0 is a far-ranging redesign of Python that breaks
79compatibility with the 2.x series. This means that existing Python
80code will need a certain amount of conversion in order to run on
81Python 3.0. However, not all the changes in 3.0 necessarily break
82compatibility. In cases where new features won't cause existing code
83to break, they've been backported to 2.6 and are described in this
84document in the appropriate place. Some of the 3.0-derived features
85are:
86
87* A :meth:`__complex__` method for converting objects to a complex number.
88* Alternate syntax for catching exceptions: ``except TypeError as exc``.
89* The addition of :func:`functools.reduce` as a synonym for the built-in
90 :func:`reduce` function.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000091
92A new command-line switch, :option:`-3`, enables warnings
93about features that will be removed in Python 3.0. You can run code
94with this switch to see how much work will be necessary to port
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000095code to 3.0. The value of this switch is available
Georg Brandld5b635f2008-03-25 08:29:14 +000096to Python code as the boolean variable :data:`sys.py3kwarning`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000097and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000098
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +000099Python 3.0 adds several new built-in functions and change the
100semantics of some existing built-ins. Entirely new functions such as
101:func:`bin` have simply been added to Python 2.6, but existing
102built-ins haven't been changed; instead, the :mod:`future_builtins`
103module has versions with the new 3.0 semantics. Code written to be
104compatible with 3.0 can do ``from future_builtins import hex, map``
105as necessary.
106
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000107.. seealso::
108
109 The 3xxx series of PEPs, which describes the development process for
110 Python 3.0 and various features that have been accepted, rejected,
111 or are still under consideration.
112
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000113
114Development Changes
115==================================================
116
117While 2.6 was being developed, the Python development process
118underwent two significant changes: the developer group
119switched from SourceForge's issue tracker to a customized
120Roundup installation, and the documentation was converted from
121LaTeX to reStructured Text.
122
123
124New Issue Tracker: Roundup
125--------------------------------------------------
126
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000127For a long time, the Python developers have been growing increasingly
128annoyed by SourceForge's bug tracker. SourceForge's hosted solution
129doesn't permit much customization; for example, it wasn't possible to
130customize the life cycle of issues.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000131
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000132The infrastructure committee of the Python Software Foundation
133therefore posted a call for issue trackers, asking volunteers to set
134up different products and import some of the bugs and patches from
135SourceForge. Four different trackers were examined: Atlassian's `Jira
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000136<http://www.atlassian.com/software/jira/>`__,
137`Launchpad <http://www.launchpad.net>`__,
138`Roundup <http://roundup.sourceforge.net/>`__, and
139Trac <http://trac.edgewall.org/>`__.
140The committee eventually settled on Jira
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000141and Roundup as the two candidates. Jira is a commercial product that
142offers a no-cost hosted instance to free-software projects; Roundup
143is an open-source project that requires volunteers
144to administer it and a server to host it.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000145
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000146After posting a call for volunteers, a new Roundup installation was
147set up at http://bugs.python.org. One installation of Roundup can
148host multiple trackers, and this server now also hosts issue trackers
149for Jython and for the Python web site. It will surely find
150other uses in the future.
151
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000152Hosting is kindly provided by `Upfront Systems <http://www.upfrontsystems.co.za/>`__ of Stellenbosch, South Africa. Martin von Loewis put a
153lot of effort into importing existing bugs and patches from
154SourceForge; his scripts for this import operation are at
155http://svn.python.org/view/tracker/importer/.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000156
157.. seealso::
158
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000159 http://bugs.python.org: The Python bug tracker.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000160
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000161 http://bugs.jython.org: The Jython bug tracker.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000162
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000163 http://roundup.sourceforge.net/: Roundup downloads and documentation.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000164
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000165
166New Documentation Format: ReStructured Text
167--------------------------------------------------
168
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000169Since the Python project's inception around 1989, the documentation
170had been written using LaTeX. At that time, most documentation was
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000171printed out for later study, not viewed online. LaTeX was widely used
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000172because it provided attractive printed output while remaining
173straightforward to write, once the basic rules of the markup have been
174learned.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000175
176LaTeX is still used today for writing technical publications destined
177for printing, but the landscape for programming tools has shifted. We
178no longer print out reams of documentation; instead, we browse through
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000179it online and HTML has become the most important format to support.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000180Unfortunately, converting LaTeX to HTML is fairly complicated, and
181Fred L. Drake Jr., the Python documentation editor for many years,
182spent a lot of time wrestling the conversion process into shape.
183Occasionally people would suggest converting the documentation into
184SGML or, later, XML, but performing a good conversion is a major task
185and no one pursued the task to completion.
186
187During the 2.6 development cycle, Georg Brandl put a substantial
188effort into building a new toolchain called Sphinx
189for processing the documentation.
190The input format is reStructured Text,
191a markup commonly used in the Python community that supports
192custom extensions and directives. Sphinx concentrates
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000193on HTML output, producing attractively styled
194and modern HTML, but printed output is still supported through
195conversion to LaTeX as an output format.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000196
197.. seealso::
198
199 `Docutils <http://docutils.sf.net>`__: The fundamental
200 reStructured Text parser and toolset.
201
Georg Brandlb19be572007-12-29 10:57:00 +0000202 :ref:`documenting-index`: Describes how to write for
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000203 Python's documentation.
204
205
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000206PEP 343: The 'with' statement
207=============================
208
209The previous version, Python 2.5, added the ':keyword:`with`'
210statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000211import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000212be specially enabled; this means that :keyword:`with` is now always a
213keyword. The rest of this section is a copy of the corresponding
214section from "What's New in Python 2.5" document; if you read
215it back when Python 2.5 came out, you can skip the rest of this
216section.
217
218The ':keyword:`with`' statement clarifies code that previously would use
219``try...finally`` blocks to ensure that clean-up code is executed. In this
220section, I'll discuss the statement as it will commonly be used. In the next
221section, I'll examine the implementation details and show how to write objects
222for use with this statement.
223
224The ':keyword:`with`' statement is a new control-flow structure whose basic
225structure is::
226
227 with expression [as variable]:
228 with-block
229
230The expression is evaluated, and it should result in an object that supports the
231context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
232methods.
233
234The object's :meth:`__enter__` is called before *with-block* is executed and
235therefore can run set-up code. It also may return a value that is bound to the
236name *variable*, if given. (Note carefully that *variable* is *not* assigned
237the result of *expression*.)
238
239After execution of the *with-block* is finished, the object's :meth:`__exit__`
240method is called, even if the block raised an exception, and can therefore run
241clean-up code.
242
243Some standard Python objects now support the context management protocol and can
244be used with the ':keyword:`with`' statement. File objects are one example::
245
246 with open('/etc/passwd', 'r') as f:
247 for line in f:
248 print line
249 ... more processing code ...
250
251After this statement has executed, the file object in *f* will have been
252automatically closed, even if the :keyword:`for` loop raised an exception part-
253way through the block.
254
255.. note::
256
257 In this case, *f* is the same object created by :func:`open`, because
258 :meth:`file.__enter__` returns *self*.
259
260The :mod:`threading` module's locks and condition variables also support the
261':keyword:`with`' statement::
262
263 lock = threading.Lock()
264 with lock:
265 # Critical section of code
266 ...
267
268The lock is acquired before the block is executed and always released once the
269block is complete.
270
271The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
272to save and restore the current decimal context, which encapsulates the desired
273precision and rounding characteristics for computations::
274
275 from decimal import Decimal, Context, localcontext
276
277 # Displays with default precision of 28 digits
278 v = Decimal('578')
279 print v.sqrt()
280
281 with localcontext(Context(prec=16)):
282 # All code in this block uses a precision of 16 digits.
283 # The original context is restored on exiting the block.
284 print v.sqrt()
285
286
287.. _new-26-context-managers:
288
289Writing Context Managers
290------------------------
291
292Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
293people will only use ':keyword:`with`' in company with existing objects and
294don't need to know these details, so you can skip the rest of this section if
295you like. Authors of new objects will need to understand the details of the
296underlying implementation and should keep reading.
297
298A high-level explanation of the context management protocol is:
299
300* The expression is evaluated and should result in an object called a "context
301 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
302 methods.
303
304* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000305 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000306 discarded.
307
308* The code in *BLOCK* is executed.
309
310* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
311 is called with the exception details, the same values returned by
312 :func:`sys.exc_info`. The method's return value controls whether the exception
313 is re-raised: any false value re-raises the exception, and ``True`` will result
314 in suppressing it. You'll only rarely want to suppress the exception, because
315 if you do the author of the code containing the ':keyword:`with`' statement will
316 never realize anything went wrong.
317
318* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
319 called, but *type*, *value*, and *traceback* are all ``None``.
320
321Let's think through an example. I won't present detailed code but will only
322sketch the methods necessary for a database that supports transactions.
323
324(For people unfamiliar with database terminology: a set of changes to the
325database are grouped into a transaction. Transactions can be either committed,
326meaning that all the changes are written into the database, or rolled back,
327meaning that the changes are all discarded and the database is unchanged. See
328any database textbook for more information.)
329
330Let's assume there's an object representing a database connection. Our goal will
331be to let the user write code like this::
332
333 db_connection = DatabaseConnection()
334 with db_connection as cursor:
335 cursor.execute('insert into ...')
336 cursor.execute('delete from ...')
337 # ... more operations ...
338
339The transaction should be committed if the code in the block runs flawlessly or
340rolled back if there's an exception. Here's the basic interface for
341:class:`DatabaseConnection` that I'll assume::
342
343 class DatabaseConnection:
344 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000345 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000346 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000347 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000348 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000349 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000350 "Rolls back current transaction"
351
352The :meth:`__enter__` method is pretty easy, having only to start a new
353transaction. For this application the resulting cursor object would be a useful
354result, so the method will return it. The user can then add ``as cursor`` to
355their ':keyword:`with`' statement to bind the cursor to a variable name. ::
356
357 class DatabaseConnection:
358 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000359 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000360 # Code to start a new transaction
361 cursor = self.cursor()
362 return cursor
363
364The :meth:`__exit__` method is the most complicated because it's where most of
365the work has to be done. The method has to check if an exception occurred. If
366there was no exception, the transaction is committed. The transaction is rolled
367back if there was an exception.
368
369In the code below, execution will just fall off the end of the function,
370returning the default value of ``None``. ``None`` is false, so the exception
371will be re-raised automatically. If you wished, you could be more explicit and
372add a :keyword:`return` statement at the marked location. ::
373
374 class DatabaseConnection:
375 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000376 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000377 if tb is None:
378 # No exception, so commit
379 self.commit()
380 else:
381 # Exception occurred, so rollback.
382 self.rollback()
383 # return False
384
385
386.. _module-contextlib:
387
388The contextlib module
389---------------------
390
391The new :mod:`contextlib` module provides some functions and a decorator that
392are useful for writing objects for use with the ':keyword:`with`' statement.
393
394The decorator is called :func:`contextmanager`, and lets you write a single
395generator function instead of defining a new class. The generator should yield
396exactly one value. The code up to the :keyword:`yield` will be executed as the
397:meth:`__enter__` method, and the value yielded will be the method's return
398value that will get bound to the variable in the ':keyword:`with`' statement's
399:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
400executed in the :meth:`__exit__` method. Any exception raised in the block will
401be raised by the :keyword:`yield` statement.
402
403Our database example from the previous section could be written using this
404decorator as::
405
406 from contextlib import contextmanager
407
408 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000409 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000410 cursor = connection.cursor()
411 try:
412 yield cursor
413 except:
414 connection.rollback()
415 raise
416 else:
417 connection.commit()
418
419 db = DatabaseConnection()
420 with db_transaction(db) as cursor:
421 ...
422
423The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
424that combines a number of context managers so you don't need to write nested
425':keyword:`with`' statements. In this example, the single ':keyword:`with`'
426statement both starts a database transaction and acquires a thread lock::
427
428 lock = threading.Lock()
429 with nested (db_transaction(db), lock) as (cursor, locked):
430 ...
431
432Finally, the :func:`closing(object)` function returns *object* so that it can be
433bound to a variable, and calls ``object.close`` at the end of the block. ::
434
435 import urllib, sys
436 from contextlib import closing
437
438 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
439 for line in f:
440 sys.stdout.write(line)
441
442
443.. seealso::
444
445 :pep:`343` - The "with" statement
446 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
447 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
448 ':keyword:`with`' statement, which can be helpful in learning how the statement
449 works.
450
451 The documentation for the :mod:`contextlib` module.
452
Georg Brandlb19be572007-12-29 10:57:00 +0000453.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000454
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000455.. _pep-0366:
456
457PEP 366: Explicit Relative Imports From a Main Module
458============================================================
459
460Python's :option:`-m` switch allows running a module as a script.
461When you ran a module that was located inside a package, relative
462imports didn't work correctly.
463
464The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
465When present, relative imports will be relative to the value of this
466attribute instead of the :attr:`__name__` attribute. PEP 302-style
467importers can then set :attr:`__package__`. The :mod:`runpy` module
468that implements the :option:`-m` switch now does this, so relative imports
469can now be used in scripts running from inside a package.
470
Georg Brandlb19be572007-12-29 10:57:00 +0000471.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000472
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000473.. ::
474
475 .. _pep-0370:
476
477 PEP 370: XXX
478 =====================================================
479
480 When you run Python, the module search page ``sys.modules`` usually
481 includes a directory whose path ends in ``"site-packages"``. This
482 directory is intended to hold locally-installed packages available to
483 all users on a machine or using a particular site installation.
484
485 Python 2.6 introduces a convention for user-specific site directories.
486
487 .. seealso::
488
489 :pep:`370` - XXX
490
491 PEP written by XXX; implemented by Christian Heimes.
492
493
494.. ======================================================================
495
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000496.. _pep-3101:
497
498PEP 3101: Advanced String Formatting
499=====================================================
500
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000501In Python 3.0, the `%` operator is supplemented by a more powerful
502string formatting method, :meth:`format`. Support for the
503:meth:`format` method has been backported to Python 2.6.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000504
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000505In 2.6, both 8-bit and Unicode strings have a `.format()` method that
506treats the string as a template and takes the arguments to be formatted.
507The formatting template uses curly brackets (`{`, `}`) as special characters::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000508
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000509 # Substitute positional argument 0 into the string.
510 "User ID: {0}".format("root") -> "User ID: root"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000511
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000512 # Use the named keyword arguments
513 uid = 'root'
514
515 'User ID: {uid} Last seen: {last_login}'.format(uid='root',
516 last_login = '5 Mar 2008 07:20') ->
517 'User ID: root Last seen: 5 Mar 2008 07:20'
518
519Curly brackets can be escaped by doubling them::
520
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000521 format("Empty dict: {{}}") -> "Empty dict: {}"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000522
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000523Field names can be integers indicating positional arguments, such as
524``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
525supply compound field names that read attributes or access dictionary keys::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000526
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000527 import sys
528 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) ->
529 'Platform: darwin\n
530 Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) \n
531 [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
532
533 import mimetypes
534 'Content-type: {0[.mp4]}'.format(mimetypes.types_map) ->
535 'Content-type: video/mp4'
536
537Note that when using dictionary-style notation such as ``[.mp4]``, you
538don't need to put any quotation marks around the string; it will look
539up the value using ``.mp4`` as the key. Strings beginning with a
540number will be converted to an integer. You can't write more
541complicated expressions inside a format string.
542
543So far we've shown how to specify which field to substitute into the
544resulting string. The precise formatting used is also controllable by
Georg Brandl859043c2008-03-21 17:19:29 +0000545adding a colon followed by a format specifier. For example::
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000546
547 # Field 0: left justify, pad to 15 characters
548 # Field 1: right justify, pad to 6 characters
549 fmt = '{0:15} ${1:>6}'
550 fmt.format('Registration', 35) ->
551 'Registration $ 35'
552 fmt.format('Tutorial', 50) ->
553 'Tutorial $ 50'
554 fmt.format('Banquet', 125) ->
555 'Banquet $ 125'
556
Georg Brandl859043c2008-03-21 17:19:29 +0000557Format specifiers can reference other fields through nesting::
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000558
559 fmt = '{0:{1}}'
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000560 fmt.format('Invoice #1234', 15) ->
561 'Invoice #1234 '
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000562 width = 35
563 fmt.format('Invoice #1234', width) ->
564 'Invoice #1234 '
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000565
566The alignment of a field within the desired width can be specified:
567
568================ ============================================
569Character Effect
570================ ============================================
571< (default) Left-align
572> Right-align
573^ Center
574= (For numeric types only) Pad after the sign.
575================ ============================================
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000576
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000577Format specifiers can also include a presentation type, which
578controls how the value is formatted. For example, floating-point numbers
579can be formatted as a general number or in exponential notation:
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000580
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000581 >>> '{0:g}'.format(3.75)
582 '3.75'
583 >>> '{0:e}'.format(3.75)
584 '3.750000e+00'
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000585
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000586A variety of presentation types are available. Consult the 2.6
587documentation for a complete list (XXX add link, once it's in the 2.6
588docs), but here's a sample::
589
590 'b' - Binary. Outputs the number in base 2.
591 'c' - Character. Converts the integer to the corresponding
592 Unicode character before printing.
593 'd' - Decimal Integer. Outputs the number in base 10.
594 'o' - Octal format. Outputs the number in base 8.
595 'x' - Hex format. Outputs the number in base 16, using lower-
596 case letters for the digits above 9.
597 'e' - Exponent notation. Prints the number in scientific
598 notation using the letter 'e' to indicate the exponent.
599 'g' - General format. This prints the number as a fixed-point
600 number, unless the number is too large, in which case
601 it switches to 'e' exponent notation.
602 'n' - Number. This is the same as 'g', except that it uses the
603 current locale setting to insert the appropriate
604 number separator characters.
605 '%' - Percentage. Multiplies the number by 100 and displays
606 in fixed ('f') format, followed by a percent sign.
607
608Classes and types can define a __format__ method to control how they're
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000609formatted. It receives a single argument, the format specifier::
610
611 def __format__(self, format_spec):
612 if isinstance(format_spec, unicode):
613 return unicode(str(self))
614 else:
615 return str(self)
616
617There's also a format() built-in that will format a single value. It calls
618the type's :meth:`__format__` method with the provided specifier::
619
620 >>> format(75.6564, '.2f')
621 '75.66'
622
623.. seealso::
624
625 :pep:`3101` - Advanced String Formatting
626 PEP written by Talin.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000627
628.. ======================================================================
629
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000630.. _pep-3105:
631
632PEP 3105: ``print`` As a Function
633=====================================================
634
635The ``print`` statement becomes the :func:`print` function in Python 3.0.
636Making :func:`print` a function makes it easier to replace within a
637module by doing 'def print(...)' or importing a new
638function from somewhere else.
639
640Python 2.6 has a ``__future__`` import that removes ``print`` as language
641syntax, letting you use the functional form instead. For example::
642
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000643 from __future__ import print_function
644 print('# of entries', len(dictionary), file=sys.stderr)
645
646The signature of the new function is::
647
648 def print(*args, sep=' ', end='\n', file=None)
649
650The parameters are:
651
652 * **args**: positional arguments whose values will be printed out.
653 * **sep**: the separator, which will be printed between arguments.
654 * **end**: the ending text, which will be printed after all of the
655 arguments have been output.
656 * **file**: the file object to which the output will be sent.
657
658.. seealso::
659
Eric Smith33dd0942008-03-20 23:04:04 +0000660 :pep:`3105` - Make print a function
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000661 PEP written by Georg Brandl.
662
663.. ======================================================================
664
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000665.. _pep-3110:
666
667PEP 3110: Exception-Handling Changes
668=====================================================
669
670One error that Python programmers occasionally make
671is the following::
672
673 try:
674 ...
675 except TypeError, ValueError:
676 ...
677
678The author is probably trying to catch both
679:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
680actually does something different: it will catch
681:exc:`TypeError` and bind the resulting exception object
682to the local name ``"ValueError"``. The correct code
683would have specified a tuple::
684
685 try:
686 ...
687 except (TypeError, ValueError):
688 ...
689
690This error is possible because the use of the comma here is ambiguous:
691does it indicate two different nodes in the parse tree, or a single
692node that's a tuple.
693
694Python 3.0 changes the syntax to make this unambiguous by replacing
695the comma with the word "as". To catch an exception and store the
696exception object in the variable ``exc``, you must write::
697
698 try:
699 ...
700 except TypeError as exc:
701 ...
702
703Python 3.0 will only support the use of "as", and therefore interprets
704the first example as catching two different exceptions. Python 2.6
705supports both the comma and "as", so existing code will continue to
706work.
707
708.. seealso::
709
710 :pep:`3110` - Catching Exceptions in Python 3000
711 PEP written and implemented by Collin Winter.
712
Georg Brandlb19be572007-12-29 10:57:00 +0000713.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000714
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000715.. _pep-3112:
716
717PEP 3112: Byte Literals
718=====================================================
719
720Python 3.0 adopts Unicode as the language's fundamental string type, and
721denotes 8-bit literals differently, either as ``b'string'``
722or using a :class:`bytes` constructor. For future compatibility,
723Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
724and it also supports the ``b''`` notation.
725
726.. seealso::
727
728 :pep:`3112` - Bytes literals in Python 3000
729 PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
730
731.. ======================================================================
732
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000733.. _pep-3116:
734
735PEP 3116: New I/O Library
736=====================================================
737
738XXX write this.
739
740.. seealso::
741
742 :pep:`3116` - New I/O
743 PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
744 XXX code written by who?
745
746.. ======================================================================
747
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +0000748.. _pep-3118:
749
750PEP 3118: Revised Buffer Protocol
751=====================================================
752
753The buffer protocol is a C-level API that lets Python extensions
754XXX
755
756.. seealso::
757
758 :pep:`3118` - Revising the buffer protocol
759 PEP written by Travis Oliphant and Carl Banks.
760
761.. ======================================================================
762
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000763.. _pep-3119:
764
765PEP 3119: Abstract Base Classes
766=====================================================
767
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000768XXX write this -- this section is currently just brief notes.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000769
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000770How to identify a file object?
771
772ABCs are a collection of classes describing various interfaces.
773Classes can derive from an ABC to indicate they support that ABC's
774interface. Concrete classes should obey the semantics specified by
775an ABC, but Python can't check this; it's up to the implementor.
776
777A metaclass lets you declare that an existing class or type
778derives from a particular ABC. You can even
779
780class AppendableSequence:
781 __metaclass__ = ABCMeta
782
783AppendableSequence.register(list)
784assert issubclass(list, AppendableSequence)
785assert isinstance([], AppendableSequence)
786
787@abstractmethod decorator -- you can't instantiate classes w/
788an abstract method.
789
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000790::
791
792 @abstractproperty decorator
793 @abstractproperty
794 def readonly(self):
795 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000796
797
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000798.. seealso::
799
800 :pep:`3119` - Introducing Abstract Base Classes
801 PEP written by Guido van Rossum and Talin.
802 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000803 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000804
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000805.. ======================================================================
806
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000807.. _pep-3127:
808
809PEP 3127: Integer Literal Support and Syntax
810=====================================================
811
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000812XXX write this -- this section is currently just brief notes.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000813
814Python 3.0 changes the syntax for octal integer literals, and
815adds supports for binary integers: 0o instad of 0,
816and 0b for binary. Python 2.6 doesn't support this, but a bin()
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000817builtin was added.
818
819XXX changes to the hex/oct builtins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000820
821
822New bin() built-in returns the binary form of a number.
823
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000824.. seealso::
825
826 :pep:`3127` - Integer Literal Support and Syntax
827 PEP written by Patrick Maupin.
828
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000829.. ======================================================================
830
831.. _pep-3129:
832
833PEP 3129: Class Decorators
834=====================================================
835
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000836Decorators have been extended from functions to classes. It's now legal to
837write::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000838
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000839 @foo
840 @bar
841 class A:
842 pass
843
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000844This is equivalent to::
845
846 class A:
847 pass
848
849 A = foo(bar(A))
850
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000851XXX need to find a good motivating example.
852
853.. seealso::
854
855 :pep:`3129` - Class Decorators
856 PEP written by Collin Winter.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000857
858.. ======================================================================
859
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000860.. _pep-3141:
861
862PEP 3141: A Type Hierarchy for Numbers
863=====================================================
864
865In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000866inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000867This change was backported to 2.6 as the :mod:`numbers` module.
868
869The most general ABC is :class:`Number`. It defines no operations at
870all, and only exists to allow checking if an object is a number by
871doing ``isinstance(obj, Number)``.
872
873Numbers are further divided into :class:`Exact` and :class:`Inexact`.
874Exact numbers can represent values precisely and operations never
875round off the results or introduce tiny errors that may break the
Georg Brandl907a7202008-02-22 12:31:45 +0000876commutativity and associativity properties; inexact numbers may
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000877perform such rounding or introduce small errors. Integers, long
878integers, and rational numbers are exact, while floating-point
879and complex numbers are inexact.
880
881:class:`Complex` is a subclass of :class:`Number`. Complex numbers
882can undergo the basic operations of addition, subtraction,
883multiplication, division, and exponentiation, and you can retrieve the
884real and imaginary parts and obtain a number's conjugate. Python's built-in
885complex type is an implementation of :class:`Complex`.
886
887:class:`Real` further derives from :class:`Complex`, and adds
888operations that only work on real numbers: :func:`floor`, :func:`trunc`,
889rounding, taking the remainder mod N, floor division,
890and comparisons.
891
892:class:`Rational` numbers derive from :class:`Real`, have
893:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +0000894converted to floats. Python 2.6 adds a simple rational-number class,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000895:class:`Fraction`, in the :mod:`fractions` module. (It's called
896:class:`Fraction` instead of :class:`Rational` to avoid
897a name clash with :class:`numbers.Rational`.)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000898
899:class:`Integral` numbers derive from :class:`Rational`, and
900can be shifted left and right with ``<<`` and ``>>``,
901combined using bitwise operations such as ``&`` and ``|``,
902and can be used as array indexes and slice boundaries.
903
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000904In Python 3.0, the PEP slightly redefines the existing built-ins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000905:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
906one, :func:`math.trunc`, that's been backported to Python 2.6.
907:func:`math.trunc` rounds toward zero, returning the closest
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000908:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000909
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000910.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000911
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000912 :pep:`3141` - A Type Hierarchy for Numbers
913 PEP written by Jeffrey Yasskin.
914
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000915 `Scheme's numerical tower <http://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000916
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +0000917 `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000918
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000919
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000920The :mod:`fractions` Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000921--------------------------------------------------
922
923To fill out the hierarchy of numeric types, a rational-number class
Mark Dickinsond058cd22008-02-10 21:29:51 +0000924has been added as the :mod:`fractions` module. Rational numbers are
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000925represented as a fraction, and can exactly represent
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000926numbers such as two-thirds that floating-point numbers can only
927approximate.
928
Mark Dickinsond058cd22008-02-10 21:29:51 +0000929The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000930that will be the numerator and denominator of the resulting fraction. ::
931
Mark Dickinsond058cd22008-02-10 21:29:51 +0000932 >>> from fractions import Fraction
933 >>> a = Fraction(2, 3)
934 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000935 >>> float(a), float(b)
936 (0.66666666666666663, 0.40000000000000002)
937 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000938 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000939 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000940 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000941
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000942To help in converting floating-point numbers to rationals,
943the float type now has a :meth:`as_integer_ratio()` method that returns
944the numerator and denominator for a fraction that evaluates to the same
945floating-point value::
946
947 >>> (2.5) .as_integer_ratio()
948 (5, 2)
949 >>> (3.1415) .as_integer_ratio()
950 (7074029114692207L, 2251799813685248L)
951 >>> (1./3) .as_integer_ratio()
952 (6004799503160661L, 18014398509481984L)
953
954Note that values that can only be approximated by floating-point
955numbers, such as 1./3, are not simplified to the number being
956approximated; the fraction attempts to match the floating-point value
957**exactly**.
958
Mark Dickinsond058cd22008-02-10 21:29:51 +0000959The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000960Mullender that was in Python's :file:`Demo/classes/` directory for a
961long time. This implementation was significantly updated by Jeffrey
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000962Yasskin.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000963
Georg Brandl8ec7f652007-08-15 14:28:01 +0000964Other Language Changes
965======================
966
967Here are all of the changes that Python 2.6 makes to the core Python language.
968
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000969* When calling a function using the ``**`` syntax to provide keyword
970 arguments, you are no longer required to use a Python dictionary;
971 any mapping will now work::
972
973 >>> def f(**kw):
974 ... print sorted(kw)
975 ...
976 >>> ud=UserDict.UserDict()
977 >>> ud['a'] = 1
978 >>> ud['b'] = 'string'
979 >>> f(**ud)
980 ['a', 'b']
981
Georg Brandlb19be572007-12-29 10:57:00 +0000982 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000983
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000984* The built-in types now have improved support for extended slicing syntax,
985 where various combinations of ``(start, stop, step)`` are supplied.
986 Previously, the support was partial and certain corner cases wouldn't work.
987 (Implemented by Thomas Wouters.)
988
Georg Brandlb19be572007-12-29 10:57:00 +0000989 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000990
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000991* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000992 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000993 adding or modifying a getter, setter or deleter function to an
994 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000995
996 class C(object):
997 @property
998 def x(self):
999 return self._x
1000
1001 @x.setter
1002 def x(self, value):
1003 self._x = value
1004
1005 @x.deleter
1006 def x(self):
1007 del self._x
1008
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001009 class D(C):
1010 @C.x.getter
1011 def x(self):
1012 return self._x * 2
1013
1014 @x.setter
1015 def x(self, value):
1016 self._x = value / 2
1017
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001018
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001019* C functions and methods that use
1020 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
1021 have a :meth:`__complex__` method. In particular, the functions in the
1022 :mod:`cmath` module will now accept objects with this method.
1023 This is a backport of a Python 3.0 change.
1024 (Contributed by Mark Dickinson.)
1025
Georg Brandlb19be572007-12-29 10:57:00 +00001026 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001027
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001028 A numerical nicety: when creating a complex number from two floats
1029 on systems that support signed zeros (-0 and +0), the
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001030 :func:`complex` constructor will now preserve the sign
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001031 of the zero.
1032
Georg Brandlb19be572007-12-29 10:57:00 +00001033 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001034
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001035* More floating-point features were also added. The :func:`float` function
1036 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001037 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001038 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +00001039 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001040
Georg Brandl225163d2008-03-05 07:10:35 +00001041 .. Patch 1635
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001042
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001043 Other functions in the :mod:`math` module, :func:`isinf` and
1044 :func:`isnan`, return true if their floating-point argument is
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001045 infinite or Not A Number.
1046
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001047 .. Patch 1640
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001048
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001049 The ``math.copysign(x, y)`` function
1050 copies the sign bit of an IEEE 754 number, returning the absolute
1051 value of *x* combined with the sign bit of *y*. For example,
1052 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
1053 Heimes.)
1054
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001055* Changes to the :class:`Exception` interface
1056 as dictated by :pep:`352` continue to be made. For 2.6,
1057 the :attr:`message` attribute is being deprecated in favor of the
1058 :attr:`args` attribute.
1059
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001060* The :exc:`GeneratorExit` exception now subclasses
1061 :exc:`BaseException` instead of :exc:`Exception`. This means
1062 that an exception handler that does ``except Exception:``
1063 will not inadvertently catch :exc:`GeneratorExit`.
1064 (Contributed by Chad Austin.)
1065
Georg Brandlb19be572007-12-29 10:57:00 +00001066 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001067
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001068* Generator objects now have a :attr:`gi_code` attribute that refers to
1069 the original code object backing the generator.
1070 (Contributed by Collin Winter.)
1071
1072 .. Patch #1473257
1073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001074* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001075 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001076
Georg Brandlb19be572007-12-29 10:57:00 +00001077 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001078
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001079* The :func:`complex` constructor now accepts strings containing
1080 parenthesized complex numbers, letting ``complex(repr(cmplx))``
1081 will now round-trip values. For example, ``complex('(3+4j)')``
1082 now returns the value (3+4j).
1083
Georg Brandlb19be572007-12-29 10:57:00 +00001084 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001085
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001086* The string :meth:`translate` method now accepts ``None`` as the
1087 translation table parameter, which is treated as the identity
1088 transformation. This makes it easier to carry out operations
1089 that only delete characters. (Contributed by Bengt Richter.)
1090
Georg Brandlb19be572007-12-29 10:57:00 +00001091 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001092
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001093* The built-in :func:`dir` function now checks for a :meth:`__dir__`
1094 method on the objects it receives. This method must return a list
1095 of strings containing the names of valid attributes for the object,
1096 and lets the object control the value that :func:`dir` produces.
1097 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +00001098 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001099
Georg Brandlb19be572007-12-29 10:57:00 +00001100 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001101
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001102* Instance method objects have new attributes for the object and function
1103 comprising the method; the new synonym for :attr:`im_self` is
1104 :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`.
1105 The old names are still supported in Python 2.6; they're gone in 3.0.
1106
Georg Brandl8ec7f652007-08-15 14:28:01 +00001107* An obscure change: when you use the the :func:`locals` function inside a
1108 :keyword:`class` statement, the resulting dictionary no longer returns free
1109 variables. (Free variables, in this case, are variables referred to in the
1110 :keyword:`class` statement that aren't attributes of the class.)
1111
Georg Brandlb19be572007-12-29 10:57:00 +00001112.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001113
1114
1115Optimizations
1116-------------
1117
Georg Brandlaf30b282008-01-15 06:55:56 +00001118* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001119 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +00001120 for a particular class; once cached, the interpreter doesn't need to
1121 traverse base classes to figure out the right method to call.
1122 The cache is cleared if a base class or the class itself is modified,
1123 so the cache should remain correct even in the face of Python's dynamic
1124 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001125 (Original optimization implemented by Armin Rigo, updated for
1126 Python 2.6 by Kevin Jacobs.)
1127
Georg Brandl225163d2008-03-05 07:10:35 +00001128 .. Patch 1700288
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001129
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001130* All of the functions in the :mod:`struct` module have been rewritten in
1131 C, thanks to work at the Need For Speed sprint.
1132 (Contributed by Raymond Hettinger.)
1133
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134* Internally, a bit is now set in type objects to indicate some of the standard
1135 built-in types. This speeds up checking if an object is a subclass of one of
1136 these types. (Contributed by Neal Norwitz.)
1137
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001138* Unicode strings now uses faster code for detecting
1139 whitespace and line breaks; this speeds up the :meth:`split` method
1140 by about 25% and :meth:`splitlines` by 35%.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001141 (Contributed by Antoine Pitrou.) Memory usage is reduced
1142 by using pymalloc for the Unicode string's data.
1143
1144* The ``with`` statement now stores the :meth:`__exit__` method on the stack,
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001145 producing a small speedup. (Implemented by Jeffrey Yasskin.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001146
1147* To reduce memory usage, the garbage collector will now clear internal
1148 free lists when garbage-collecting the highest generation of objects.
1149 This may return memory to the OS sooner.
1150
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
1152benchmark around XX% faster than Python 2.5.
1153
Georg Brandlb19be572007-12-29 10:57:00 +00001154.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001155
1156
1157New, Improved, and Deprecated Modules
1158=====================================
1159
1160As usual, Python's standard library received a number of enhancements and bug
1161fixes. Here's a partial list of the most notable changes, sorted alphabetically
1162by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
1163complete list of changes, or look through the CVS logs for all the details.
1164
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001165* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
1166 available, instead of restricting itself to protocol 1.
1167 (Contributed by W. Barnes.)
1168
Georg Brandlb19be572007-12-29 10:57:00 +00001169 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001170
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001171* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001172 fieldnames)` is a factory function that creates subclasses of the standard tuple
1173 whose fields are accessible by name as well as index. For example::
1174
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001175 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001176 ... 'id name type size')
1177 # Names are separated by spaces or commas.
1178 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +00001179 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001180 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001181
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001182 >>> var = var_type(1, 'frequency', 'int', 4)
1183 >>> print var[0], var.id # Equivalent
1184 1 1
1185 >>> print var[2], var.type # Equivalent
1186 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +00001187 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001188 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +00001189 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001190 >>> v2
1191 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001192
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001193 Where the new :class:`namedtuple` type proved suitable, the standard
1194 library has been modified to return them. For example,
1195 the :meth:`Decimal.as_tuple` method now returns a named tuple with
1196 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1197
Georg Brandl8ec7f652007-08-15 14:28:01 +00001198 (Contributed by Raymond Hettinger.)
1199
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001200* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +00001201 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001202 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +00001203 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001204 old items to be discarded.
1205
1206 ::
1207
1208 >>> from collections import deque
1209 >>> dq=deque(maxlen=3)
1210 >>> dq
1211 deque([], maxlen=3)
1212 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
1213 >>> dq
1214 deque([1, 2, 3], maxlen=3)
1215 >>> dq.append(4)
1216 >>> dq
1217 deque([2, 3, 4], maxlen=3)
1218
1219 (Contributed by Raymond Hettinger.)
1220
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001221* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
1222 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
1223
Georg Brandlb19be572007-12-29 10:57:00 +00001224 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001225
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001226 The :mod:`ctypes` string, buffer and array types also have improved
1227 support for extended slicing syntax,
1228 where various combinations of ``(start, stop, step)`` are supplied.
1229 (Implemented by Thomas Wouters.)
1230
Georg Brandlb19be572007-12-29 10:57:00 +00001231 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001232
Georg Brandl8ec7f652007-08-15 14:28:01 +00001233* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001234 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001235 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001236 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001237
1238 # Boldface text starting at y=0,x=21
1239 # and affecting the rest of the line.
1240 stdscr.chgat(0,21, curses.A_BOLD)
1241
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001242 The :class:`Textbox` class in the :mod:`curses.textpad` module
1243 now supports editing in insert mode as well as overwrite mode.
1244 Insert mode is enabled by supplying a true value for the *insert_mode*
1245 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001246
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001247* The :mod:`datetime` module's :meth:`strftime` methods now support a
1248 ``%f`` format code that expands to the number of microseconds in the
1249 object, zero-padded on
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001250 the left to six places. (Contributed by Skip Montanaro.)
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001251
1252 .. Patch 1158
1253
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001254* The :mod:`decimal` module was updated to version 1.66 of
1255 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
1256 include some methods for some basic mathematical functions such as
1257 :meth:`exp` and :meth:`log10`::
1258
1259 >>> Decimal(1).exp()
1260 Decimal("2.718281828459045235360287471")
1261 >>> Decimal("2.7182818").ln()
1262 Decimal("0.9999999895305022877376682436")
1263 >>> Decimal(1000).log10()
1264 Decimal("3")
1265
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001266 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
1267 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1268
1269 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
1270 support added by Raymond Hettinger.)
1271
1272* The :mod:`difflib` module's :class:`SequenceMatcher` class
1273 now returns named tuples representing matches.
1274 In addition to behaving like tuples, the returned values
1275 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
1276 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001277
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001278* An optional ``timeout`` parameter was added to the
1279 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
1280 method, specifying a timeout measured in seconds. (Added by Facundo
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001281 Batista.) Also, the :class:`FTP` class's
1282 :meth:`storbinary` and :meth:`storlines`
1283 now take an optional *callback* parameter that will be called with
1284 each block of data after the data has been sent.
1285 (Contributed by Phil Schwartz.)
1286
1287 .. Patch 1221598
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001288
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001289* The :func:`reduce` built-in function is also available in the
1290 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
1291 only available from :mod:`functools`; currently there are no plans
1292 to drop the built-in in the 2.x series. (Patched by
1293 Christian Heimes.)
1294
Georg Brandlb19be572007-12-29 10:57:00 +00001295 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001296
Georg Brandl8ec7f652007-08-15 14:28:01 +00001297* The :func:`glob.glob` function can now return Unicode filenames if
1298 a Unicode path was used and Unicode filenames are matched within the directory.
1299
Georg Brandlb19be572007-12-29 10:57:00 +00001300 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +00001301
1302* The :mod:`gopherlib` module has been removed.
1303
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001304* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
1305 takes any number of iterables that return data *in sorted
1306 order*, and returns a new iterator that returns the contents of all
1307 the iterators, also in sorted order. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001308
1309 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
1310 [1, 2, 3, 5, 8, 9, 16]
1311
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001312 Another new function, ``heappushpop(heap, item)``,
1313 pushes *item* onto *heap*, then pops off and returns the smallest item.
1314 This is more efficient than making a call to :func:`heappush` and then
1315 :func:`heappop`.
1316
Georg Brandl8ec7f652007-08-15 14:28:01 +00001317 (Contributed by Raymond Hettinger.)
1318
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001319* An optional ``timeout`` parameter was added to the
1320 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
1321 class constructors, specifying a timeout measured in seconds.
1322 (Added by Facundo Batista.)
1323
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001324* Most of the :mod:`inspect` module's functions, such as
1325 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
1326 In addition to behaving like tuples, the elements of the return value
1327 can also be accessed as attributes.
1328 (Contributed by Raymond Hettinger.)
1329
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001330 Some new functions in the module include
1331 :func:`isgenerator`, :func:`isgeneratorfunction`,
1332 and :func:`isabstract`.
1333
1334* The :mod:`itertools` module gained several new functions.
1335
1336 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
1337 each of the elements; if some of the iterables are shorter than
1338 others, the missing values are set to *fillvalue*. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001339
1340 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
1341 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
1342
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001343 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
1344 of the supplied iterables, a set of tuples containing
1345 every possible combination of the elements returned from each iterable. ::
1346
1347 itertools.product([1,2,3], [4,5,6]) ->
1348 [(1, 4), (1, 5), (1, 6),
1349 (2, 4), (2, 5), (2, 6),
1350 (3, 4), (3, 5), (3, 6)]
1351
1352 The optional *repeat* keyword argument is used for taking the
1353 product of an iterable or a set of iterables with themselves,
1354 repeated *N* times. With a single iterable argument, *N*-tuples
1355 are returned::
1356
1357 itertools.product([1,2], repeat=3)) ->
1358 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
1359 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
1360
1361 With two iterables, *2N*-tuples are returned. ::
1362
1363 itertools(product([1,2], [3,4], repeat=2) ->
1364 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
1365 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
1366 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
1367 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
1368
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001369 ``combinations(iterable, r)`` returns sub-sequences of length *r* from
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001370 the elements of *iterable*. ::
1371
1372 itertools.combinations('123', 2) ->
1373 [('1', '2'), ('1', '3'), ('2', '3')]
1374
1375 itertools.combinations('123', 3) ->
1376 [('1', '2', '3')]
1377
1378 itertools.combinations('1234', 3) ->
1379 [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
1380 ('2', '3', '4')]
1381
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001382 ``permutations(iter[, r])`` returns all the permutations of length *r* of
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001383 the iterable's elements. If *r* is not specified, it will default to the
1384 number of elements produced by the iterable.
1385
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001386 itertools.permutations([1,2,3,4], 2) ->
1387 [(1, 2), (1, 3), (1, 4),
1388 (2, 1), (2, 3), (2, 4),
1389 (3, 1), (3, 2), (3, 4),
1390 (4, 1), (4, 2), (4, 3)]
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001391
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001392 ``itertools.chain(*iterables)` is an existing function in
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001393 :mod:`itertools` that gained a new constructor in Python 2.6.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001394 ``itertools.chain.from_iterable(iterable)`` takes a single
1395 iterable that should return other iterables. :func:`chain` will
1396 then return all the elements of the first iterable, then
1397 all the elements of the second, and so on. ::
1398
1399 chain.from_iterable([[1,2,3], [4,5,6]]) ->
1400 [1, 2, 3, 4, 5, 6]
1401
1402 (All contributed by Raymond Hettinger.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001403
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001404* The :mod:`logging` module's :class:`FileHandler` class
1405 and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
1406 and :class:`TimedRotatingFileHandler` now
1407 have an optional *delay* parameter to its constructor. If *delay*
1408 is true, opening of the log file is deferred until the first
1409 :meth:`emit` call is made. (Contributed by Vinay Sajip.)
1410
Georg Brandl8ec7f652007-08-15 14:28:01 +00001411* The :mod:`macfs` module has been removed. This in turn required the
1412 :func:`macostools.touched` function to be removed because it depended on the
1413 :mod:`macfs` module.
1414
Georg Brandlb19be572007-12-29 10:57:00 +00001415 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +00001416
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001417* :class:`mmap` objects now have a :meth:`rfind` method that finds
1418 a substring, beginning at the end of the string and searching
1419 backwards. The :meth:`find` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001420 also gained an *end* parameter containing the index at which to stop
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001421 the forward search.
1422 (Contributed by John Lenton.)
1423
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001424* (3.0-warning mode) The :mod:`new` module has been removed from
1425 Python 3.0. Importing it therefore triggers a warning message.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001426
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001427* The :mod:`operator` module gained a
1428 :func:`methodcaller` function that takes a name and an optional
1429 set of arguments, returning a callable that will call
1430 the named function on any arguments passed to it. For example::
1431
1432 >>> # Equivalent to lambda s: s.replace('old', 'new')
1433 >>> replacer = operator.methodcaller('replace', 'old', 'new')
1434 >>> replacer('old wine in old bottles')
1435 'new wine in new bottles'
1436
Georg Brandl27504da2008-03-04 07:25:54 +00001437 (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001438
1439 The :func:`attrgetter` function now accepts dotted names and performs
1440 the corresponding attribute lookups::
1441
1442 >>> inst_name = operator.attrgetter('__class__.__name__')
1443 >>> inst_name('')
1444 'str'
1445 >>> inst_name(help)
1446 '_Helper'
1447
Georg Brandl27504da2008-03-04 07:25:54 +00001448 (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001449
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001450* New functions in the :mod:`os` module include
1451 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
1452 and ``lchmod(path, mode)``, on operating systems that support these
1453 functions. :func:`fchmod` and :func:`fchown` let you change the mode
1454 and ownership of an opened file, and :func:`lchmod` changes the mode
1455 of a symlink.
1456
1457 (Contributed by Georg Brandl and Christian Heimes.)
1458
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001459* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001460 set to True, it will follow symlinks pointing to directories and
1461 visit the directory's contents. For backward compatibility, the
1462 parameter's default value is false. Note that the function can fall
1463 into an infinite recursion if there's a symlink that points to a
1464 parent directory.
1465
Georg Brandlb19be572007-12-29 10:57:00 +00001466 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001467
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001468* The ``os.environ`` object's :meth:`clear` method will now unset the
1469 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001470 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001471
Georg Brandlb19be572007-12-29 10:57:00 +00001472 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001473
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001474* In the :mod:`os.path` module, the :func:`splitext` function
1475 has been changed to not split on leading period characters.
1476 This produces better results when operating on Unix's dot-files.
1477 For example, ``os.path.splitext('.ipython')``
1478 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
1479
Georg Brandlb19be572007-12-29 10:57:00 +00001480 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001481
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001482 A new function, :func:`relpath(path, start)` returns a relative path
1483 from the ``start`` path, if it's supplied, or from the current
1484 working directory to the destination ``path``. (Contributed by
1485 Richard Barran.)
1486
Georg Brandlb19be572007-12-29 10:57:00 +00001487 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001488
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001489 On Windows, :func:`os.path.expandvars` will now expand environment variables
1490 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001491 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001492
Georg Brandlb19be572007-12-29 10:57:00 +00001493 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001494
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001495* The Python debugger provided by the :mod:`pdb` module
1496 gained a new command: "run" restarts the Python program being debugged,
1497 and can optionally take new command-line arguments for the program.
1498 (Contributed by Rocky Bernstein.)
1499
Georg Brandlb19be572007-12-29 10:57:00 +00001500 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001501
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001502* The :mod:`pickletools` module now has an :func:`optimize` function
1503 that takes a string containing a pickle and removes some unused
1504 opcodes, returning a shorter pickle that contains the same data structure.
1505 (Contributed by Raymond Hettinger.)
1506
Georg Brandl8ec7f652007-08-15 14:28:01 +00001507* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
1508 are wrappers for the corresponding system calls (where they're available).
1509 Constants for the flag values are defined in the :mod:`stat` module; some
1510 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
1511 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
1512 file. (Contributed by M. Levinson.)
1513
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001514 ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors
1515 from *low* to *high*, ignoring any errors and not including *high* itself.
1516 This function is now used by the :mod:`subprocess` module to make starting
1517 processes faster. (Contributed by Georg Brandl.)
1518
1519 .. Patch #1663329
1520
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00001521* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
1522 their :attr:`buffer_size` attribute to change the size of the buffer
1523 used to hold character data.
1524 (Contributed by Achim Gaedke.)
1525
1526 .. Patch 1137
1527
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001528* The :mod:`Queue` module now provides queue classes that retrieve entries
1529 in different orders. The :class:`PriorityQueue` class stores
1530 queued items in a heap and retrieves them in priority order,
1531 and :class:`LifoQueue` retrieves the most recently added entries first,
1532 meaning that it behaves like a stack.
1533 (Contributed by Raymond Hettinger.)
1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001535* The :mod:`random` module's :class:`Random` objects can
1536 now be pickled on a 32-bit system and unpickled on a 64-bit
1537 system, and vice versa. Unfortunately, this change also means
1538 that Python 2.6's :class:`Random` objects can't be unpickled correctly
1539 on earlier versions of Python.
1540 (Contributed by Shawn Ligocki.)
1541
Georg Brandlb19be572007-12-29 10:57:00 +00001542 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001543
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001544 The new ``triangular(low, high, mode)`` function returns random
1545 numbers following a triangular distribution. The returned values
1546 are between *low* and *high*, not including *high* itself, and
1547 with *mode* as the mode, the most frequently occurring value
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001548 in the distribution. (Contributed by Wladmir van der Laan and
1549 Raymond Hettinger.)
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001550
1551 .. Patch 1681432
1552
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001553* Long regular expression searches carried out by the :mod:`re`
1554 module will now check for signals being delivered, so especially
1555 long searches can now be interrupted.
1556 (Contributed by Josh Hoyt and Ralf Schmitt.)
1557
Georg Brandl225163d2008-03-05 07:10:35 +00001558 .. Patch 846388
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001559
Georg Brandl8ec7f652007-08-15 14:28:01 +00001560* The :mod:`rgbimg` module has been removed.
1561
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001562* The :mod:`sched` module's :class:`scheduler` instances now
1563 have a read-only :attr:`queue` attribute that returns the
1564 contents of the scheduler's queue, represented as a list of
Georg Brandl225163d2008-03-05 07:10:35 +00001565 named tuples with the fields ``(time, priority, action, argument)``.
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001566 (Contributed by Raymond Hettinger.)
Georg Brandl225163d2008-03-05 07:10:35 +00001567
1568 .. Patch 1861
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001569
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001570* The :mod:`select` module now has wrapper functions
1571 for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls.
1572 Also, a :meth:`modify` method was added to the existing :class:`poll`
1573 objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
1574 or file object and an event mask,
1575
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001576 (Contributed by Christian Heimes.)
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00001577
1578 .. Patch 1657
1579
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001580* The :mod:`sets` module has been deprecated; it's better to
1581 use the built-in :class:`set` and :class:`frozenset` types.
1582
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001583* Integrating signal handling with GUI handling event loops
1584 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001585 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001586 The :mod:`signal` module can now make this more efficient.
1587 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
1588 to be used; when a signal is received, a byte is written to that
1589 file descriptor. There's also a C-level function,
1590 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
1591
1592 Event loops will use this by opening a pipe to create two descriptors,
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001593 one for reading and one for writing. The writable descriptor
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001594 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
1595 will be added to the list of descriptors monitored by the event loop via
1596 :cfunc:`select` or :cfunc:`poll`.
1597 On receiving a signal, a byte will be written and the main event loop
1598 will be woken up, without the need to poll.
1599
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001600 (Contributed by Adam Olsen.)
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001601
Georg Brandl225163d2008-03-05 07:10:35 +00001602 .. Patch 1583
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001603
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001604 The :func:`siginterrupt` function is now available from Python code,
1605 and allows changing whether signals can interrupt system calls or not.
1606 (Contributed by Ralf Schmitt.)
1607
Andrew M. Kuchlingb2ff8a72008-04-05 03:38:39 +00001608 The :func:`setitimer` and :func:`getitimer` functions have also been
1609 added on systems that support these system calls. :func:`setitimer`
1610 allows setting interval timers that will cause a signal to be
1611 delivered to the process after a specified time, measured in
1612 wall-clock time, consumed process time, or combined process+system
1613 time. (Contributed by Guilherme Polo.)
1614
1615 .. Patch 2240
1616
1617
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001618* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
1619 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001620 interface identical to the existing :class:`SMTP` class. Both
1621 class constructors also have an optional ``timeout`` parameter
1622 that specifies a timeout for the initial connection attempt, measured in
1623 seconds.
1624
1625 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001626 the module. LMTP is used in place of SMTP when transferring e-mail
1627 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001628
1629 (SMTP over SSL contributed by Monty Taylor; timeout parameter
1630 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001631 Hedstrom.)
1632
Georg Brandlb19be572007-12-29 10:57:00 +00001633 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +00001634
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001635* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
1636 and forgets any knowledge obtained from the server not obtained from
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001637 the TLS negotiation itself. (Patch contributed by Bill Fenner.)
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001638
1639 .. Issue 829951
1640
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001641* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1642 a high-performance non-IP-based protocol designed for use in clustered
1643 environments. TIPC addresses are 4- or 5-tuples.
1644 (Contributed by Alberto Bertogli.)
1645
1646 .. Patch #1646
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00001647
1648* The base classes in the :mod:`SocketServer` module now support
1649 calling a :meth:`handle_timeout` method after a span of inactivity
1650 specified by the server's :attr:`timeout` attribute. (Contributed
1651 by Michael Pomraning.)
1652
1653 .. Patch #742598
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001654
1655* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
1656 using the format character ``'?'``.
1657 (Contributed by David Remahl.)
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001658
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001659* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001660 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001661 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001662 derived from the :file:`float.h` file. Attributes of this object
1663 include
1664 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001665 (smallest difference between 1.0 and the next largest value
1666 representable), and several others. (Contributed by Christian Heimes.)
1667
Georg Brandlb19be572007-12-29 10:57:00 +00001668 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001669
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00001670 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
1671 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1672 If this variable is true, the compiled files are not written. The
1673 variable is initially set on start-up by supplying the :option:`-B`
1674 switch to the Python interpreter, or by setting the
1675 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
1676 running the interpreter. Python code can subsequently
1677 change the value of this variable to control whether bytecode files
1678 are written or not.
1679 (Contributed by Neal Norwitz and Georg Brandl.)
1680
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001681 Information about the command-line arguments supplied to the Python
1682 interpreter are available as attributes of a ``sys.flags`` named
1683 tuple. For example, the :attr:`verbose` attribute is true if Python
1684 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1685 These attributes are all read-only.
1686 (Contributed by Christian Heimes.)
1687
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001688 It's now possible to determine the current profiler and tracer functions
1689 by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
1690 (Contributed by Georg Brandl.)
1691
1692 .. Patch #1648
1693
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001694* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1695 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1696 format that was already supported. The default format
1697 is GNU tar; specify the ``format`` parameter to open a file
1698 using a different format::
1699
1700 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1701
1702 The new ``errors`` parameter lets you specify an error handling
1703 scheme for character conversions: the three standard ways Python can
1704 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1705 special value ``'utf-8'``, which replaces bad characters with their
1706 UTF-8 representation. Character conversions occur because the PAX
1707 format supports Unicode filenames, defaulting to UTF-8 encoding.
1708
1709 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1710 a function that can be used to exclude certain filenames from
1711 an archive.
1712 The function must take a filename and return true if the file
1713 should be excluded or false if it should be archived.
1714 The function is applied to both the name initially passed to :meth:`add`
1715 and to the names of files in recursively-added directories.
1716
1717 (All changes contributed by Lars Gustäbel).
1718
1719* An optional ``timeout`` parameter was added to the
1720 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1721 measured in seconds. (Added by Facundo Batista.)
1722
1723* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1724 the temporary file it created when the file is closed. This
1725 behaviour can now be changed by passing ``delete=False`` to the
1726 constructor. (Contributed by Damien Miller.)
1727
Georg Brandlb19be572007-12-29 10:57:00 +00001728 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001729
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001730 A new class, :class:`SpooledTemporaryFile`, behaves like
1731 a temporary file but stores its data in memory until a maximum size is
1732 exceeded. On reaching that limit, the contents will be written to
1733 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
1734
1735 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
1736 both work as context managers, so you can write
1737 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
1738 (Contributed by Alexander Belopolsky.)
1739
1740 .. Issue #2021
1741
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001742* The :mod:`test.test_support` module now contains a
1743 :func:`EnvironmentVarGuard`
1744 context manager that supports temporarily changing environment variables and
1745 automatically restores them to their old values.
1746
1747 Another context manager, :class:`TransientResource`, can surround calls
1748 to resources that may or may not be available; it will catch and
1749 ignore a specified list of exceptions. For example,
1750 a network test may ignore certain failures when connecting to an
1751 external web site::
1752
1753 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
1754 f = urllib.urlopen('https://sf.net')
1755 ...
1756
1757 (Contributed by Brett Cannon.)
1758
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001759* The :mod:`textwrap` module can now preserve existing whitespace
1760 at the beginnings and ends of the newly-created lines
1761 by specifying ``drop_whitespace=False``
1762 as an argument::
1763
1764 >>> S = """This sentence has a bunch of extra whitespace."""
1765 >>> print textwrap.fill(S, width=15)
1766 This sentence
1767 has a bunch
1768 of extra
1769 whitespace.
1770 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
1771 This sentence
1772 has a bunch
1773 of extra
1774 whitespace.
1775 >>>
1776
Georg Brandl27504da2008-03-04 07:25:54 +00001777 (Contributed by Dwayne Bailey.)
1778
Georg Brandlb19be572007-12-29 10:57:00 +00001779 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001780
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001781* The :mod:`timeit` module now accepts callables as well as strings
1782 for the statement being timed and for the setup code.
1783 Two convenience functions were added for creating
1784 :class:`Timer` instances:
1785 ``repeat(stmt, setup, time, repeat, number)`` and
1786 ``timeit(stmt, setup, time, number)`` create an instance and call
1787 the corresponding method. (Contributed by Erik Demaine.)
1788
Georg Brandlb19be572007-12-29 10:57:00 +00001789 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001790
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001791* An optional ``timeout`` parameter was added to the
1792 :func:`urllib.urlopen` function and the
1793 :class:`urllib.ftpwrapper` class constructor, as well as the
1794 :func:`urllib2.urlopen` function. The parameter specifies a timeout
1795 measured in seconds. For example::
1796
1797 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
1798 Traceback (most recent call last):
1799 ...
1800 urllib2.URLError: <urlopen error timed out>
1801 >>>
1802
1803 (Added by Facundo Batista.)
1804
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001805* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001806 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001807 their socket by passing True as the ``bind_and_activate``
1808 constructor parameter. This can be used to modify the instance's
1809 :attr:`allow_reuse_address` attribute before calling the
1810 :meth:`server_bind` and :meth:`server_activate` methods to
1811 open the socket and begin listening for connections.
1812 (Contributed by Peter Parente.)
1813
Georg Brandlb19be572007-12-29 10:57:00 +00001814 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001815
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001816 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
1817 attribute; if true, the exception and formatted traceback are returned
1818 as HTTP headers "X-Exception" and "X-Traceback". This feature is
1819 for debugging purposes only and should not be used on production servers
1820 because the tracebacks could possibly reveal passwords or other sensitive
1821 information. (Contributed by Alan McIntyre as part of his
1822 project for Google's Summer of Code 2007.)
1823
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001824* The :mod:`zipfile` module's :class:`ZipFile` class now has
1825 :meth:`extract` and :meth:`extractall` methods that will unpack
1826 a single file or all the files in the archive to the current directory, or
1827 to a specified directory::
1828
1829 z = zipfile.ZipFile('python-251.zip')
1830
1831 # Unpack a single file, writing it relative to the /tmp directory.
1832 z.extract('Python/sysmodule.c', '/tmp')
1833
1834 # Unpack all the files in the archive.
1835 z.extractall()
1836
1837 (Contributed by Alan McIntyre.)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001838
1839 .. Patch 467924
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001840
Georg Brandlb19be572007-12-29 10:57:00 +00001841.. ======================================================================
1842.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001843
1844Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00001845--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001846
1847Bill Janssen made extensive improvements to Python 2.6's support for
1848SSL.
1849
1850XXX use ssl.sslsocket - subclass of socket.socket.
1851
1852XXX Can specify if certificate is required, and obtain certificate info
1853by calling getpeercert method.
1854
1855XXX sslwrap() behaves like socket.ssl
1856
1857XXX Certain features require the OpenSSL package to be installed, notably
1858 the 'openssl' binary.
1859
1860.. seealso::
1861
1862 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001863
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001864
1865.. ======================================================================
1866
1867plistlib: A Property-List Parser
1868--------------------------------------------------
1869
1870A commonly-used format on MacOS X is the ``.plist`` format,
1871which stores basic data types (numbers, strings, lists,
1872and dictionaries) and serializes them into an XML-based format.
1873(It's a lot like the XML-RPC serialization of data types.)
1874
1875Despite being primarily used on MacOS X, the format
1876has nothing Mac-specific about it and the Python implementation works
1877on any platform that Python supports, so the :mod:`plistlib` module
1878has been promoted to the standard library.
1879
1880Using the module is simple::
1881
1882 import sys
1883 import plistlib
1884 import datetime
1885
1886 # Create data structure
1887 data_struct = dict(lastAccessed=datetime.datetime.now(),
1888 version=1,
1889 categories=('Personal', 'Shared', 'Private'))
1890
1891 # Create string containing XML.
1892 plist_str = plistlib.writePlistToString(data_struct)
1893 new_struct = plistlib.readPlistFromString(plist_str)
1894 print data_struct
1895 print new_struct
1896
1897 # Write data structure to a file and read it back.
1898 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
1899 new_struct = plistlib.readPlist('/tmp/customizations.plist')
1900
1901 # read/writePlist accepts file-like objects as well as paths.
1902 plistlib.writePlist(data_struct, sys.stdout)
1903
1904
Georg Brandlb19be572007-12-29 10:57:00 +00001905.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001906
1907
1908Build and C API Changes
1909=======================
1910
1911Changes to Python's build process and to the C API include:
1912
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001913* Python 2.6 can be built with Microsoft Visual Studio 2008.
1914 See the :file:`PCbuild9` directory for the build files.
1915 (Implemented by Christian Heimes.)
1916
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001917* Python now can only be compiled with C89 compilers (after 19
1918 years!). This means that the Python source tree can now drop its
1919 own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
1920 are in the C89 standard library.
1921
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001922* The BerkeleyDB module now has a C API object, available as
1923 ``bsddb.db.api``. This object can be used by other C extensions
1924 that wish to use the :mod:`bsddb` module for their own purposes.
1925 (Contributed by Duncan Grisby.)
1926
Georg Brandlb19be572007-12-29 10:57:00 +00001927 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001928
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001929* Several functions return information about the platform's
1930 floating-point support. :cfunc:`PyFloat_GetMax` returns
1931 the maximum representable floating point value,
1932 and :cfunc:`PyFloat_GetMin` returns the minimum
1933 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1934 containing more information from the :file:`float.h` file, such as
1935 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1936 (smallest difference between 1.0 and the next largest value
1937 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001938 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001939
Georg Brandlb19be572007-12-29 10:57:00 +00001940 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001941
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001942* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00001943 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001944 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001945 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001946
1947 .. Issue 1635
1948
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001949* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
1950 they are macros,
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001951 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001952 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001953 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
1954 The mixed-case macros are still available
1955 in Python 2.6 for backward compatibility.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001956
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001957 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001958
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001959* Distutils now places C extensions it builds in a
1960 different directory when running on a debug version of Python.
1961 (Contributed by Collin Winter.)
1962
1963 .. Patch 1530959
1964
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001965* Several basic data types, such as integers and strings, maintain
1966 internal free lists of objects that can be re-used. The data
1967 structures for these free lists now follow a naming convention: the
1968 variable is always named ``free_list``, the counter is always named
1969 ``numfree``, and a macro :cmacro:`Py<typename>_MAXFREELIST` is
1970 always defined.
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001971
Georg Brandlb19be572007-12-29 10:57:00 +00001972.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001973
1974
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001975Port-Specific Changes: Windows
1976-----------------------------------
1977
1978* The :mod:`msvcrt` module now supports
1979 both the normal and wide char variants of the console I/O
1980 API. The :func:`getwch` function reads a keypress and returns a Unicode
1981 value, as does the :func:`getwche` function. The :func:`putwch` function
1982 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001983 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001984
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001985* :func:`os.path.expandvars` will now expand environment variables
1986 in the form "%var%", and "~user" will be expanded into the
1987 user's home directory path. (Contributed by Josiah Carlson.)
1988
1989* The :mod:`socket` module's socket objects now have an
1990 :meth:`ioctl` method that provides a limited interface to the
1991 :cfunc:`WSAIoctl` system interface.
1992
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001993* The :mod:`_winreg` module now has a function,
1994 :func:`ExpandEnvironmentStrings`,
1995 that expands environment variable references such as ``%NAME%``
1996 in an input string. The handle objects provided by this
1997 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001998 in :keyword:`with` statements. (Contributed by Christian Heimes.)
1999
2000* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
2001 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
2002 were moved into the PC/ directory. The new PCbuild directory supports
2003 cross compilation for X64, debug builds and Profile Guided Optimization
2004 (PGO). PGO builds are roughly 10% faster than normal builds.
2005 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
2006 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002007
Georg Brandlb19be572007-12-29 10:57:00 +00002008.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002009
2010
2011.. _section-other:
2012
2013Other Changes and Fixes
2014=======================
2015
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002016As usual, there were a bunch of other improvements and bugfixes
2017scattered throughout the source tree. A search through the change
2018logs finds there were XXX patches applied and YYY bugs fixed between
2019Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002020
2021Some of the more notable changes are:
2022
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002023* It's now possible to prevent Python from writing any :file:`.pyc`
2024 or :file:`.pyo` files by either supplying the :option:`-B` switch
2025 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
2026 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00002027 are also used to set the :data:`sys.dont_write_bytecode` attribute;
2028 Python code can change this variable to control whether bytecode
2029 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002030 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00002031
Georg Brandlb19be572007-12-29 10:57:00 +00002032.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002033
2034
2035Porting to Python 2.6
2036=====================
2037
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002038This section lists previously described changes and other bugfixes
2039that may require changes to your code:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002040
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00002041* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00002042 now clears any existing contents of the deque
2043 before adding elements from the iterable. This change makes the
2044 behavior match that of ``list.__init__()``.
2045
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00002046* The :class:`Decimal` constructor now accepts leading and trailing
2047 whitespace when passed a string. Previously it would raise an
2048 :exc:`InvalidOperation` exception. On the other hand, the
2049 :meth:`create_decimal` method of :class:`Context` objects now
2050 explicitly disallows extra whitespace, raising a
2051 :exc:`ConversionSyntax` exception.
2052
2053* Due to an implementation accident, if you passed a file path to
2054 the built-in :func:`__import__` function, it would actually import
2055 the specified file. This was never intended to work, however, and
2056 the implementation now explicitly checks for this case and raises
2057 an :exc:`ImportError`.
2058
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00002059* The :mod:`socket` module exception :exc:`socket.error` now inherits
2060 from :exc:`IOError`. Previously it wasn't a subclass of
2061 :exc:`StandardError` but now it is, through :exc:`IOError`.
2062 (Implemented by Gregory P. Smith.)
2063
Georg Brandlb19be572007-12-29 10:57:00 +00002064 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00002065
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00002066* The :mod:`xmlrpclib` module no longer automatically converts
2067 :class:`datetime.date` and :class:`datetime.time` to the
2068 :class:`xmlrpclib.DateTime` type; the conversion semantics were
2069 not necessarily correct for all applications. Code using
2070 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
2071 instances.
2072
2073 .. Issue 1330538
2074
Andrew M. Kuchling7c29aae2008-03-26 00:30:02 +00002075* (3.0-warning mode) The :class:`Exception` class now warns
2076 when accessed using slicing or index access; having
2077 :class:`Exception` behave like a tuple is being phased out.
2078
2079* (3.0-warning mode) inequality comparisons between two dictionaries
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00002080 or two objects that don't implement comparison methods are reported
2081 as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2``
2082 is being phased out.
2083
2084 Comparisons between cells, which are an implementation detail of Python's
2085 scoping rules, also cause warnings because such comparisons are forbidden
2086 entirely in 3.0.
2087
Georg Brandlb19be572007-12-29 10:57:00 +00002088.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00002089
2090
2091.. _acks:
2092
2093Acknowledgements
2094================
2095
2096The author would like to thank the following people for offering suggestions,
2097corrections and assistance with various drafts of this article: .
2098