blob: c874939fd7c40450d83f3420fd9fae3d211736b7 [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
96to Python code as the boolean variable ``sys.py3kwarning``,
97and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000098
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
136<XXX>`__, `Launchpad <http://www.launchpad.net>`__, ` `Roundup
137<XXX>`__, and Trac <XXX>`__. The committee eventually settled on Jira
138and Roundup as the two candidates. Jira is a commercial product that
139offers a no-cost hosted instance to free-software projects; Roundup
140is an open-source project that requires volunteers
141to administer it and a server to host it.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000142
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000143After posting a call for volunteers, a new Roundup installation was
144set up at http://bugs.python.org. One installation of Roundup can
145host multiple trackers, and this server now also hosts issue trackers
146for Jython and for the Python web site. It will surely find
147other uses in the future.
148
149Hosting is kindly provided by `Upfront <XXX>`__ of XXX. Martin von
150Loewis put a lot of effort into importing existing bugs and patches
151from SourceForge; his scripts for this import are at XXX.
152
153.. seealso::
154
155 XXX Roundup web site.
156
157 bugs.python.org
158
159 bugs.jython.org
160
161 Python web site bug tracker
162
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000163
164New Documentation Format: ReStructured Text
165--------------------------------------------------
166
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000167Since the Python project's inception around 1989, the documentation
168had been written using LaTeX. At that time, most documentation was
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000169printed out for later study, not viewed online. LaTeX was widely used
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000170because it provided attractive printed output while remaining
171straightforward to write, once the basic rules of the markup have been
172learned.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000173
174LaTeX is still used today for writing technical publications destined
175for printing, but the landscape for programming tools has shifted. We
176no longer print out reams of documentation; instead, we browse through
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000177it online and HTML has become the most important format to support.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000178Unfortunately, converting LaTeX to HTML is fairly complicated, and
179Fred L. Drake Jr., the Python documentation editor for many years,
180spent a lot of time wrestling the conversion process into shape.
181Occasionally people would suggest converting the documentation into
182SGML or, later, XML, but performing a good conversion is a major task
183and no one pursued the task to completion.
184
185During the 2.6 development cycle, Georg Brandl put a substantial
186effort into building a new toolchain called Sphinx
187for processing the documentation.
188The input format is reStructured Text,
189a markup commonly used in the Python community that supports
190custom extensions and directives. Sphinx concentrates
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000191on HTML output, producing attractively styled
192and modern HTML, but printed output is still supported through
193conversion to LaTeX as an output format.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000194
195.. seealso::
196
197 `Docutils <http://docutils.sf.net>`__: The fundamental
198 reStructured Text parser and toolset.
199
Georg Brandlb19be572007-12-29 10:57:00 +0000200 :ref:`documenting-index`: Describes how to write for
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000201 Python's documentation.
202
203
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000204PEP 343: The 'with' statement
205=============================
206
207The previous version, Python 2.5, added the ':keyword:`with`'
208statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000209import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000210be specially enabled; this means that :keyword:`with` is now always a
211keyword. The rest of this section is a copy of the corresponding
212section from "What's New in Python 2.5" document; if you read
213it back when Python 2.5 came out, you can skip the rest of this
214section.
215
216The ':keyword:`with`' statement clarifies code that previously would use
217``try...finally`` blocks to ensure that clean-up code is executed. In this
218section, I'll discuss the statement as it will commonly be used. In the next
219section, I'll examine the implementation details and show how to write objects
220for use with this statement.
221
222The ':keyword:`with`' statement is a new control-flow structure whose basic
223structure is::
224
225 with expression [as variable]:
226 with-block
227
228The expression is evaluated, and it should result in an object that supports the
229context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
230methods.
231
232The object's :meth:`__enter__` is called before *with-block* is executed and
233therefore can run set-up code. It also may return a value that is bound to the
234name *variable*, if given. (Note carefully that *variable* is *not* assigned
235the result of *expression*.)
236
237After execution of the *with-block* is finished, the object's :meth:`__exit__`
238method is called, even if the block raised an exception, and can therefore run
239clean-up code.
240
241Some standard Python objects now support the context management protocol and can
242be used with the ':keyword:`with`' statement. File objects are one example::
243
244 with open('/etc/passwd', 'r') as f:
245 for line in f:
246 print line
247 ... more processing code ...
248
249After this statement has executed, the file object in *f* will have been
250automatically closed, even if the :keyword:`for` loop raised an exception part-
251way through the block.
252
253.. note::
254
255 In this case, *f* is the same object created by :func:`open`, because
256 :meth:`file.__enter__` returns *self*.
257
258The :mod:`threading` module's locks and condition variables also support the
259':keyword:`with`' statement::
260
261 lock = threading.Lock()
262 with lock:
263 # Critical section of code
264 ...
265
266The lock is acquired before the block is executed and always released once the
267block is complete.
268
269The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
270to save and restore the current decimal context, which encapsulates the desired
271precision and rounding characteristics for computations::
272
273 from decimal import Decimal, Context, localcontext
274
275 # Displays with default precision of 28 digits
276 v = Decimal('578')
277 print v.sqrt()
278
279 with localcontext(Context(prec=16)):
280 # All code in this block uses a precision of 16 digits.
281 # The original context is restored on exiting the block.
282 print v.sqrt()
283
284
285.. _new-26-context-managers:
286
287Writing Context Managers
288------------------------
289
290Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
291people will only use ':keyword:`with`' in company with existing objects and
292don't need to know these details, so you can skip the rest of this section if
293you like. Authors of new objects will need to understand the details of the
294underlying implementation and should keep reading.
295
296A high-level explanation of the context management protocol is:
297
298* The expression is evaluated and should result in an object called a "context
299 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
300 methods.
301
302* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000303 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000304 discarded.
305
306* The code in *BLOCK* is executed.
307
308* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
309 is called with the exception details, the same values returned by
310 :func:`sys.exc_info`. The method's return value controls whether the exception
311 is re-raised: any false value re-raises the exception, and ``True`` will result
312 in suppressing it. You'll only rarely want to suppress the exception, because
313 if you do the author of the code containing the ':keyword:`with`' statement will
314 never realize anything went wrong.
315
316* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
317 called, but *type*, *value*, and *traceback* are all ``None``.
318
319Let's think through an example. I won't present detailed code but will only
320sketch the methods necessary for a database that supports transactions.
321
322(For people unfamiliar with database terminology: a set of changes to the
323database are grouped into a transaction. Transactions can be either committed,
324meaning that all the changes are written into the database, or rolled back,
325meaning that the changes are all discarded and the database is unchanged. See
326any database textbook for more information.)
327
328Let's assume there's an object representing a database connection. Our goal will
329be to let the user write code like this::
330
331 db_connection = DatabaseConnection()
332 with db_connection as cursor:
333 cursor.execute('insert into ...')
334 cursor.execute('delete from ...')
335 # ... more operations ...
336
337The transaction should be committed if the code in the block runs flawlessly or
338rolled back if there's an exception. Here's the basic interface for
339:class:`DatabaseConnection` that I'll assume::
340
341 class DatabaseConnection:
342 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000343 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000344 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000345 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000346 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000347 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000348 "Rolls back current transaction"
349
350The :meth:`__enter__` method is pretty easy, having only to start a new
351transaction. For this application the resulting cursor object would be a useful
352result, so the method will return it. The user can then add ``as cursor`` to
353their ':keyword:`with`' statement to bind the cursor to a variable name. ::
354
355 class DatabaseConnection:
356 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000357 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000358 # Code to start a new transaction
359 cursor = self.cursor()
360 return cursor
361
362The :meth:`__exit__` method is the most complicated because it's where most of
363the work has to be done. The method has to check if an exception occurred. If
364there was no exception, the transaction is committed. The transaction is rolled
365back if there was an exception.
366
367In the code below, execution will just fall off the end of the function,
368returning the default value of ``None``. ``None`` is false, so the exception
369will be re-raised automatically. If you wished, you could be more explicit and
370add a :keyword:`return` statement at the marked location. ::
371
372 class DatabaseConnection:
373 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000374 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000375 if tb is None:
376 # No exception, so commit
377 self.commit()
378 else:
379 # Exception occurred, so rollback.
380 self.rollback()
381 # return False
382
383
384.. _module-contextlib:
385
386The contextlib module
387---------------------
388
389The new :mod:`contextlib` module provides some functions and a decorator that
390are useful for writing objects for use with the ':keyword:`with`' statement.
391
392The decorator is called :func:`contextmanager`, and lets you write a single
393generator function instead of defining a new class. The generator should yield
394exactly one value. The code up to the :keyword:`yield` will be executed as the
395:meth:`__enter__` method, and the value yielded will be the method's return
396value that will get bound to the variable in the ':keyword:`with`' statement's
397:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
398executed in the :meth:`__exit__` method. Any exception raised in the block will
399be raised by the :keyword:`yield` statement.
400
401Our database example from the previous section could be written using this
402decorator as::
403
404 from contextlib import contextmanager
405
406 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000407 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000408 cursor = connection.cursor()
409 try:
410 yield cursor
411 except:
412 connection.rollback()
413 raise
414 else:
415 connection.commit()
416
417 db = DatabaseConnection()
418 with db_transaction(db) as cursor:
419 ...
420
421The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
422that combines a number of context managers so you don't need to write nested
423':keyword:`with`' statements. In this example, the single ':keyword:`with`'
424statement both starts a database transaction and acquires a thread lock::
425
426 lock = threading.Lock()
427 with nested (db_transaction(db), lock) as (cursor, locked):
428 ...
429
430Finally, the :func:`closing(object)` function returns *object* so that it can be
431bound to a variable, and calls ``object.close`` at the end of the block. ::
432
433 import urllib, sys
434 from contextlib import closing
435
436 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
437 for line in f:
438 sys.stdout.write(line)
439
440
441.. seealso::
442
443 :pep:`343` - The "with" statement
444 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
445 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
446 ':keyword:`with`' statement, which can be helpful in learning how the statement
447 works.
448
449 The documentation for the :mod:`contextlib` module.
450
Georg Brandlb19be572007-12-29 10:57:00 +0000451.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000452
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000453.. _pep-0366:
454
455PEP 366: Explicit Relative Imports From a Main Module
456============================================================
457
458Python's :option:`-m` switch allows running a module as a script.
459When you ran a module that was located inside a package, relative
460imports didn't work correctly.
461
462The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
463When present, relative imports will be relative to the value of this
464attribute instead of the :attr:`__name__` attribute. PEP 302-style
465importers can then set :attr:`__package__`. The :mod:`runpy` module
466that implements the :option:`-m` switch now does this, so relative imports
467can now be used in scripts running from inside a package.
468
Georg Brandlb19be572007-12-29 10:57:00 +0000469.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000470
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000471.. ::
472
473 .. _pep-0370:
474
475 PEP 370: XXX
476 =====================================================
477
478 When you run Python, the module search page ``sys.modules`` usually
479 includes a directory whose path ends in ``"site-packages"``. This
480 directory is intended to hold locally-installed packages available to
481 all users on a machine or using a particular site installation.
482
483 Python 2.6 introduces a convention for user-specific site directories.
484
485 .. seealso::
486
487 :pep:`370` - XXX
488
489 PEP written by XXX; implemented by Christian Heimes.
490
491
492.. ======================================================================
493
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000494.. _pep-3101:
495
496PEP 3101: Advanced String Formatting
497=====================================================
498
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000499In Python 3.0, the `%` operator is supplemented by a more powerful
500string formatting method, :meth:`format`. Support for the
501:meth:`format` method has been backported to Python 2.6.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000502
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000503In 2.6, both 8-bit and Unicode strings have a `.format()` method that
504treats the string as a template and takes the arguments to be formatted.
505The formatting template uses curly brackets (`{`, `}`) as special characters::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000506
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000507 # Substitute positional argument 0 into the string.
508 "User ID: {0}".format("root") -> "User ID: root"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000509
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000510 # Use the named keyword arguments
511 uid = 'root'
512
513 'User ID: {uid} Last seen: {last_login}'.format(uid='root',
514 last_login = '5 Mar 2008 07:20') ->
515 'User ID: root Last seen: 5 Mar 2008 07:20'
516
517Curly brackets can be escaped by doubling them::
518
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000519 format("Empty dict: {{}}") -> "Empty dict: {}"
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000520
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000521Field names can be integers indicating positional arguments, such as
522``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
523supply compound field names that read attributes or access dictionary keys::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000524
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000525 import sys
526 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) ->
527 'Platform: darwin\n
528 Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) \n
529 [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
530
531 import mimetypes
532 'Content-type: {0[.mp4]}'.format(mimetypes.types_map) ->
533 'Content-type: video/mp4'
534
535Note that when using dictionary-style notation such as ``[.mp4]``, you
536don't need to put any quotation marks around the string; it will look
537up the value using ``.mp4`` as the key. Strings beginning with a
538number will be converted to an integer. You can't write more
539complicated expressions inside a format string.
540
541So far we've shown how to specify which field to substitute into the
542resulting string. The precise formatting used is also controllable by
543adding a colon followed by a format specifier. For example:
544
545 # Field 0: left justify, pad to 15 characters
546 # Field 1: right justify, pad to 6 characters
547 fmt = '{0:15} ${1:>6}'
548 fmt.format('Registration', 35) ->
549 'Registration $ 35'
550 fmt.format('Tutorial', 50) ->
551 'Tutorial $ 50'
552 fmt.format('Banquet', 125) ->
553 'Banquet $ 125'
554
555Format specifiers can reference other fields through nesting:
556
557 fmt = '{0:{1}}'
558 fmt.format('Invoice #1234', width) ->
559 'Invoice #1234 '
560 fmt.format('Invoice #1234', 15) ->
561 'Invoice #1234 '
562
563The alignment of a field within the desired width can be specified:
564
565================ ============================================
566Character Effect
567================ ============================================
568< (default) Left-align
569> Right-align
570^ Center
571= (For numeric types only) Pad after the sign.
572================ ============================================
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000573
574Format data types::
575
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000576 ... XXX take table from PEP 3101
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000577
578Classes and types can define a __format__ method to control how it's
579formatted. It receives a single argument, the format specifier::
580
581 def __format__(self, format_spec):
582 if isinstance(format_spec, unicode):
583 return unicode(str(self))
584 else:
585 return str(self)
586
587There's also a format() built-in that will format a single value. It calls
588the type's :meth:`__format__` method with the provided specifier::
589
590 >>> format(75.6564, '.2f')
591 '75.66'
592
593.. seealso::
594
595 :pep:`3101` - Advanced String Formatting
596 PEP written by Talin.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000597
598.. ======================================================================
599
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000600.. _pep-3105:
601
602PEP 3105: ``print`` As a Function
603=====================================================
604
605The ``print`` statement becomes the :func:`print` function in Python 3.0.
606Making :func:`print` a function makes it easier to replace within a
607module by doing 'def print(...)' or importing a new
608function from somewhere else.
609
610Python 2.6 has a ``__future__`` import that removes ``print`` as language
611syntax, letting you use the functional form instead. For example::
612
613 XXX need to check
614 from __future__ import print_function
615 print('# of entries', len(dictionary), file=sys.stderr)
616
617The signature of the new function is::
618
619 def print(*args, sep=' ', end='\n', file=None)
620
621The parameters are:
622
623 * **args**: positional arguments whose values will be printed out.
624 * **sep**: the separator, which will be printed between arguments.
625 * **end**: the ending text, which will be printed after all of the
626 arguments have been output.
627 * **file**: the file object to which the output will be sent.
628
629.. seealso::
630
631 :pep:`3105` - Advanced String Formatting
632 PEP written by Georg Brandl.
633
634.. ======================================================================
635
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000636.. _pep-3110:
637
638PEP 3110: Exception-Handling Changes
639=====================================================
640
641One error that Python programmers occasionally make
642is the following::
643
644 try:
645 ...
646 except TypeError, ValueError:
647 ...
648
649The author is probably trying to catch both
650:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
651actually does something different: it will catch
652:exc:`TypeError` and bind the resulting exception object
653to the local name ``"ValueError"``. The correct code
654would have specified a tuple::
655
656 try:
657 ...
658 except (TypeError, ValueError):
659 ...
660
661This error is possible because the use of the comma here is ambiguous:
662does it indicate two different nodes in the parse tree, or a single
663node that's a tuple.
664
665Python 3.0 changes the syntax to make this unambiguous by replacing
666the comma with the word "as". To catch an exception and store the
667exception object in the variable ``exc``, you must write::
668
669 try:
670 ...
671 except TypeError as exc:
672 ...
673
674Python 3.0 will only support the use of "as", and therefore interprets
675the first example as catching two different exceptions. Python 2.6
676supports both the comma and "as", so existing code will continue to
677work.
678
679.. seealso::
680
681 :pep:`3110` - Catching Exceptions in Python 3000
682 PEP written and implemented by Collin Winter.
683
Georg Brandlb19be572007-12-29 10:57:00 +0000684.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000685
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000686.. _pep-3112:
687
688PEP 3112: Byte Literals
689=====================================================
690
691Python 3.0 adopts Unicode as the language's fundamental string type, and
692denotes 8-bit literals differently, either as ``b'string'``
693or using a :class:`bytes` constructor. For future compatibility,
694Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
695and it also supports the ``b''`` notation.
696
697.. seealso::
698
699 :pep:`3112` - Bytes literals in Python 3000
700 PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
701
702.. ======================================================================
703
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000704.. _pep-3119:
705
706PEP 3119: Abstract Base Classes
707=====================================================
708
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000709XXX write this -- this section is currently just brief notes.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000710
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000711How to identify a file object?
712
713ABCs are a collection of classes describing various interfaces.
714Classes can derive from an ABC to indicate they support that ABC's
715interface. Concrete classes should obey the semantics specified by
716an ABC, but Python can't check this; it's up to the implementor.
717
718A metaclass lets you declare that an existing class or type
719derives from a particular ABC. You can even
720
721class AppendableSequence:
722 __metaclass__ = ABCMeta
723
724AppendableSequence.register(list)
725assert issubclass(list, AppendableSequence)
726assert isinstance([], AppendableSequence)
727
728@abstractmethod decorator -- you can't instantiate classes w/
729an abstract method.
730
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000731::
732
733 @abstractproperty decorator
734 @abstractproperty
735 def readonly(self):
736 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000737
738
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000739.. seealso::
740
741 :pep:`3119` - Introducing Abstract Base Classes
742 PEP written by Guido van Rossum and Talin.
743 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000744 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000745
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000746.. ======================================================================
747
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000748.. _pep-3127:
749
750PEP 3127: Integer Literal Support and Syntax
751=====================================================
752
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000753XXX write this -- this section is currently just brief notes.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000754
755Python 3.0 changes the syntax for octal integer literals, and
756adds supports for binary integers: 0o instad of 0,
757and 0b for binary. Python 2.6 doesn't support this, but a bin()
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000758builtin was added.
759
760XXX changes to the hex/oct builtins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000761
762
763New bin() built-in returns the binary form of a number.
764
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000765.. seealso::
766
767 :pep:`3127` - Integer Literal Support and Syntax
768 PEP written by Patrick Maupin.
769
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000770.. ======================================================================
771
772.. _pep-3129:
773
774PEP 3129: Class Decorators
775=====================================================
776
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000777Decorators have been extended from functions to classes. It's now legal to
778write::
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000779
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000780 @foo
781 @bar
782 class A:
783 pass
784
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +0000785This is equivalent to::
786
787 class A:
788 pass
789
790 A = foo(bar(A))
791
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000792XXX need to find a good motivating example.
793
794.. seealso::
795
796 :pep:`3129` - Class Decorators
797 PEP written by Collin Winter.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000798
799.. ======================================================================
800
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000801.. _pep-3141:
802
803PEP 3141: A Type Hierarchy for Numbers
804=====================================================
805
806In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000807inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000808This change was backported to 2.6 as the :mod:`numbers` module.
809
810The most general ABC is :class:`Number`. It defines no operations at
811all, and only exists to allow checking if an object is a number by
812doing ``isinstance(obj, Number)``.
813
814Numbers are further divided into :class:`Exact` and :class:`Inexact`.
815Exact numbers can represent values precisely and operations never
816round off the results or introduce tiny errors that may break the
Georg Brandl907a7202008-02-22 12:31:45 +0000817commutativity and associativity properties; inexact numbers may
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000818perform such rounding or introduce small errors. Integers, long
819integers, and rational numbers are exact, while floating-point
820and complex numbers are inexact.
821
822:class:`Complex` is a subclass of :class:`Number`. Complex numbers
823can undergo the basic operations of addition, subtraction,
824multiplication, division, and exponentiation, and you can retrieve the
825real and imaginary parts and obtain a number's conjugate. Python's built-in
826complex type is an implementation of :class:`Complex`.
827
828:class:`Real` further derives from :class:`Complex`, and adds
829operations that only work on real numbers: :func:`floor`, :func:`trunc`,
830rounding, taking the remainder mod N, floor division,
831and comparisons.
832
833:class:`Rational` numbers derive from :class:`Real`, have
834:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +0000835converted to floats. Python 2.6 adds a simple rational-number class,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000836:class:`Fraction`, in the :mod:`fractions` module. (It's called
837:class:`Fraction` instead of :class:`Rational` to avoid
838a name clash with :class:`numbers.Rational`.)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000839
840:class:`Integral` numbers derive from :class:`Rational`, and
841can be shifted left and right with ``<<`` and ``>>``,
842combined using bitwise operations such as ``&`` and ``|``,
843and can be used as array indexes and slice boundaries.
844
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000845In Python 3.0, the PEP slightly redefines the existing built-ins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000846:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
847one, :func:`math.trunc`, that's been backported to Python 2.6.
848:func:`math.trunc` rounds toward zero, returning the closest
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000849:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000850
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000851.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000852
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000853 :pep:`3141` - A Type Hierarchy for Numbers
854 PEP written by Jeffrey Yasskin.
855
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000856 XXX link: Discusses Scheme's numeric tower.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000857
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000858
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000859
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000860The :mod:`fractions` Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000861--------------------------------------------------
862
863To fill out the hierarchy of numeric types, a rational-number class
Mark Dickinsond058cd22008-02-10 21:29:51 +0000864has been added as the :mod:`fractions` module. Rational numbers are
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000865represented as a fraction, and can exactly represent
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000866numbers such as two-thirds that floating-point numbers can only
867approximate.
868
Mark Dickinsond058cd22008-02-10 21:29:51 +0000869The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000870that will be the numerator and denominator of the resulting fraction. ::
871
Mark Dickinsond058cd22008-02-10 21:29:51 +0000872 >>> from fractions import Fraction
873 >>> a = Fraction(2, 3)
874 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000875 >>> float(a), float(b)
876 (0.66666666666666663, 0.40000000000000002)
877 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000878 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000879 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000880 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000881
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000882To help in converting floating-point numbers to rationals,
883the float type now has a :meth:`as_integer_ratio()` method that returns
884the numerator and denominator for a fraction that evaluates to the same
885floating-point value::
886
887 >>> (2.5) .as_integer_ratio()
888 (5, 2)
889 >>> (3.1415) .as_integer_ratio()
890 (7074029114692207L, 2251799813685248L)
891 >>> (1./3) .as_integer_ratio()
892 (6004799503160661L, 18014398509481984L)
893
894Note that values that can only be approximated by floating-point
895numbers, such as 1./3, are not simplified to the number being
896approximated; the fraction attempts to match the floating-point value
897**exactly**.
898
Mark Dickinsond058cd22008-02-10 21:29:51 +0000899The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000900Mullender that was in Python's :file:`Demo/classes/` directory for a
901long time. This implementation was significantly updated by Jeffrey
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000902Yasskin.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000903
Georg Brandl8ec7f652007-08-15 14:28:01 +0000904Other Language Changes
905======================
906
907Here are all of the changes that Python 2.6 makes to the core Python language.
908
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000909* When calling a function using the ``**`` syntax to provide keyword
910 arguments, you are no longer required to use a Python dictionary;
911 any mapping will now work::
912
913 >>> def f(**kw):
914 ... print sorted(kw)
915 ...
916 >>> ud=UserDict.UserDict()
917 >>> ud['a'] = 1
918 >>> ud['b'] = 'string'
919 >>> f(**ud)
920 ['a', 'b']
921
Georg Brandlb19be572007-12-29 10:57:00 +0000922 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000923
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000924* The built-in types now have improved support for extended slicing syntax,
925 where various combinations of ``(start, stop, step)`` are supplied.
926 Previously, the support was partial and certain corner cases wouldn't work.
927 (Implemented by Thomas Wouters.)
928
Georg Brandlb19be572007-12-29 10:57:00 +0000929 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000930
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000931* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000932 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000933 adding or modifying a getter, setter or deleter function to an
934 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000935
936 class C(object):
937 @property
938 def x(self):
939 return self._x
940
941 @x.setter
942 def x(self, value):
943 self._x = value
944
945 @x.deleter
946 def x(self):
947 del self._x
948
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000949 class D(C):
950 @C.x.getter
951 def x(self):
952 return self._x * 2
953
954 @x.setter
955 def x(self, value):
956 self._x = value / 2
957
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000958
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000959* C functions and methods that use
960 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
961 have a :meth:`__complex__` method. In particular, the functions in the
962 :mod:`cmath` module will now accept objects with this method.
963 This is a backport of a Python 3.0 change.
964 (Contributed by Mark Dickinson.)
965
Georg Brandlb19be572007-12-29 10:57:00 +0000966 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000967
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000968 A numerical nicety: when creating a complex number from two floats
969 on systems that support signed zeros (-0 and +0), the
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000970 :func:`complex` constructor will now preserve the sign
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000971 of the zero.
972
Georg Brandlb19be572007-12-29 10:57:00 +0000973 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000974
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000975* More floating-point features were also added. The :func:`float` function
976 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000977 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000978 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +0000979 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000980
Georg Brandl225163d2008-03-05 07:10:35 +0000981 .. Patch 1635
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000982
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000983 Other functions in the :mod:`math` module, :func:`isinf` and
984 :func:`isnan`, return true if their floating-point argument is
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000985 infinite or Not A Number.
986
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000987 .. Patch 1640
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000988
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000989 The ``math.copysign(x, y)`` function
990 copies the sign bit of an IEEE 754 number, returning the absolute
991 value of *x* combined with the sign bit of *y*. For example,
992 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
993 Heimes.)
994
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000995* Changes to the :class:`Exception` interface
996 as dictated by :pep:`352` continue to be made. For 2.6,
997 the :attr:`message` attribute is being deprecated in favor of the
998 :attr:`args` attribute.
999
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001000* The :exc:`GeneratorExit` exception now subclasses
1001 :exc:`BaseException` instead of :exc:`Exception`. This means
1002 that an exception handler that does ``except Exception:``
1003 will not inadvertently catch :exc:`GeneratorExit`.
1004 (Contributed by Chad Austin.)
1005
Georg Brandlb19be572007-12-29 10:57:00 +00001006 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001007
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001008* Generator objects now have a :attr:`gi_code` attribute that refers to
1009 the original code object backing the generator.
1010 (Contributed by Collin Winter.)
1011
1012 .. Patch #1473257
1013
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001014* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001015 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001016
Georg Brandlb19be572007-12-29 10:57:00 +00001017 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001018
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001019* The :func:`complex` constructor now accepts strings containing
1020 parenthesized complex numbers, letting ``complex(repr(cmplx))``
1021 will now round-trip values. For example, ``complex('(3+4j)')``
1022 now returns the value (3+4j).
1023
Georg Brandlb19be572007-12-29 10:57:00 +00001024 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001025
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001026* The string :meth:`translate` method now accepts ``None`` as the
1027 translation table parameter, which is treated as the identity
1028 transformation. This makes it easier to carry out operations
1029 that only delete characters. (Contributed by Bengt Richter.)
1030
Georg Brandlb19be572007-12-29 10:57:00 +00001031 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001032
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001033* The built-in :func:`dir` function now checks for a :meth:`__dir__`
1034 method on the objects it receives. This method must return a list
1035 of strings containing the names of valid attributes for the object,
1036 and lets the object control the value that :func:`dir` produces.
1037 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +00001038 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001039
Georg Brandlb19be572007-12-29 10:57:00 +00001040 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001041
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001042* Instance method objects have new attributes for the object and function
1043 comprising the method; the new synonym for :attr:`im_self` is
1044 :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`.
1045 The old names are still supported in Python 2.6; they're gone in 3.0.
1046
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047* An obscure change: when you use the the :func:`locals` function inside a
1048 :keyword:`class` statement, the resulting dictionary no longer returns free
1049 variables. (Free variables, in this case, are variables referred to in the
1050 :keyword:`class` statement that aren't attributes of the class.)
1051
Georg Brandlb19be572007-12-29 10:57:00 +00001052.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001053
1054
1055Optimizations
1056-------------
1057
Georg Brandlaf30b282008-01-15 06:55:56 +00001058* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001059 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +00001060 for a particular class; once cached, the interpreter doesn't need to
1061 traverse base classes to figure out the right method to call.
1062 The cache is cleared if a base class or the class itself is modified,
1063 so the cache should remain correct even in the face of Python's dynamic
1064 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001065 (Original optimization implemented by Armin Rigo, updated for
1066 Python 2.6 by Kevin Jacobs.)
1067
Georg Brandl225163d2008-03-05 07:10:35 +00001068 .. Patch 1700288
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001069
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001070* All of the functions in the :mod:`struct` module have been rewritten in
1071 C, thanks to work at the Need For Speed sprint.
1072 (Contributed by Raymond Hettinger.)
1073
Georg Brandl8ec7f652007-08-15 14:28:01 +00001074* Internally, a bit is now set in type objects to indicate some of the standard
1075 built-in types. This speeds up checking if an object is a subclass of one of
1076 these types. (Contributed by Neal Norwitz.)
1077
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001078* Unicode strings now uses faster code for detecting
1079 whitespace and line breaks; this speeds up the :meth:`split` method
1080 by about 25% and :meth:`splitlines` by 35%.
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001081 (Contributed by Antoine Pitrou.) Memory usage is reduced
1082 by using pymalloc for the Unicode string's data.
1083
1084* The ``with`` statement now stores the :meth:`__exit__` method on the stack,
1085 producing a small speedup. (Implemented by Nick Coghlan.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001086
1087* To reduce memory usage, the garbage collector will now clear internal
1088 free lists when garbage-collecting the highest generation of objects.
1089 This may return memory to the OS sooner.
1090
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
1092benchmark around XX% faster than Python 2.5.
1093
Georg Brandlb19be572007-12-29 10:57:00 +00001094.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001095
1096
1097New, Improved, and Deprecated Modules
1098=====================================
1099
1100As usual, Python's standard library received a number of enhancements and bug
1101fixes. Here's a partial list of the most notable changes, sorted alphabetically
1102by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
1103complete list of changes, or look through the CVS logs for all the details.
1104
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001105* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
1106 available, instead of restricting itself to protocol 1.
1107 (Contributed by W. Barnes.)
1108
Georg Brandlb19be572007-12-29 10:57:00 +00001109 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001110
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001111* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001112 fieldnames)` is a factory function that creates subclasses of the standard tuple
1113 whose fields are accessible by name as well as index. For example::
1114
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +00001115 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001116 ... 'id name type size')
1117 # Names are separated by spaces or commas.
1118 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +00001119 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001120 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001121
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001122 >>> var = var_type(1, 'frequency', 'int', 4)
1123 >>> print var[0], var.id # Equivalent
1124 1 1
1125 >>> print var[2], var.type # Equivalent
1126 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +00001127 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001128 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +00001129 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001130 >>> v2
1131 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001132
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001133 Where the new :class:`namedtuple` type proved suitable, the standard
1134 library has been modified to return them. For example,
1135 the :meth:`Decimal.as_tuple` method now returns a named tuple with
1136 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1137
Georg Brandl8ec7f652007-08-15 14:28:01 +00001138 (Contributed by Raymond Hettinger.)
1139
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001140* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +00001141 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001142 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +00001143 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001144 old items to be discarded.
1145
1146 ::
1147
1148 >>> from collections import deque
1149 >>> dq=deque(maxlen=3)
1150 >>> dq
1151 deque([], maxlen=3)
1152 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
1153 >>> dq
1154 deque([1, 2, 3], maxlen=3)
1155 >>> dq.append(4)
1156 >>> dq
1157 deque([2, 3, 4], maxlen=3)
1158
1159 (Contributed by Raymond Hettinger.)
1160
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001161* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
1162 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
1163
Georg Brandlb19be572007-12-29 10:57:00 +00001164 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001165
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001166 The :mod:`ctypes` string, buffer and array types also have improved
1167 support for extended slicing syntax,
1168 where various combinations of ``(start, stop, step)`` are supplied.
1169 (Implemented by Thomas Wouters.)
1170
Georg Brandlb19be572007-12-29 10:57:00 +00001171 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001172
Georg Brandl8ec7f652007-08-15 14:28:01 +00001173* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001174 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001175 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001176 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001177
1178 # Boldface text starting at y=0,x=21
1179 # and affecting the rest of the line.
1180 stdscr.chgat(0,21, curses.A_BOLD)
1181
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001182 The :class:`Textbox` class in the :mod:`curses.textpad` module
1183 now supports editing in insert mode as well as overwrite mode.
1184 Insert mode is enabled by supplying a true value for the *insert_mode*
1185 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001186
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001187* The :mod:`datetime` module's :meth:`strftime` methods now support a
1188 ``%f`` format code that expands to the number of microseconds in the
1189 object, zero-padded on
1190 the left to six places. (Contributed by XXX.)
1191
1192 .. Patch 1158
1193
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001194* The :mod:`decimal` module was updated to version 1.66 of
1195 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
1196 include some methods for some basic mathematical functions such as
1197 :meth:`exp` and :meth:`log10`::
1198
1199 >>> Decimal(1).exp()
1200 Decimal("2.718281828459045235360287471")
1201 >>> Decimal("2.7182818").ln()
1202 Decimal("0.9999999895305022877376682436")
1203 >>> Decimal(1000).log10()
1204 Decimal("3")
1205
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001206 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
1207 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1208
1209 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
1210 support added by Raymond Hettinger.)
1211
1212* The :mod:`difflib` module's :class:`SequenceMatcher` class
1213 now returns named tuples representing matches.
1214 In addition to behaving like tuples, the returned values
1215 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
1216 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001217
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001218* An optional ``timeout`` parameter was added to the
1219 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
1220 method, specifying a timeout measured in seconds. (Added by Facundo
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001221 Batista.) Also, the :class:`FTP` class's
1222 :meth:`storbinary` and :meth:`storlines`
1223 now take an optional *callback* parameter that will be called with
1224 each block of data after the data has been sent.
1225 (Contributed by Phil Schwartz.)
1226
1227 .. Patch 1221598
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001228
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001229* The :func:`reduce` built-in function is also available in the
1230 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
1231 only available from :mod:`functools`; currently there are no plans
1232 to drop the built-in in the 2.x series. (Patched by
1233 Christian Heimes.)
1234
Georg Brandlb19be572007-12-29 10:57:00 +00001235 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001236
Georg Brandl8ec7f652007-08-15 14:28:01 +00001237* The :func:`glob.glob` function can now return Unicode filenames if
1238 a Unicode path was used and Unicode filenames are matched within the directory.
1239
Georg Brandlb19be572007-12-29 10:57:00 +00001240 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +00001241
1242* The :mod:`gopherlib` module has been removed.
1243
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001244* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
1245 takes any number of iterables that return data *in sorted
1246 order*, and returns a new iterator that returns the contents of all
1247 the iterators, also in sorted order. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001248
1249 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
1250 [1, 2, 3, 5, 8, 9, 16]
1251
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001252 Another new function, ``heappushpop(heap, item)``,
1253 pushes *item* onto *heap*, then pops off and returns the smallest item.
1254 This is more efficient than making a call to :func:`heappush` and then
1255 :func:`heappop`.
1256
Georg Brandl8ec7f652007-08-15 14:28:01 +00001257 (Contributed by Raymond Hettinger.)
1258
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001259* An optional ``timeout`` parameter was added to the
1260 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
1261 class constructors, specifying a timeout measured in seconds.
1262 (Added by Facundo Batista.)
1263
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001264* Most of the :mod:`inspect` module's functions, such as
1265 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
1266 In addition to behaving like tuples, the elements of the return value
1267 can also be accessed as attributes.
1268 (Contributed by Raymond Hettinger.)
1269
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001270 Some new functions in the module include
1271 :func:`isgenerator`, :func:`isgeneratorfunction`,
1272 and :func:`isabstract`.
1273
1274* The :mod:`itertools` module gained several new functions.
1275
1276 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
1277 each of the elements; if some of the iterables are shorter than
1278 others, the missing values are set to *fillvalue*. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001279
1280 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
1281 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
1282
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001283 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
1284 of the supplied iterables, a set of tuples containing
1285 every possible combination of the elements returned from each iterable. ::
1286
1287 itertools.product([1,2,3], [4,5,6]) ->
1288 [(1, 4), (1, 5), (1, 6),
1289 (2, 4), (2, 5), (2, 6),
1290 (3, 4), (3, 5), (3, 6)]
1291
1292 The optional *repeat* keyword argument is used for taking the
1293 product of an iterable or a set of iterables with themselves,
1294 repeated *N* times. With a single iterable argument, *N*-tuples
1295 are returned::
1296
1297 itertools.product([1,2], repeat=3)) ->
1298 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
1299 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
1300
1301 With two iterables, *2N*-tuples are returned. ::
1302
1303 itertools(product([1,2], [3,4], repeat=2) ->
1304 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
1305 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
1306 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
1307 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
1308
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001309 ``combinations(iterable, r)`` returns sub-sequences of length *r* from
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001310 the elements of *iterable*. ::
1311
1312 itertools.combinations('123', 2) ->
1313 [('1', '2'), ('1', '3'), ('2', '3')]
1314
1315 itertools.combinations('123', 3) ->
1316 [('1', '2', '3')]
1317
1318 itertools.combinations('1234', 3) ->
1319 [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
1320 ('2', '3', '4')]
1321
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001322 ``permutations(iter[, r])`` returns all the permutations of length *r* of
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001323 the iterable's elements. If *r* is not specified, it will default to the
1324 number of elements produced by the iterable.
1325
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001326 itertools.permutations([1,2,3,4], 2) ->
1327 [(1, 2), (1, 3), (1, 4),
1328 (2, 1), (2, 3), (2, 4),
1329 (3, 1), (3, 2), (3, 4),
1330 (4, 1), (4, 2), (4, 3)]
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001331
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001332 ``itertools.chain(*iterables)` is an existing function in
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001333 :mod:`itertools` that gained a new constructor in Python 2.6.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001334 ``itertools.chain.from_iterable(iterable)`` takes a single
1335 iterable that should return other iterables. :func:`chain` will
1336 then return all the elements of the first iterable, then
1337 all the elements of the second, and so on. ::
1338
1339 chain.from_iterable([[1,2,3], [4,5,6]]) ->
1340 [1, 2, 3, 4, 5, 6]
1341
1342 (All contributed by Raymond Hettinger.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001343
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001344* The :mod:`logging` module's :class:`FileHandler` class
1345 and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
1346 and :class:`TimedRotatingFileHandler` now
1347 have an optional *delay* parameter to its constructor. If *delay*
1348 is true, opening of the log file is deferred until the first
1349 :meth:`emit` call is made. (Contributed by Vinay Sajip.)
1350
Georg Brandl8ec7f652007-08-15 14:28:01 +00001351* The :mod:`macfs` module has been removed. This in turn required the
1352 :func:`macostools.touched` function to be removed because it depended on the
1353 :mod:`macfs` module.
1354
Georg Brandlb19be572007-12-29 10:57:00 +00001355 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001357* :class:`mmap` objects now have a :meth:`rfind` method that finds
1358 a substring, beginning at the end of the string and searching
1359 backwards. The :meth:`find` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001360 also gained an *end* parameter containing the index at which to stop
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001361 the forward search.
1362 (Contributed by John Lenton.)
1363
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001364* The :mod:`new` module has been removed from Python 3.0.
1365 Importing it therefore
1366 triggers a warning message when Python is running in 3.0-warning
1367 mode.
1368
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001369* The :mod:`operator` module gained a
1370 :func:`methodcaller` function that takes a name and an optional
1371 set of arguments, returning a callable that will call
1372 the named function on any arguments passed to it. For example::
1373
1374 >>> # Equivalent to lambda s: s.replace('old', 'new')
1375 >>> replacer = operator.methodcaller('replace', 'old', 'new')
1376 >>> replacer('old wine in old bottles')
1377 'new wine in new bottles'
1378
Georg Brandl27504da2008-03-04 07:25:54 +00001379 (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001380
1381 The :func:`attrgetter` function now accepts dotted names and performs
1382 the corresponding attribute lookups::
1383
1384 >>> inst_name = operator.attrgetter('__class__.__name__')
1385 >>> inst_name('')
1386 'str'
1387 >>> inst_name(help)
1388 '_Helper'
1389
Georg Brandl27504da2008-03-04 07:25:54 +00001390 (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001391
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001392* New functions in the :mod:`os` module include
1393 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
1394 and ``lchmod(path, mode)``, on operating systems that support these
1395 functions. :func:`fchmod` and :func:`fchown` let you change the mode
1396 and ownership of an opened file, and :func:`lchmod` changes the mode
1397 of a symlink.
1398
1399 (Contributed by Georg Brandl and Christian Heimes.)
1400
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001401* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001402 set to True, it will follow symlinks pointing to directories and
1403 visit the directory's contents. For backward compatibility, the
1404 parameter's default value is false. Note that the function can fall
1405 into an infinite recursion if there's a symlink that points to a
1406 parent directory.
1407
Georg Brandlb19be572007-12-29 10:57:00 +00001408 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001409
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001410* The ``os.environ`` object's :meth:`clear` method will now unset the
1411 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001412 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001413
Georg Brandlb19be572007-12-29 10:57:00 +00001414 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001415
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001416* In the :mod:`os.path` module, the :func:`splitext` function
1417 has been changed to not split on leading period characters.
1418 This produces better results when operating on Unix's dot-files.
1419 For example, ``os.path.splitext('.ipython')``
1420 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
1421
Georg Brandlb19be572007-12-29 10:57:00 +00001422 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001423
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001424 A new function, :func:`relpath(path, start)` returns a relative path
1425 from the ``start`` path, if it's supplied, or from the current
1426 working directory to the destination ``path``. (Contributed by
1427 Richard Barran.)
1428
Georg Brandlb19be572007-12-29 10:57:00 +00001429 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001430
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001431 On Windows, :func:`os.path.expandvars` will now expand environment variables
1432 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001433 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001434
Georg Brandlb19be572007-12-29 10:57:00 +00001435 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001436
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001437* The Python debugger provided by the :mod:`pdb` module
1438 gained a new command: "run" restarts the Python program being debugged,
1439 and can optionally take new command-line arguments for the program.
1440 (Contributed by Rocky Bernstein.)
1441
Georg Brandlb19be572007-12-29 10:57:00 +00001442 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001443
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001444* The :mod:`pickletools` module now has an :func:`optimize` function
1445 that takes a string containing a pickle and removes some unused
1446 opcodes, returning a shorter pickle that contains the same data structure.
1447 (Contributed by Raymond Hettinger.)
1448
Georg Brandl8ec7f652007-08-15 14:28:01 +00001449* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
1450 are wrappers for the corresponding system calls (where they're available).
1451 Constants for the flag values are defined in the :mod:`stat` module; some
1452 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
1453 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
1454 file. (Contributed by M. Levinson.)
1455
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001456 ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors
1457 from *low* to *high*, ignoring any errors and not including *high* itself.
1458 This function is now used by the :mod:`subprocess` module to make starting
1459 processes faster. (Contributed by Georg Brandl.)
1460
1461 .. Patch #1663329
1462
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00001463* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
1464 their :attr:`buffer_size` attribute to change the size of the buffer
1465 used to hold character data.
1466 (Contributed by Achim Gaedke.)
1467
1468 .. Patch 1137
1469
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001470* The :mod:`Queue` module now provides queue classes that retrieve entries
1471 in different orders. The :class:`PriorityQueue` class stores
1472 queued items in a heap and retrieves them in priority order,
1473 and :class:`LifoQueue` retrieves the most recently added entries first,
1474 meaning that it behaves like a stack.
1475 (Contributed by Raymond Hettinger.)
1476
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001477* The :mod:`random` module's :class:`Random` objects can
1478 now be pickled on a 32-bit system and unpickled on a 64-bit
1479 system, and vice versa. Unfortunately, this change also means
1480 that Python 2.6's :class:`Random` objects can't be unpickled correctly
1481 on earlier versions of Python.
1482 (Contributed by Shawn Ligocki.)
1483
Georg Brandlb19be572007-12-29 10:57:00 +00001484 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001485
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001486* Long regular expression searches carried out by the :mod:`re`
1487 module will now check for signals being delivered, so especially
1488 long searches can now be interrupted.
1489 (Contributed by Josh Hoyt and Ralf Schmitt.)
1490
Georg Brandl225163d2008-03-05 07:10:35 +00001491 .. Patch 846388
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001492
Georg Brandl8ec7f652007-08-15 14:28:01 +00001493* The :mod:`rgbimg` module has been removed.
1494
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001495* The :mod:`sched` module's :class:`scheduler` instances now
1496 have a read-only :attr:`queue` attribute that returns the
1497 contents of the scheduler's queue, represented as a list of
Georg Brandl225163d2008-03-05 07:10:35 +00001498 named tuples with the fields ``(time, priority, action, argument)``.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001499 (Contributed by Raymond Hettinger XXX check.)
Georg Brandl225163d2008-03-05 07:10:35 +00001500
1501 .. Patch 1861
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001502
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001503* The :mod:`sets` module has been deprecated; it's better to
1504 use the built-in :class:`set` and :class:`frozenset` types.
1505
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001506* Integrating signal handling with GUI handling event loops
1507 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001508 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001509 The :mod:`signal` module can now make this more efficient.
1510 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
1511 to be used; when a signal is received, a byte is written to that
1512 file descriptor. There's also a C-level function,
1513 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
1514
1515 Event loops will use this by opening a pipe to create two descriptors,
1516 one for reading and one for writing. The writeable descriptor
1517 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
1518 will be added to the list of descriptors monitored by the event loop via
1519 :cfunc:`select` or :cfunc:`poll`.
1520 On receiving a signal, a byte will be written and the main event loop
1521 will be woken up, without the need to poll.
1522
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001523 (Contributed by Adam Olsen.)
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001524
Georg Brandl225163d2008-03-05 07:10:35 +00001525 .. Patch 1583
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001526
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001527 The :func:`siginterrupt` function is now available from Python code,
1528 and allows changing whether signals can interrupt system calls or not.
1529 (Contributed by Ralf Schmitt.)
1530
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001531* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
1532 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001533 interface identical to the existing :class:`SMTP` class. Both
1534 class constructors also have an optional ``timeout`` parameter
1535 that specifies a timeout for the initial connection attempt, measured in
1536 seconds.
1537
1538 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001539 the module. LMTP is used in place of SMTP when transferring e-mail
1540 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001541
1542 (SMTP over SSL contributed by Monty Taylor; timeout parameter
1543 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001544 Hedstrom.)
1545
Georg Brandlb19be572007-12-29 10:57:00 +00001546 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +00001547
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001548* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
1549 and forgets any knowledge obtained from the server not obtained from
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001550 the TLS negotiation itself. (Patch contributed by Bill Fenner.)
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001551
1552 .. Issue 829951
1553
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001554* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1555 a high-performance non-IP-based protocol designed for use in clustered
1556 environments. TIPC addresses are 4- or 5-tuples.
1557 (Contributed by Alberto Bertogli.)
1558
1559 .. Patch #1646
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00001560
1561* The base classes in the :mod:`SocketServer` module now support
1562 calling a :meth:`handle_timeout` method after a span of inactivity
1563 specified by the server's :attr:`timeout` attribute. (Contributed
1564 by Michael Pomraning.)
1565
1566 .. Patch #742598
Andrew M. Kuchling1d136bb2008-03-06 01:36:27 +00001567
1568* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
1569 using the format character ``'?'``.
1570 (Contributed by David Remahl.)
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001571
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001572* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001573 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001574 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001575 derived from the :file:`float.h` file. Attributes of this object
1576 include
1577 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001578 (smallest difference between 1.0 and the next largest value
1579 representable), and several others. (Contributed by Christian Heimes.)
1580
Georg Brandlb19be572007-12-29 10:57:00 +00001581 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001582
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00001583 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
1584 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1585 If this variable is true, the compiled files are not written. The
1586 variable is initially set on start-up by supplying the :option:`-B`
1587 switch to the Python interpreter, or by setting the
1588 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
1589 running the interpreter. Python code can subsequently
1590 change the value of this variable to control whether bytecode files
1591 are written or not.
1592 (Contributed by Neal Norwitz and Georg Brandl.)
1593
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001594 Information about the command-line arguments supplied to the Python
1595 interpreter are available as attributes of a ``sys.flags`` named
1596 tuple. For example, the :attr:`verbose` attribute is true if Python
1597 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1598 These attributes are all read-only.
1599 (Contributed by Christian Heimes.)
1600
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001601 It's now possible to determine the current profiler and tracer functions
1602 by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
1603 (Contributed by Georg Brandl.)
1604
1605 .. Patch #1648
1606
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001607* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1608 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1609 format that was already supported. The default format
1610 is GNU tar; specify the ``format`` parameter to open a file
1611 using a different format::
1612
1613 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1614
1615 The new ``errors`` parameter lets you specify an error handling
1616 scheme for character conversions: the three standard ways Python can
1617 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1618 special value ``'utf-8'``, which replaces bad characters with their
1619 UTF-8 representation. Character conversions occur because the PAX
1620 format supports Unicode filenames, defaulting to UTF-8 encoding.
1621
1622 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1623 a function that can be used to exclude certain filenames from
1624 an archive.
1625 The function must take a filename and return true if the file
1626 should be excluded or false if it should be archived.
1627 The function is applied to both the name initially passed to :meth:`add`
1628 and to the names of files in recursively-added directories.
1629
1630 (All changes contributed by Lars Gustäbel).
1631
1632* An optional ``timeout`` parameter was added to the
1633 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1634 measured in seconds. (Added by Facundo Batista.)
1635
1636* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1637 the temporary file it created when the file is closed. This
1638 behaviour can now be changed by passing ``delete=False`` to the
1639 constructor. (Contributed by Damien Miller.)
1640
Georg Brandlb19be572007-12-29 10:57:00 +00001641 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001642
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001643 A new class, :class:`SpooledTemporaryFile`, behaves like
1644 a temporary file but stores its data in memory until a maximum size is
1645 exceeded. On reaching that limit, the contents will be written to
1646 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
1647
1648 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
1649 both work as context managers, so you can write
1650 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
1651 (Contributed by Alexander Belopolsky.)
1652
1653 .. Issue #2021
1654
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001655* The :mod:`test.test_support` module now contains a
1656 :func:`EnvironmentVarGuard`
1657 context manager that supports temporarily changing environment variables and
1658 automatically restores them to their old values.
1659
1660 Another context manager, :class:`TransientResource`, can surround calls
1661 to resources that may or may not be available; it will catch and
1662 ignore a specified list of exceptions. For example,
1663 a network test may ignore certain failures when connecting to an
1664 external web site::
1665
1666 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
1667 f = urllib.urlopen('https://sf.net')
1668 ...
1669
1670 (Contributed by Brett Cannon.)
1671
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001672* The :mod:`textwrap` module can now preserve existing whitespace
1673 at the beginnings and ends of the newly-created lines
1674 by specifying ``drop_whitespace=False``
1675 as an argument::
1676
1677 >>> S = """This sentence has a bunch of extra whitespace."""
1678 >>> print textwrap.fill(S, width=15)
1679 This sentence
1680 has a bunch
1681 of extra
1682 whitespace.
1683 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
1684 This sentence
1685 has a bunch
1686 of extra
1687 whitespace.
1688 >>>
1689
Georg Brandl27504da2008-03-04 07:25:54 +00001690 (Contributed by Dwayne Bailey.)
1691
Georg Brandlb19be572007-12-29 10:57:00 +00001692 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001693
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001694* The :mod:`timeit` module now accepts callables as well as strings
1695 for the statement being timed and for the setup code.
1696 Two convenience functions were added for creating
1697 :class:`Timer` instances:
1698 ``repeat(stmt, setup, time, repeat, number)`` and
1699 ``timeit(stmt, setup, time, number)`` create an instance and call
1700 the corresponding method. (Contributed by Erik Demaine.)
1701
Georg Brandlb19be572007-12-29 10:57:00 +00001702 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001703
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001704* An optional ``timeout`` parameter was added to the
1705 :func:`urllib.urlopen` function and the
1706 :class:`urllib.ftpwrapper` class constructor, as well as the
1707 :func:`urllib2.urlopen` function. The parameter specifies a timeout
1708 measured in seconds. For example::
1709
1710 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
1711 Traceback (most recent call last):
1712 ...
1713 urllib2.URLError: <urlopen error timed out>
1714 >>>
1715
1716 (Added by Facundo Batista.)
1717
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001718* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001719 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001720 their socket by passing True as the ``bind_and_activate``
1721 constructor parameter. This can be used to modify the instance's
1722 :attr:`allow_reuse_address` attribute before calling the
1723 :meth:`server_bind` and :meth:`server_activate` methods to
1724 open the socket and begin listening for connections.
1725 (Contributed by Peter Parente.)
1726
Georg Brandlb19be572007-12-29 10:57:00 +00001727 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001728
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001729 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
1730 attribute; if true, the exception and formatted traceback are returned
1731 as HTTP headers "X-Exception" and "X-Traceback". This feature is
1732 for debugging purposes only and should not be used on production servers
1733 because the tracebacks could possibly reveal passwords or other sensitive
1734 information. (Contributed by Alan McIntyre as part of his
1735 project for Google's Summer of Code 2007.)
1736
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001737* The :mod:`zipfile` module's :class:`ZipFile` class now has
1738 :meth:`extract` and :meth:`extractall` methods that will unpack
1739 a single file or all the files in the archive to the current directory, or
1740 to a specified directory::
1741
1742 z = zipfile.ZipFile('python-251.zip')
1743
1744 # Unpack a single file, writing it relative to the /tmp directory.
1745 z.extract('Python/sysmodule.c', '/tmp')
1746
1747 # Unpack all the files in the archive.
1748 z.extractall()
1749
1750 (Contributed by Alan McIntyre.)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001751
1752 .. Patch 467924
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001753
Georg Brandlb19be572007-12-29 10:57:00 +00001754.. ======================================================================
1755.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001756
1757Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00001758--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001759
1760Bill Janssen made extensive improvements to Python 2.6's support for
1761SSL.
1762
1763XXX use ssl.sslsocket - subclass of socket.socket.
1764
1765XXX Can specify if certificate is required, and obtain certificate info
1766by calling getpeercert method.
1767
1768XXX sslwrap() behaves like socket.ssl
1769
1770XXX Certain features require the OpenSSL package to be installed, notably
1771 the 'openssl' binary.
1772
1773.. seealso::
1774
1775 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001776
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001777
1778.. ======================================================================
1779
1780plistlib: A Property-List Parser
1781--------------------------------------------------
1782
1783A commonly-used format on MacOS X is the ``.plist`` format,
1784which stores basic data types (numbers, strings, lists,
1785and dictionaries) and serializes them into an XML-based format.
1786(It's a lot like the XML-RPC serialization of data types.)
1787
1788Despite being primarily used on MacOS X, the format
1789has nothing Mac-specific about it and the Python implementation works
1790on any platform that Python supports, so the :mod:`plistlib` module
1791has been promoted to the standard library.
1792
1793Using the module is simple::
1794
1795 import sys
1796 import plistlib
1797 import datetime
1798
1799 # Create data structure
1800 data_struct = dict(lastAccessed=datetime.datetime.now(),
1801 version=1,
1802 categories=('Personal', 'Shared', 'Private'))
1803
1804 # Create string containing XML.
1805 plist_str = plistlib.writePlistToString(data_struct)
1806 new_struct = plistlib.readPlistFromString(plist_str)
1807 print data_struct
1808 print new_struct
1809
1810 # Write data structure to a file and read it back.
1811 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
1812 new_struct = plistlib.readPlist('/tmp/customizations.plist')
1813
1814 # read/writePlist accepts file-like objects as well as paths.
1815 plistlib.writePlist(data_struct, sys.stdout)
1816
1817
Georg Brandlb19be572007-12-29 10:57:00 +00001818.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001819
1820
1821Build and C API Changes
1822=======================
1823
1824Changes to Python's build process and to the C API include:
1825
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001826* Python 2.6 can be built with Microsoft Visual Studio 2008.
1827 See the :file:`PCbuild9` directory for the build files.
1828 (Implemented by Christian Heimes.)
1829
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001830* Python now can only be compiled with C89 compilers (after 19
1831 years!). This means that the Python source tree can now drop its
1832 own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
1833 are in the C89 standard library.
1834
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001835* The BerkeleyDB module now has a C API object, available as
1836 ``bsddb.db.api``. This object can be used by other C extensions
1837 that wish to use the :mod:`bsddb` module for their own purposes.
1838 (Contributed by Duncan Grisby.)
1839
Georg Brandlb19be572007-12-29 10:57:00 +00001840 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001841
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001842* Several functions return information about the platform's
1843 floating-point support. :cfunc:`PyFloat_GetMax` returns
1844 the maximum representable floating point value,
1845 and :cfunc:`PyFloat_GetMin` returns the minimum
1846 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1847 containing more information from the :file:`float.h` file, such as
1848 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1849 (smallest difference between 1.0 and the next largest value
1850 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001851 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001852
Georg Brandlb19be572007-12-29 10:57:00 +00001853 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001854
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001855* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00001856 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001857 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001858 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001859
1860 .. Issue 1635
1861
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001862* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
1863 they are macros,
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001864 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001865 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001866 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
1867 The mixed-case macros are still available
1868 in Python 2.6 for backward compatibility.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001869
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001870 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001871
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001872* Distutils now places C extensions it builds in a
1873 different directory when running on a debug version of Python.
1874 (Contributed by Collin Winter.)
1875
1876 .. Patch 1530959
1877
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001878* Several basic data types, such as integers and strings, maintain
1879 internal free lists of objects that can be re-used. The data
1880 structures for these free lists now follow a naming convention: the
1881 variable is always named ``free_list``, the counter is always named
1882 ``numfree``, and a macro :cmacro:`Py<typename>_MAXFREELIST` is
1883 always defined.
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001884
Georg Brandlb19be572007-12-29 10:57:00 +00001885.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001886
1887
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001888Port-Specific Changes: Windows
1889-----------------------------------
1890
1891* The :mod:`msvcrt` module now supports
1892 both the normal and wide char variants of the console I/O
1893 API. The :func:`getwch` function reads a keypress and returns a Unicode
1894 value, as does the :func:`getwche` function. The :func:`putwch` function
1895 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001896 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001897
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001898* :func:`os.path.expandvars` will now expand environment variables
1899 in the form "%var%", and "~user" will be expanded into the
1900 user's home directory path. (Contributed by Josiah Carlson.)
1901
1902* The :mod:`socket` module's socket objects now have an
1903 :meth:`ioctl` method that provides a limited interface to the
1904 :cfunc:`WSAIoctl` system interface.
1905
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001906* The :mod:`_winreg` module now has a function,
1907 :func:`ExpandEnvironmentStrings`,
1908 that expands environment variable references such as ``%NAME%``
1909 in an input string. The handle objects provided by this
1910 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001911 in :keyword:`with` statements. (Contributed by Christian Heimes.)
1912
1913* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
1914 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
1915 were moved into the PC/ directory. The new PCbuild directory supports
1916 cross compilation for X64, debug builds and Profile Guided Optimization
1917 (PGO). PGO builds are roughly 10% faster than normal builds.
1918 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
1919 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001920
Georg Brandlb19be572007-12-29 10:57:00 +00001921.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001922
1923
1924.. _section-other:
1925
1926Other Changes and Fixes
1927=======================
1928
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001929As usual, there were a bunch of other improvements and bugfixes
1930scattered throughout the source tree. A search through the change
1931logs finds there were XXX patches applied and YYY bugs fixed between
1932Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001933
1934Some of the more notable changes are:
1935
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001936* It's now possible to prevent Python from writing any :file:`.pyc`
1937 or :file:`.pyo` files by either supplying the :option:`-B` switch
1938 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
1939 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00001940 are also used to set the :data:`sys.dont_write_bytecode` attribute;
1941 Python code can change this variable to control whether bytecode
1942 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001943 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001944
Georg Brandlb19be572007-12-29 10:57:00 +00001945.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001946
1947
1948Porting to Python 2.6
1949=====================
1950
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001951This section lists previously described changes, and a few
1952esoteric bugfixes, that may require changes to your
Georg Brandl8ec7f652007-08-15 14:28:01 +00001953code:
1954
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001955* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001956 now clears any existing contents of the deque
1957 before adding elements from the iterable. This change makes the
1958 behavior match that of ``list.__init__()``.
1959
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001960* The :class:`Decimal` constructor now accepts leading and trailing
1961 whitespace when passed a string. Previously it would raise an
1962 :exc:`InvalidOperation` exception. On the other hand, the
1963 :meth:`create_decimal` method of :class:`Context` objects now
1964 explicitly disallows extra whitespace, raising a
1965 :exc:`ConversionSyntax` exception.
1966
1967* Due to an implementation accident, if you passed a file path to
1968 the built-in :func:`__import__` function, it would actually import
1969 the specified file. This was never intended to work, however, and
1970 the implementation now explicitly checks for this case and raises
1971 an :exc:`ImportError`.
1972
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001973* The :mod:`socket` module exception :exc:`socket.error` now inherits
1974 from :exc:`IOError`. Previously it wasn't a subclass of
1975 :exc:`StandardError` but now it is, through :exc:`IOError`.
1976 (Implemented by Gregory P. Smith.)
1977
Georg Brandlb19be572007-12-29 10:57:00 +00001978 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00001979
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00001980* The :mod:`xmlrpclib` module no longer automatically converts
1981 :class:`datetime.date` and :class:`datetime.time` to the
1982 :class:`xmlrpclib.DateTime` type; the conversion semantics were
1983 not necessarily correct for all applications. Code using
1984 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
1985 instances.
1986
1987 .. Issue 1330538
1988
Andrew M. Kuchling9cf2f5d2008-03-20 22:49:26 +00001989* In 3.0-warning mode, inequality comparisons between two dictionaries
1990 or two objects that don't implement comparison methods are reported
1991 as warnings. ``dict1 == dict2`` still works, but ``dict1 < dict2``
1992 is being phased out.
1993
1994 Comparisons between cells, which are an implementation detail of Python's
1995 scoping rules, also cause warnings because such comparisons are forbidden
1996 entirely in 3.0.
1997
Georg Brandlb19be572007-12-29 10:57:00 +00001998.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001999
2000
2001.. _acks:
2002
2003Acknowledgements
2004================
2005
2006The author would like to thank the following people for offering suggestions,
2007corrections and assistance with various drafts of this article: .
2008