blob: 1ee812df9b80a283128eb68adf08d4b596e9482c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001****************************
2 What's New in Python 2.6
3****************************
4
Georg Brandlb19be572007-12-29 10:57:00 +00005.. XXX mention switch to Roundup for bug tracking
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00006.. XXX add trademark info for Apple, Microsoft.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00007
Georg Brandl8ec7f652007-08-15 14:28:01 +00008:Author: A.M. Kuchling
9:Release: |release|
10:Date: |today|
11
Georg Brandlb19be572007-12-29 10:57:00 +000012.. $Id: whatsnew26.tex 55746 2007-06-02 18:33:53Z neal.norwitz $
13 Rules for maintenance:
14
15 * Anyone can add text to this document. Do not spend very much time
16 on the wording of your changes, because your text will probably
17 get rewritten to some degree.
18
19 * The maintainer will go through Misc/NEWS periodically and add
20 changes; it's therefore more important to add your changes to
21 Misc/NEWS than to this file.
22
23 * This is not a complete list of every single change; completeness
24 is the purpose of Misc/NEWS. Some changes I consider too small
25 or esoteric to include. If such a change is added to the text,
26 I'll just remove it. (This is another reason you shouldn't spend
27 too much time on writing your addition.)
28
29 * If you want to draw your new text to the attention of the
30 maintainer, add 'XXX' to the beginning of the paragraph or
31 section.
32
33 * It's OK to just add a fragmentary note about a change. For
34 example: "XXX Describe the transmogrify() function added to the
35 socket module." The maintainer will research the change and
36 write the necessary text.
37
38 * You can comment out your additions if you like, but it's not
39 necessary (especially when a final release is some months away).
40
41 * Credit the author of a patch or bugfix. Just the name is
42 sufficient; the e-mail address isn't necessary.
43
44 * It's helpful to add the bug/patch number as a comment:
45
46 % Patch 12345
47 XXX Describe the transmogrify() function added to the socket
48 module.
49 (Contributed by P.Y. Developer.)
50
51 This saves the maintainer the effort of going through the SVN log
52 when researching a change.
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
54This article explains the new features in Python 2.6. No release date for
55Python 2.6 has been set; it will probably be released in mid 2008.
56
57This article doesn't attempt to provide a complete specification of the new
58features, but instead provides a convenient overview. For full details, you
59should refer to the documentation for Python 2.6. If you want to understand the
60complete implementation and design rationale, refer to the PEP for a particular
61new feature.
62
Georg Brandlb19be572007-12-29 10:57:00 +000063.. Compare with previous release in 2 - 3 sentences here.
64 add hyperlink when the documentation becomes available online.
Georg Brandl8ec7f652007-08-15 14:28:01 +000065
Georg Brandlb19be572007-12-29 10:57:00 +000066.. ========================================================================
67.. Large, PEP-level features and changes should be described here.
68.. Should there be a new section here for 3k migration?
69.. Or perhaps a more general section describing module changes/deprecation?
70.. ========================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +000071
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000072Python 3.0
73================
74
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +000075The development cycle for Python 2.6 also saw the release of the first
76alphas of Python 3.0, and the development of 3.0 has influenced
77a number of features in 2.6.
78
79Python 3.0 is a far-ranging redesign of Python that breaks
80compatibility with the 2.x series. This means that existing Python
81code will need a certain amount of conversion in order to run on
82Python 3.0. However, not all the changes in 3.0 necessarily break
83compatibility. In cases where new features won't cause existing code
84to break, they've been backported to 2.6 and are described in this
85document in the appropriate place. Some of the 3.0-derived features
86are:
87
88* A :meth:`__complex__` method for converting objects to a complex number.
89* Alternate syntax for catching exceptions: ``except TypeError as exc``.
90* The addition of :func:`functools.reduce` as a synonym for the built-in
91 :func:`reduce` function.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000092
93A new command-line switch, :option:`-3`, enables warnings
94about features that will be removed in Python 3.0. You can run code
95with this switch to see how much work will be necessary to port
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +000096code to 3.0. The value of this switch is available
97to Python code as the boolean variable ``sys.py3kwarning``,
98and to C extension code as :cdata:`Py_Py3kWarningFlag`.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +000099
100.. seealso::
101
102 The 3xxx series of PEPs, which describes the development process for
103 Python 3.0 and various features that have been accepted, rejected,
104 or are still under consideration.
105
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000106
107Development Changes
108==================================================
109
110While 2.6 was being developed, the Python development process
111underwent two significant changes: the developer group
112switched from SourceForge's issue tracker to a customized
113Roundup installation, and the documentation was converted from
114LaTeX to reStructured Text.
115
116
117New Issue Tracker: Roundup
118--------------------------------------------------
119
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000120XXX write this -- this section is currently just brief notes.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000121
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000122The developers were growing increasingly annoyed by SourceForge's
123bug tracker. (Discuss problems in a sentence or two.)
124
125Hosting provided by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000126
127New Documentation Format: ReStructured Text
128--------------------------------------------------
129
130Python's documentation had been written using LaTeX since the
131project's inception around 1989. At that time, most documentation was
132printed out for later study, not viewed online. LaTeX was widely used
133because it provided attractive printed output while
134remaining straightforward to write, once the basic rules
135of the markup have been learned.
136
137LaTeX is still used today for writing technical publications destined
138for printing, but the landscape for programming tools has shifted. We
139no longer print out reams of documentation; instead, we browse through
140it online and HTML is the most important format to support.
141Unfortunately, converting LaTeX to HTML is fairly complicated, and
142Fred L. Drake Jr., the Python documentation editor for many years,
143spent a lot of time wrestling the conversion process into shape.
144Occasionally people would suggest converting the documentation into
145SGML or, later, XML, but performing a good conversion is a major task
146and no one pursued the task to completion.
147
148During the 2.6 development cycle, Georg Brandl put a substantial
149effort into building a new toolchain called Sphinx
150for processing the documentation.
151The input format is reStructured Text,
152a markup commonly used in the Python community that supports
153custom extensions and directives. Sphinx concentrates
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000154on HTML output, producing attractively styled
155and modern HTML, but printed output is still supported through
156conversion to LaTeX as an output format.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000157
158.. seealso::
159
160 `Docutils <http://docutils.sf.net>`__: The fundamental
161 reStructured Text parser and toolset.
162
Georg Brandlb19be572007-12-29 10:57:00 +0000163 :ref:`documenting-index`: Describes how to write for
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000164 Python's documentation.
165
166
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000167PEP 343: The 'with' statement
168=============================
169
170The previous version, Python 2.5, added the ':keyword:`with`'
171statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000172import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000173be specially enabled; this means that :keyword:`with` is now always a
174keyword. The rest of this section is a copy of the corresponding
175section from "What's New in Python 2.5" document; if you read
176it back when Python 2.5 came out, you can skip the rest of this
177section.
178
179The ':keyword:`with`' statement clarifies code that previously would use
180``try...finally`` blocks to ensure that clean-up code is executed. In this
181section, I'll discuss the statement as it will commonly be used. In the next
182section, I'll examine the implementation details and show how to write objects
183for use with this statement.
184
185The ':keyword:`with`' statement is a new control-flow structure whose basic
186structure is::
187
188 with expression [as variable]:
189 with-block
190
191The expression is evaluated, and it should result in an object that supports the
192context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
193methods.
194
195The object's :meth:`__enter__` is called before *with-block* is executed and
196therefore can run set-up code. It also may return a value that is bound to the
197name *variable*, if given. (Note carefully that *variable* is *not* assigned
198the result of *expression*.)
199
200After execution of the *with-block* is finished, the object's :meth:`__exit__`
201method is called, even if the block raised an exception, and can therefore run
202clean-up code.
203
204Some standard Python objects now support the context management protocol and can
205be used with the ':keyword:`with`' statement. File objects are one example::
206
207 with open('/etc/passwd', 'r') as f:
208 for line in f:
209 print line
210 ... more processing code ...
211
212After this statement has executed, the file object in *f* will have been
213automatically closed, even if the :keyword:`for` loop raised an exception part-
214way through the block.
215
216.. note::
217
218 In this case, *f* is the same object created by :func:`open`, because
219 :meth:`file.__enter__` returns *self*.
220
221The :mod:`threading` module's locks and condition variables also support the
222':keyword:`with`' statement::
223
224 lock = threading.Lock()
225 with lock:
226 # Critical section of code
227 ...
228
229The lock is acquired before the block is executed and always released once the
230block is complete.
231
232The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
233to save and restore the current decimal context, which encapsulates the desired
234precision and rounding characteristics for computations::
235
236 from decimal import Decimal, Context, localcontext
237
238 # Displays with default precision of 28 digits
239 v = Decimal('578')
240 print v.sqrt()
241
242 with localcontext(Context(prec=16)):
243 # All code in this block uses a precision of 16 digits.
244 # The original context is restored on exiting the block.
245 print v.sqrt()
246
247
248.. _new-26-context-managers:
249
250Writing Context Managers
251------------------------
252
253Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
254people will only use ':keyword:`with`' in company with existing objects and
255don't need to know these details, so you can skip the rest of this section if
256you like. Authors of new objects will need to understand the details of the
257underlying implementation and should keep reading.
258
259A high-level explanation of the context management protocol is:
260
261* The expression is evaluated and should result in an object called a "context
262 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
263 methods.
264
265* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000266 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000267 discarded.
268
269* The code in *BLOCK* is executed.
270
271* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
272 is called with the exception details, the same values returned by
273 :func:`sys.exc_info`. The method's return value controls whether the exception
274 is re-raised: any false value re-raises the exception, and ``True`` will result
275 in suppressing it. You'll only rarely want to suppress the exception, because
276 if you do the author of the code containing the ':keyword:`with`' statement will
277 never realize anything went wrong.
278
279* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
280 called, but *type*, *value*, and *traceback* are all ``None``.
281
282Let's think through an example. I won't present detailed code but will only
283sketch the methods necessary for a database that supports transactions.
284
285(For people unfamiliar with database terminology: a set of changes to the
286database are grouped into a transaction. Transactions can be either committed,
287meaning that all the changes are written into the database, or rolled back,
288meaning that the changes are all discarded and the database is unchanged. See
289any database textbook for more information.)
290
291Let's assume there's an object representing a database connection. Our goal will
292be to let the user write code like this::
293
294 db_connection = DatabaseConnection()
295 with db_connection as cursor:
296 cursor.execute('insert into ...')
297 cursor.execute('delete from ...')
298 # ... more operations ...
299
300The transaction should be committed if the code in the block runs flawlessly or
301rolled back if there's an exception. Here's the basic interface for
302:class:`DatabaseConnection` that I'll assume::
303
304 class DatabaseConnection:
305 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000306 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000307 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000308 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000309 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000310 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000311 "Rolls back current transaction"
312
313The :meth:`__enter__` method is pretty easy, having only to start a new
314transaction. For this application the resulting cursor object would be a useful
315result, so the method will return it. The user can then add ``as cursor`` to
316their ':keyword:`with`' statement to bind the cursor to a variable name. ::
317
318 class DatabaseConnection:
319 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000320 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000321 # Code to start a new transaction
322 cursor = self.cursor()
323 return cursor
324
325The :meth:`__exit__` method is the most complicated because it's where most of
326the work has to be done. The method has to check if an exception occurred. If
327there was no exception, the transaction is committed. The transaction is rolled
328back if there was an exception.
329
330In the code below, execution will just fall off the end of the function,
331returning the default value of ``None``. ``None`` is false, so the exception
332will be re-raised automatically. If you wished, you could be more explicit and
333add a :keyword:`return` statement at the marked location. ::
334
335 class DatabaseConnection:
336 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000337 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000338 if tb is None:
339 # No exception, so commit
340 self.commit()
341 else:
342 # Exception occurred, so rollback.
343 self.rollback()
344 # return False
345
346
347.. _module-contextlib:
348
349The contextlib module
350---------------------
351
352The new :mod:`contextlib` module provides some functions and a decorator that
353are useful for writing objects for use with the ':keyword:`with`' statement.
354
355The decorator is called :func:`contextmanager`, and lets you write a single
356generator function instead of defining a new class. The generator should yield
357exactly one value. The code up to the :keyword:`yield` will be executed as the
358:meth:`__enter__` method, and the value yielded will be the method's return
359value that will get bound to the variable in the ':keyword:`with`' statement's
360:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
361executed in the :meth:`__exit__` method. Any exception raised in the block will
362be raised by the :keyword:`yield` statement.
363
364Our database example from the previous section could be written using this
365decorator as::
366
367 from contextlib import contextmanager
368
369 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000370 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000371 cursor = connection.cursor()
372 try:
373 yield cursor
374 except:
375 connection.rollback()
376 raise
377 else:
378 connection.commit()
379
380 db = DatabaseConnection()
381 with db_transaction(db) as cursor:
382 ...
383
384The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
385that combines a number of context managers so you don't need to write nested
386':keyword:`with`' statements. In this example, the single ':keyword:`with`'
387statement both starts a database transaction and acquires a thread lock::
388
389 lock = threading.Lock()
390 with nested (db_transaction(db), lock) as (cursor, locked):
391 ...
392
393Finally, the :func:`closing(object)` function returns *object* so that it can be
394bound to a variable, and calls ``object.close`` at the end of the block. ::
395
396 import urllib, sys
397 from contextlib import closing
398
399 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
400 for line in f:
401 sys.stdout.write(line)
402
403
404.. seealso::
405
406 :pep:`343` - The "with" statement
407 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
408 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
409 ':keyword:`with`' statement, which can be helpful in learning how the statement
410 works.
411
412 The documentation for the :mod:`contextlib` module.
413
Georg Brandlb19be572007-12-29 10:57:00 +0000414.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000415
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000416.. _pep-0366:
417
418PEP 366: Explicit Relative Imports From a Main Module
419============================================================
420
421Python's :option:`-m` switch allows running a module as a script.
422When you ran a module that was located inside a package, relative
423imports didn't work correctly.
424
425The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
426When present, relative imports will be relative to the value of this
427attribute instead of the :attr:`__name__` attribute. PEP 302-style
428importers can then set :attr:`__package__`. The :mod:`runpy` module
429that implements the :option:`-m` switch now does this, so relative imports
430can now be used in scripts running from inside a package.
431
Georg Brandlb19be572007-12-29 10:57:00 +0000432.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000433
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000434.. ::
435
436 .. _pep-0370:
437
438 PEP 370: XXX
439 =====================================================
440
441 When you run Python, the module search page ``sys.modules`` usually
442 includes a directory whose path ends in ``"site-packages"``. This
443 directory is intended to hold locally-installed packages available to
444 all users on a machine or using a particular site installation.
445
446 Python 2.6 introduces a convention for user-specific site directories.
447
448 .. seealso::
449
450 :pep:`370` - XXX
451
452 PEP written by XXX; implemented by Christian Heimes.
453
454
455.. ======================================================================
456
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000457.. _pep-3101:
458
459PEP 3101: Advanced String Formatting
460=====================================================
461
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000462XXX write this -- this section is currently just brief notes.
463
4648-bit and Unicode strings have a .format() method that takes the arguments
465to be formatted.
466
467.format() uses curly brackets ({, }) as special characters:
468
469 format("User ID: {0}", "root") -> "User ID: root"
470 format("Empty dict: {{}}") -> "Empty dict: {}"
471 0.name
472 0[name]
473
474Format specifiers:
475
476 0:8 -> left-align, pad
477 0:>8 -> right-align, pad
478
479Format data types::
480
481 ... take table from PEP 3101
482
483Classes and types can define a __format__ method to control how it's
484formatted. It receives a single argument, the format specifier::
485
486 def __format__(self, format_spec):
487 if isinstance(format_spec, unicode):
488 return unicode(str(self))
489 else:
490 return str(self)
491
492There's also a format() built-in that will format a single value. It calls
493the type's :meth:`__format__` method with the provided specifier::
494
495 >>> format(75.6564, '.2f')
496 '75.66'
497
498.. seealso::
499
500 :pep:`3101` - Advanced String Formatting
501 PEP written by Talin.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000502
503.. ======================================================================
504
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000505.. _pep-3110:
506
507PEP 3110: Exception-Handling Changes
508=====================================================
509
510One error that Python programmers occasionally make
511is the following::
512
513 try:
514 ...
515 except TypeError, ValueError:
516 ...
517
518The author is probably trying to catch both
519:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
520actually does something different: it will catch
521:exc:`TypeError` and bind the resulting exception object
522to the local name ``"ValueError"``. The correct code
523would have specified a tuple::
524
525 try:
526 ...
527 except (TypeError, ValueError):
528 ...
529
530This error is possible because the use of the comma here is ambiguous:
531does it indicate two different nodes in the parse tree, or a single
532node that's a tuple.
533
534Python 3.0 changes the syntax to make this unambiguous by replacing
535the comma with the word "as". To catch an exception and store the
536exception object in the variable ``exc``, you must write::
537
538 try:
539 ...
540 except TypeError as exc:
541 ...
542
543Python 3.0 will only support the use of "as", and therefore interprets
544the first example as catching two different exceptions. Python 2.6
545supports both the comma and "as", so existing code will continue to
546work.
547
548.. seealso::
549
550 :pep:`3110` - Catching Exceptions in Python 3000
551 PEP written and implemented by Collin Winter.
552
Georg Brandlb19be572007-12-29 10:57:00 +0000553.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000554
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000555.. _pep-3112:
556
557PEP 3112: Byte Literals
558=====================================================
559
560Python 3.0 adopts Unicode as the language's fundamental string type, and
561denotes 8-bit literals differently, either as ``b'string'``
562or using a :class:`bytes` constructor. For future compatibility,
563Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
564and it also supports the ``b''`` notation.
565
566.. seealso::
567
568 :pep:`3112` - Bytes literals in Python 3000
569 PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
570
571.. ======================================================================
572
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000573.. _pep-3119:
574
575PEP 3119: Abstract Base Classes
576=====================================================
577
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000578XXX write this -- this section is currently just brief notes.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000579
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000580How to identify a file object?
581
582ABCs are a collection of classes describing various interfaces.
583Classes can derive from an ABC to indicate they support that ABC's
584interface. Concrete classes should obey the semantics specified by
585an ABC, but Python can't check this; it's up to the implementor.
586
587A metaclass lets you declare that an existing class or type
588derives from a particular ABC. You can even
589
590class AppendableSequence:
591 __metaclass__ = ABCMeta
592
593AppendableSequence.register(list)
594assert issubclass(list, AppendableSequence)
595assert isinstance([], AppendableSequence)
596
597@abstractmethod decorator -- you can't instantiate classes w/
598an abstract method.
599
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000600::
601
602 @abstractproperty decorator
603 @abstractproperty
604 def readonly(self):
605 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000606
607
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000608.. seealso::
609
610 :pep:`3119` - Introducing Abstract Base Classes
611 PEP written by Guido van Rossum and Talin.
612 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000613 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000614
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000615.. ======================================================================
616
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000617.. _pep-3127:
618
619PEP 3127: Integer Literal Support and Syntax
620=====================================================
621
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000622XXX write this -- this section is currently just brief notes.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000623
624Python 3.0 changes the syntax for octal integer literals, and
625adds supports for binary integers: 0o instad of 0,
626and 0b for binary. Python 2.6 doesn't support this, but a bin()
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000627builtin was added.
628
629XXX changes to the hex/oct builtins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000630
631
632New bin() built-in returns the binary form of a number.
633
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000634.. seealso::
635
636 :pep:`3127` - Integer Literal Support and Syntax
637 PEP written by Patrick Maupin.
638
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000639.. ======================================================================
640
641.. _pep-3129:
642
643PEP 3129: Class Decorators
644=====================================================
645
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000646XXX write this -- this section is currently just brief notes.
647
648Class decorators are analogous to function decorators. After defining a class,
649it's passed through the specified series of decorator functions
650and the ultimate return value is recorded as the class.
651
652::
653
654 class A:
655 pass
656 A = foo(bar(A))
657
658
659 @foo
660 @bar
661 class A:
662 pass
663
664XXX need to find a good motivating example.
665
666.. seealso::
667
668 :pep:`3129` - Class Decorators
669 PEP written by Collin Winter.
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000670
671.. ======================================================================
672
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000673.. _pep-3141:
674
675PEP 3141: A Type Hierarchy for Numbers
676=====================================================
677
678In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000679inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000680This change was backported to 2.6 as the :mod:`numbers` module.
681
682The most general ABC is :class:`Number`. It defines no operations at
683all, and only exists to allow checking if an object is a number by
684doing ``isinstance(obj, Number)``.
685
686Numbers are further divided into :class:`Exact` and :class:`Inexact`.
687Exact numbers can represent values precisely and operations never
688round off the results or introduce tiny errors that may break the
Georg Brandl907a7202008-02-22 12:31:45 +0000689commutativity and associativity properties; inexact numbers may
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000690perform such rounding or introduce small errors. Integers, long
691integers, and rational numbers are exact, while floating-point
692and complex numbers are inexact.
693
694:class:`Complex` is a subclass of :class:`Number`. Complex numbers
695can undergo the basic operations of addition, subtraction,
696multiplication, division, and exponentiation, and you can retrieve the
697real and imaginary parts and obtain a number's conjugate. Python's built-in
698complex type is an implementation of :class:`Complex`.
699
700:class:`Real` further derives from :class:`Complex`, and adds
701operations that only work on real numbers: :func:`floor`, :func:`trunc`,
702rounding, taking the remainder mod N, floor division,
703and comparisons.
704
705:class:`Rational` numbers derive from :class:`Real`, have
706:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +0000707converted to floats. Python 2.6 adds a simple rational-number class,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000708:class:`Fraction`, in the :mod:`fractions` module. (It's called
709:class:`Fraction` instead of :class:`Rational` to avoid
710a name clash with :class:`numbers.Rational`.)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000711
712:class:`Integral` numbers derive from :class:`Rational`, and
713can be shifted left and right with ``<<`` and ``>>``,
714combined using bitwise operations such as ``&`` and ``|``,
715and can be used as array indexes and slice boundaries.
716
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000717In Python 3.0, the PEP slightly redefines the existing built-ins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000718:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
719one, :func:`math.trunc`, that's been backported to Python 2.6.
720:func:`math.trunc` rounds toward zero, returning the closest
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000721:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000722
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000723.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000724
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000725 :pep:`3141` - A Type Hierarchy for Numbers
726 PEP written by Jeffrey Yasskin.
727
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000728 XXX link: Discusses Scheme's numeric tower.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000729
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000730
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000731
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000732The :mod:`fractions` Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000733--------------------------------------------------
734
735To fill out the hierarchy of numeric types, a rational-number class
Mark Dickinsond058cd22008-02-10 21:29:51 +0000736has been added as the :mod:`fractions` module. Rational numbers are
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000737represented as a fraction, and can exactly represent
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000738numbers such as two-thirds that floating-point numbers can only
739approximate.
740
Mark Dickinsond058cd22008-02-10 21:29:51 +0000741The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000742that will be the numerator and denominator of the resulting fraction. ::
743
Mark Dickinsond058cd22008-02-10 21:29:51 +0000744 >>> from fractions import Fraction
745 >>> a = Fraction(2, 3)
746 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000747 >>> float(a), float(b)
748 (0.66666666666666663, 0.40000000000000002)
749 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000750 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000751 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000752 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000753
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000754To help in converting floating-point numbers to rationals,
755the float type now has a :meth:`as_integer_ratio()` method that returns
756the numerator and denominator for a fraction that evaluates to the same
757floating-point value::
758
759 >>> (2.5) .as_integer_ratio()
760 (5, 2)
761 >>> (3.1415) .as_integer_ratio()
762 (7074029114692207L, 2251799813685248L)
763 >>> (1./3) .as_integer_ratio()
764 (6004799503160661L, 18014398509481984L)
765
766Note that values that can only be approximated by floating-point
767numbers, such as 1./3, are not simplified to the number being
768approximated; the fraction attempts to match the floating-point value
769**exactly**.
770
Mark Dickinsond058cd22008-02-10 21:29:51 +0000771The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000772Mullender that was in Python's :file:`Demo/classes/` directory for a
773long time. This implementation was significantly updated by Jeffrey
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000774Yasskin.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000775
Georg Brandl8ec7f652007-08-15 14:28:01 +0000776Other Language Changes
777======================
778
779Here are all of the changes that Python 2.6 makes to the core Python language.
780
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000781* When calling a function using the ``**`` syntax to provide keyword
782 arguments, you are no longer required to use a Python dictionary;
783 any mapping will now work::
784
785 >>> def f(**kw):
786 ... print sorted(kw)
787 ...
788 >>> ud=UserDict.UserDict()
789 >>> ud['a'] = 1
790 >>> ud['b'] = 'string'
791 >>> f(**ud)
792 ['a', 'b']
793
Georg Brandlb19be572007-12-29 10:57:00 +0000794 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000795
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000796* The built-in types now have improved support for extended slicing syntax,
797 where various combinations of ``(start, stop, step)`` are supplied.
798 Previously, the support was partial and certain corner cases wouldn't work.
799 (Implemented by Thomas Wouters.)
800
Georg Brandlb19be572007-12-29 10:57:00 +0000801 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000802
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000803* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000804 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000805 adding or modifying a getter, setter or deleter function to an
806 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000807
808 class C(object):
809 @property
810 def x(self):
811 return self._x
812
813 @x.setter
814 def x(self, value):
815 self._x = value
816
817 @x.deleter
818 def x(self):
819 del self._x
820
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000821 class D(C):
822 @C.x.getter
823 def x(self):
824 return self._x * 2
825
826 @x.setter
827 def x(self, value):
828 self._x = value / 2
829
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000830
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000831* C functions and methods that use
832 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
833 have a :meth:`__complex__` method. In particular, the functions in the
834 :mod:`cmath` module will now accept objects with this method.
835 This is a backport of a Python 3.0 change.
836 (Contributed by Mark Dickinson.)
837
Georg Brandlb19be572007-12-29 10:57:00 +0000838 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000839
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000840 A numerical nicety: when creating a complex number from two floats
841 on systems that support signed zeros (-0 and +0), the
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000842 :func:`complex` constructor will now preserve the sign
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000843 of the zero.
844
Georg Brandlb19be572007-12-29 10:57:00 +0000845 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000846
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000847* More floating-point features were also added. The :func:`float` function
848 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000849 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000850 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +0000851 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000852
Georg Brandl225163d2008-03-05 07:10:35 +0000853 .. Patch 1635
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000854
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000855 Other functions in the :mod:`math` module, :func:`isinf` and
856 :func:`isnan`, return true if their floating-point argument is
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000857 infinite or Not A Number.
858
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000859 .. Patch 1640
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000860
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000861 The ``math.copysign(x, y)`` function
862 copies the sign bit of an IEEE 754 number, returning the absolute
863 value of *x* combined with the sign bit of *y*. For example,
864 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
865 Heimes.)
866
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000867* Changes to the :class:`Exception` interface
868 as dictated by :pep:`352` continue to be made. For 2.6,
869 the :attr:`message` attribute is being deprecated in favor of the
870 :attr:`args` attribute.
871
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000872* The :exc:`GeneratorExit` exception now subclasses
873 :exc:`BaseException` instead of :exc:`Exception`. This means
874 that an exception handler that does ``except Exception:``
875 will not inadvertently catch :exc:`GeneratorExit`.
876 (Contributed by Chad Austin.)
877
Georg Brandlb19be572007-12-29 10:57:00 +0000878 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000879
Andrew M. Kuchling3710a132008-03-05 00:44:41 +0000880* Generator objects now have a :attr:`gi_code` attribute that refers to
881 the original code object backing the generator.
882 (Contributed by Collin Winter.)
883
884 .. Patch #1473257
885
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000886* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000887 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000888
Georg Brandlb19be572007-12-29 10:57:00 +0000889 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000890
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000891* The :func:`complex` constructor now accepts strings containing
892 parenthesized complex numbers, letting ``complex(repr(cmplx))``
893 will now round-trip values. For example, ``complex('(3+4j)')``
894 now returns the value (3+4j).
895
Georg Brandlb19be572007-12-29 10:57:00 +0000896 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000897
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000898* The string :meth:`translate` method now accepts ``None`` as the
899 translation table parameter, which is treated as the identity
900 transformation. This makes it easier to carry out operations
901 that only delete characters. (Contributed by Bengt Richter.)
902
Georg Brandlb19be572007-12-29 10:57:00 +0000903 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000904
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000905* The built-in :func:`dir` function now checks for a :meth:`__dir__`
906 method on the objects it receives. This method must return a list
907 of strings containing the names of valid attributes for the object,
908 and lets the object control the value that :func:`dir` produces.
909 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +0000910 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000911
Georg Brandlb19be572007-12-29 10:57:00 +0000912 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000913
Georg Brandl8ec7f652007-08-15 14:28:01 +0000914* An obscure change: when you use the the :func:`locals` function inside a
915 :keyword:`class` statement, the resulting dictionary no longer returns free
916 variables. (Free variables, in this case, are variables referred to in the
917 :keyword:`class` statement that aren't attributes of the class.)
918
Georg Brandlb19be572007-12-29 10:57:00 +0000919.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000920
921
922Optimizations
923-------------
924
Georg Brandlaf30b282008-01-15 06:55:56 +0000925* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000926 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +0000927 for a particular class; once cached, the interpreter doesn't need to
928 traverse base classes to figure out the right method to call.
929 The cache is cleared if a base class or the class itself is modified,
930 so the cache should remain correct even in the face of Python's dynamic
931 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000932 (Original optimization implemented by Armin Rigo, updated for
933 Python 2.6 by Kevin Jacobs.)
934
Georg Brandl225163d2008-03-05 07:10:35 +0000935 .. Patch 1700288
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000936
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000937* All of the functions in the :mod:`struct` module have been rewritten in
938 C, thanks to work at the Need For Speed sprint.
939 (Contributed by Raymond Hettinger.)
940
Georg Brandl8ec7f652007-08-15 14:28:01 +0000941* Internally, a bit is now set in type objects to indicate some of the standard
942 built-in types. This speeds up checking if an object is a subclass of one of
943 these types. (Contributed by Neal Norwitz.)
944
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000945* Unicode strings now uses faster code for detecting
946 whitespace and line breaks; this speeds up the :meth:`split` method
947 by about 25% and :meth:`splitlines` by 35%.
948 (Contributed by Antoine Pitrou.)
949
950* To reduce memory usage, the garbage collector will now clear internal
951 free lists when garbage-collecting the highest generation of objects.
952 This may return memory to the OS sooner.
953
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
955benchmark around XX% faster than Python 2.5.
956
Georg Brandlb19be572007-12-29 10:57:00 +0000957.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000958
959
960New, Improved, and Deprecated Modules
961=====================================
962
963As usual, Python's standard library received a number of enhancements and bug
964fixes. Here's a partial list of the most notable changes, sorted alphabetically
965by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
966complete list of changes, or look through the CVS logs for all the details.
967
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000968* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
969 available, instead of restricting itself to protocol 1.
970 (Contributed by W. Barnes.)
971
Georg Brandlb19be572007-12-29 10:57:00 +0000972 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000973
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000974* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975 fieldnames)` is a factory function that creates subclasses of the standard tuple
976 whose fields are accessible by name as well as index. For example::
977
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000978 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000979 ... 'id name type size')
980 # Names are separated by spaces or commas.
981 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +0000982 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000983 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000984
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000985 >>> var = var_type(1, 'frequency', 'int', 4)
986 >>> print var[0], var.id # Equivalent
987 1 1
988 >>> print var[2], var.type # Equivalent
989 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +0000990 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000991 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +0000992 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000993 >>> v2
994 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000995
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000996 Where the new :class:`namedtuple` type proved suitable, the standard
997 library has been modified to return them. For example,
998 the :meth:`Decimal.as_tuple` method now returns a named tuple with
999 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1000
Georg Brandl8ec7f652007-08-15 14:28:01 +00001001 (Contributed by Raymond Hettinger.)
1002
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001003* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +00001004 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001005 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +00001006 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001007 old items to be discarded.
1008
1009 ::
1010
1011 >>> from collections import deque
1012 >>> dq=deque(maxlen=3)
1013 >>> dq
1014 deque([], maxlen=3)
1015 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
1016 >>> dq
1017 deque([1, 2, 3], maxlen=3)
1018 >>> dq.append(4)
1019 >>> dq
1020 deque([2, 3, 4], maxlen=3)
1021
1022 (Contributed by Raymond Hettinger.)
1023
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001024* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
1025 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
1026
Georg Brandlb19be572007-12-29 10:57:00 +00001027 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001028
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001029 The :mod:`ctypes` string, buffer and array types also have improved
1030 support for extended slicing syntax,
1031 where various combinations of ``(start, stop, step)`` are supplied.
1032 (Implemented by Thomas Wouters.)
1033
Georg Brandlb19be572007-12-29 10:57:00 +00001034 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001035
Georg Brandl8ec7f652007-08-15 14:28:01 +00001036* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001037 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001038 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001039 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
1041 # Boldface text starting at y=0,x=21
1042 # and affecting the rest of the line.
1043 stdscr.chgat(0,21, curses.A_BOLD)
1044
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +00001045 The :class:`Textbox` class in the :mod:`curses.textpad` module
1046 now supports editing in insert mode as well as overwrite mode.
1047 Insert mode is enabled by supplying a true value for the *insert_mode*
1048 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001049
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001050* The :mod:`decimal` module was updated to version 1.66 of
1051 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
1052 include some methods for some basic mathematical functions such as
1053 :meth:`exp` and :meth:`log10`::
1054
1055 >>> Decimal(1).exp()
1056 Decimal("2.718281828459045235360287471")
1057 >>> Decimal("2.7182818").ln()
1058 Decimal("0.9999999895305022877376682436")
1059 >>> Decimal(1000).log10()
1060 Decimal("3")
1061
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001062 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
1063 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
1064
1065 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
1066 support added by Raymond Hettinger.)
1067
1068* The :mod:`difflib` module's :class:`SequenceMatcher` class
1069 now returns named tuples representing matches.
1070 In addition to behaving like tuples, the returned values
1071 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
1072 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001073
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001074* An optional ``timeout`` parameter was added to the
1075 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
1076 method, specifying a timeout measured in seconds. (Added by Facundo
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001077 Batista.) Also, the :class:`FTP` class's
1078 :meth:`storbinary` and :meth:`storlines`
1079 now take an optional *callback* parameter that will be called with
1080 each block of data after the data has been sent.
1081 (Contributed by Phil Schwartz.)
1082
1083 .. Patch 1221598
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001084
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001085* The :func:`reduce` built-in function is also available in the
1086 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
1087 only available from :mod:`functools`; currently there are no plans
1088 to drop the built-in in the 2.x series. (Patched by
1089 Christian Heimes.)
1090
Georg Brandlb19be572007-12-29 10:57:00 +00001091 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001092
Georg Brandl8ec7f652007-08-15 14:28:01 +00001093* The :func:`glob.glob` function can now return Unicode filenames if
1094 a Unicode path was used and Unicode filenames are matched within the directory.
1095
Georg Brandlb19be572007-12-29 10:57:00 +00001096 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +00001097
1098* The :mod:`gopherlib` module has been removed.
1099
1100* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
1101 takes any number of iterables that return data *in sorted order*, and returns
1102 a new iterator that returns the contents of all the iterators, also in sorted
1103 order. For example::
1104
1105 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
1106 [1, 2, 3, 5, 8, 9, 16]
1107
1108 (Contributed by Raymond Hettinger.)
1109
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001110* An optional ``timeout`` parameter was added to the
1111 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
1112 class constructors, specifying a timeout measured in seconds.
1113 (Added by Facundo Batista.)
1114
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001115* Most of the :mod:`inspect` module's functions, such as
1116 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
1117 In addition to behaving like tuples, the elements of the return value
1118 can also be accessed as attributes.
1119 (Contributed by Raymond Hettinger.)
1120
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001121 Some new functions in the module include
1122 :func:`isgenerator`, :func:`isgeneratorfunction`,
1123 and :func:`isabstract`.
1124
1125* The :mod:`itertools` module gained several new functions.
1126
1127 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
1128 each of the elements; if some of the iterables are shorter than
1129 others, the missing values are set to *fillvalue*. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001130
1131 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
1132 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
1133
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001134 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
1135 of the supplied iterables, a set of tuples containing
1136 every possible combination of the elements returned from each iterable. ::
1137
1138 itertools.product([1,2,3], [4,5,6]) ->
1139 [(1, 4), (1, 5), (1, 6),
1140 (2, 4), (2, 5), (2, 6),
1141 (3, 4), (3, 5), (3, 6)]
1142
1143 The optional *repeat* keyword argument is used for taking the
1144 product of an iterable or a set of iterables with themselves,
1145 repeated *N* times. With a single iterable argument, *N*-tuples
1146 are returned::
1147
1148 itertools.product([1,2], repeat=3)) ->
1149 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
1150 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
1151
1152 With two iterables, *2N*-tuples are returned. ::
1153
1154 itertools(product([1,2], [3,4], repeat=2) ->
1155 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
1156 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
1157 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
1158 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
1159
1160 ``combinations(iter, r)`` returns combinations of length *r* from
1161 the elements of *iterable*. ::
1162
1163 itertools.combinations('123', 2) ->
1164 [('1', '2'), ('1', '3'), ('2', '3')]
1165
1166 itertools.combinations('123', 3) ->
1167 [('1', '2', '3')]
1168
1169 itertools.combinations('1234', 3) ->
1170 [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
1171 ('2', '3', '4')]
1172
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001173 ``permutations(iter[, r])`` returns all the permutations of length *r* from
1174 the iterable's elements. If *r* is not specified, it will default to the
1175 number of elements produced by the iterable.
1176
1177 XXX enter example once Raymond commits the code.
1178
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001179 ``itertools.chain(*iterables)` is an existing function in
1180 :mod:`itertools` that gained a new constructor.
1181 ``itertools.chain.from_iterable(iterable)`` takes a single
1182 iterable that should return other iterables. :func:`chain` will
1183 then return all the elements of the first iterable, then
1184 all the elements of the second, and so on. ::
1185
1186 chain.from_iterable([[1,2,3], [4,5,6]]) ->
1187 [1, 2, 3, 4, 5, 6]
1188
1189 (All contributed by Raymond Hettinger.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001190
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001191* The :mod:`logging` module's :class:`FileHandler` class
1192 and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
1193 and :class:`TimedRotatingFileHandler` now
1194 have an optional *delay* parameter to its constructor. If *delay*
1195 is true, opening of the log file is deferred until the first
1196 :meth:`emit` call is made. (Contributed by Vinay Sajip.)
1197
Georg Brandl8ec7f652007-08-15 14:28:01 +00001198* The :mod:`macfs` module has been removed. This in turn required the
1199 :func:`macostools.touched` function to be removed because it depended on the
1200 :mod:`macfs` module.
1201
Georg Brandlb19be572007-12-29 10:57:00 +00001202 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +00001203
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001204* :class:`mmap` objects now have a :meth:`rfind` method that finds
1205 a substring, beginning at the end of the string and searching
1206 backwards. The :meth:`find` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001207 also gained an *end* parameter containing the index at which to stop
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001208 the forward search.
1209 (Contributed by John Lenton.)
1210
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001211* The :mod:`new` module has been removed from Python 3.0.
1212 Importing it therefore
1213 triggers a warning message when Python is running in 3.0-warning
1214 mode.
1215
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001216* The :mod:`operator` module gained a
1217 :func:`methodcaller` function that takes a name and an optional
1218 set of arguments, returning a callable that will call
1219 the named function on any arguments passed to it. For example::
1220
1221 >>> # Equivalent to lambda s: s.replace('old', 'new')
1222 >>> replacer = operator.methodcaller('replace', 'old', 'new')
1223 >>> replacer('old wine in old bottles')
1224 'new wine in new bottles'
1225
Georg Brandl27504da2008-03-04 07:25:54 +00001226 (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001227
1228 The :func:`attrgetter` function now accepts dotted names and performs
1229 the corresponding attribute lookups::
1230
1231 >>> inst_name = operator.attrgetter('__class__.__name__')
1232 >>> inst_name('')
1233 'str'
1234 >>> inst_name(help)
1235 '_Helper'
1236
Georg Brandl27504da2008-03-04 07:25:54 +00001237 (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001238
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001239* New functions in the :mod:`os` module include
1240 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
1241 and ``lchmod(path, mode)``, on operating systems that support these
1242 functions. :func:`fchmod` and :func:`fchown` let you change the mode
1243 and ownership of an opened file, and :func:`lchmod` changes the mode
1244 of a symlink.
1245
1246 (Contributed by Georg Brandl and Christian Heimes.)
1247
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001248* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001249 set to True, it will follow symlinks pointing to directories and
1250 visit the directory's contents. For backward compatibility, the
1251 parameter's default value is false. Note that the function can fall
1252 into an infinite recursion if there's a symlink that points to a
1253 parent directory.
1254
Georg Brandlb19be572007-12-29 10:57:00 +00001255 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001256
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001257* The ``os.environ`` object's :meth:`clear` method will now unset the
1258 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001259 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001260
Georg Brandlb19be572007-12-29 10:57:00 +00001261 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001262
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001263* In the :mod:`os.path` module, the :func:`splitext` function
1264 has been changed to not split on leading period characters.
1265 This produces better results when operating on Unix's dot-files.
1266 For example, ``os.path.splitext('.ipython')``
1267 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
1268
Georg Brandlb19be572007-12-29 10:57:00 +00001269 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001270
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001271 A new function, :func:`relpath(path, start)` returns a relative path
1272 from the ``start`` path, if it's supplied, or from the current
1273 working directory to the destination ``path``. (Contributed by
1274 Richard Barran.)
1275
Georg Brandlb19be572007-12-29 10:57:00 +00001276 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001277
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001278 On Windows, :func:`os.path.expandvars` will now expand environment variables
1279 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001280 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001281
Georg Brandlb19be572007-12-29 10:57:00 +00001282 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001283
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001284* The Python debugger provided by the :mod:`pdb` module
1285 gained a new command: "run" restarts the Python program being debugged,
1286 and can optionally take new command-line arguments for the program.
1287 (Contributed by Rocky Bernstein.)
1288
Georg Brandlb19be572007-12-29 10:57:00 +00001289 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001290
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001291* The :mod:`pickletools` module now has an :func:`optimize` function
1292 that takes a string containing a pickle and removes some unused
1293 opcodes, returning a shorter pickle that contains the same data structure.
1294 (Contributed by Raymond Hettinger.)
1295
Georg Brandl8ec7f652007-08-15 14:28:01 +00001296* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
1297 are wrappers for the corresponding system calls (where they're available).
1298 Constants for the flag values are defined in the :mod:`stat` module; some
1299 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
1300 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
1301 file. (Contributed by M. Levinson.)
1302
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001303 ``os.closerange(*low*, *high*)`` efficiently closes all file descriptors
1304 from *low* to *high*, ignoring any errors and not including *high* itself.
1305 This function is now used by the :mod:`subprocess` module to make starting
1306 processes faster. (Contributed by Georg Brandl.)
1307
1308 .. Patch #1663329
1309
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00001310* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
1311 their :attr:`buffer_size` attribute to change the size of the buffer
1312 used to hold character data.
1313 (Contributed by Achim Gaedke.)
1314
1315 .. Patch 1137
1316
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001317* The :mod:`Queue` module now provides queue classes that retrieve entries
1318 in different orders. The :class:`PriorityQueue` class stores
1319 queued items in a heap and retrieves them in priority order,
1320 and :class:`LifoQueue` retrieves the most recently added entries first,
1321 meaning that it behaves like a stack.
1322 (Contributed by Raymond Hettinger.)
1323
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001324* The :mod:`random` module's :class:`Random` objects can
1325 now be pickled on a 32-bit system and unpickled on a 64-bit
1326 system, and vice versa. Unfortunately, this change also means
1327 that Python 2.6's :class:`Random` objects can't be unpickled correctly
1328 on earlier versions of Python.
1329 (Contributed by Shawn Ligocki.)
1330
Georg Brandlb19be572007-12-29 10:57:00 +00001331 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001332
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001333* Long regular expression searches carried out by the :mod:`re`
1334 module will now check for signals being delivered, so especially
1335 long searches can now be interrupted.
1336 (Contributed by Josh Hoyt and Ralf Schmitt.)
1337
Georg Brandl225163d2008-03-05 07:10:35 +00001338 .. Patch 846388
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001339
Georg Brandl8ec7f652007-08-15 14:28:01 +00001340* The :mod:`rgbimg` module has been removed.
1341
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001342* The :mod:`sched` module's :class:`scheduler` instances now
1343 have a read-only :attr:`queue` attribute that returns the
1344 contents of the scheduler's queue, represented as a list of
Georg Brandl225163d2008-03-05 07:10:35 +00001345 named tuples with the fields ``(time, priority, action, argument)``.
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001346 (Contributed by Raymond Hettinger XXX check.)
Georg Brandl225163d2008-03-05 07:10:35 +00001347
1348 .. Patch 1861
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001349
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001350* The :mod:`sets` module has been deprecated; it's better to
1351 use the built-in :class:`set` and :class:`frozenset` types.
1352
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001353* Integrating signal handling with GUI handling event loops
1354 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001355 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001356 The :mod:`signal` module can now make this more efficient.
1357 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
1358 to be used; when a signal is received, a byte is written to that
1359 file descriptor. There's also a C-level function,
1360 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
1361
1362 Event loops will use this by opening a pipe to create two descriptors,
1363 one for reading and one for writing. The writeable descriptor
1364 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
1365 will be added to the list of descriptors monitored by the event loop via
1366 :cfunc:`select` or :cfunc:`poll`.
1367 On receiving a signal, a byte will be written and the main event loop
1368 will be woken up, without the need to poll.
1369
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001370 (Contributed by Adam Olsen.)
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001371
Georg Brandl225163d2008-03-05 07:10:35 +00001372 .. Patch 1583
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001373
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001374 The :func:`siginterrupt` function is now available from Python code,
1375 and allows changing whether signals can interrupt system calls or not.
1376 (Contributed by Ralf Schmitt.)
1377
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001378* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
1379 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001380 interface identical to the existing :class:`SMTP` class. Both
1381 class constructors also have an optional ``timeout`` parameter
1382 that specifies a timeout for the initial connection attempt, measured in
1383 seconds.
1384
1385 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001386 the module. LMTP is used in place of SMTP when transferring e-mail
1387 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001388
1389 (SMTP over SSL contributed by Monty Taylor; timeout parameter
1390 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001391 Hedstrom.)
1392
Georg Brandlb19be572007-12-29 10:57:00 +00001393 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +00001394
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001395* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
1396 and forgets any knowledge obtained from the server not obtained from
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001397 the TLS negotiation itself. (Patch contributed by Bill Fenner.)
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001398
1399 .. Issue 829951
1400
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001401* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1402 a high-performance non-IP-based protocol designed for use in clustered
1403 environments. TIPC addresses are 4- or 5-tuples.
1404 (Contributed by Alberto Bertogli.)
1405
1406 .. Patch #1646
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00001407
1408* The base classes in the :mod:`SocketServer` module now support
1409 calling a :meth:`handle_timeout` method after a span of inactivity
1410 specified by the server's :attr:`timeout` attribute. (Contributed
1411 by Michael Pomraning.)
1412
1413 .. Patch #742598
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001414
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001415* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001416 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001417 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001418 derived from the :file:`float.h` file. Attributes of this object
1419 include
1420 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001421 (smallest difference between 1.0 and the next largest value
1422 representable), and several others. (Contributed by Christian Heimes.)
1423
Georg Brandlb19be572007-12-29 10:57:00 +00001424 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001425
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00001426 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
1427 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1428 If this variable is true, the compiled files are not written. The
1429 variable is initially set on start-up by supplying the :option:`-B`
1430 switch to the Python interpreter, or by setting the
1431 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
1432 running the interpreter. Python code can subsequently
1433 change the value of this variable to control whether bytecode files
1434 are written or not.
1435 (Contributed by Neal Norwitz and Georg Brandl.)
1436
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001437 Information about the command-line arguments supplied to the Python
1438 interpreter are available as attributes of a ``sys.flags`` named
1439 tuple. For example, the :attr:`verbose` attribute is true if Python
1440 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1441 These attributes are all read-only.
1442 (Contributed by Christian Heimes.)
1443
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001444 It's now possible to determine the current profiler and tracer functions
1445 by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
1446 (Contributed by Georg Brandl.)
1447
1448 .. Patch #1648
1449
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001450* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1451 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1452 format that was already supported. The default format
1453 is GNU tar; specify the ``format`` parameter to open a file
1454 using a different format::
1455
1456 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1457
1458 The new ``errors`` parameter lets you specify an error handling
1459 scheme for character conversions: the three standard ways Python can
1460 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1461 special value ``'utf-8'``, which replaces bad characters with their
1462 UTF-8 representation. Character conversions occur because the PAX
1463 format supports Unicode filenames, defaulting to UTF-8 encoding.
1464
1465 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1466 a function that can be used to exclude certain filenames from
1467 an archive.
1468 The function must take a filename and return true if the file
1469 should be excluded or false if it should be archived.
1470 The function is applied to both the name initially passed to :meth:`add`
1471 and to the names of files in recursively-added directories.
1472
1473 (All changes contributed by Lars Gustäbel).
1474
1475* An optional ``timeout`` parameter was added to the
1476 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1477 measured in seconds. (Added by Facundo Batista.)
1478
1479* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1480 the temporary file it created when the file is closed. This
1481 behaviour can now be changed by passing ``delete=False`` to the
1482 constructor. (Contributed by Damien Miller.)
1483
Georg Brandlb19be572007-12-29 10:57:00 +00001484 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001485
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001486 A new class, :class:`SpooledTemporaryFile`, behaves like
1487 a temporary file but stores its data in memory until a maximum size is
1488 exceeded. On reaching that limit, the contents will be written to
1489 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
1490
1491 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
1492 both work as context managers, so you can write
1493 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
1494 (Contributed by Alexander Belopolsky.)
1495
1496 .. Issue #2021
1497
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001498* The :mod:`test.test_support` module now contains a
1499 :func:`EnvironmentVarGuard`
1500 context manager that supports temporarily changing environment variables and
1501 automatically restores them to their old values.
1502
1503 Another context manager, :class:`TransientResource`, can surround calls
1504 to resources that may or may not be available; it will catch and
1505 ignore a specified list of exceptions. For example,
1506 a network test may ignore certain failures when connecting to an
1507 external web site::
1508
1509 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
1510 f = urllib.urlopen('https://sf.net')
1511 ...
1512
1513 (Contributed by Brett Cannon.)
1514
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001515* The :mod:`textwrap` module can now preserve existing whitespace
1516 at the beginnings and ends of the newly-created lines
1517 by specifying ``drop_whitespace=False``
1518 as an argument::
1519
1520 >>> S = """This sentence has a bunch of extra whitespace."""
1521 >>> print textwrap.fill(S, width=15)
1522 This sentence
1523 has a bunch
1524 of extra
1525 whitespace.
1526 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
1527 This sentence
1528 has a bunch
1529 of extra
1530 whitespace.
1531 >>>
1532
Georg Brandl27504da2008-03-04 07:25:54 +00001533 (Contributed by Dwayne Bailey.)
1534
Georg Brandlb19be572007-12-29 10:57:00 +00001535 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001536
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001537* The :mod:`timeit` module now accepts callables as well as strings
1538 for the statement being timed and for the setup code.
1539 Two convenience functions were added for creating
1540 :class:`Timer` instances:
1541 ``repeat(stmt, setup, time, repeat, number)`` and
1542 ``timeit(stmt, setup, time, number)`` create an instance and call
1543 the corresponding method. (Contributed by Erik Demaine.)
1544
Georg Brandlb19be572007-12-29 10:57:00 +00001545 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001546
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001547* An optional ``timeout`` parameter was added to the
1548 :func:`urllib.urlopen` function and the
1549 :class:`urllib.ftpwrapper` class constructor, as well as the
1550 :func:`urllib2.urlopen` function. The parameter specifies a timeout
1551 measured in seconds. For example::
1552
1553 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
1554 Traceback (most recent call last):
1555 ...
1556 urllib2.URLError: <urlopen error timed out>
1557 >>>
1558
1559 (Added by Facundo Batista.)
1560
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001561* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001562 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001563 their socket by passing True as the ``bind_and_activate``
1564 constructor parameter. This can be used to modify the instance's
1565 :attr:`allow_reuse_address` attribute before calling the
1566 :meth:`server_bind` and :meth:`server_activate` methods to
1567 open the socket and begin listening for connections.
1568 (Contributed by Peter Parente.)
1569
Georg Brandlb19be572007-12-29 10:57:00 +00001570 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001571
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001572 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
1573 attribute; if true, the exception and formatted traceback are returned
1574 as HTTP headers "X-Exception" and "X-Traceback". This feature is
1575 for debugging purposes only and should not be used on production servers
1576 because the tracebacks could possibly reveal passwords or other sensitive
1577 information. (Contributed by Alan McIntyre as part of his
1578 project for Google's Summer of Code 2007.)
1579
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001580* The :mod:`zipfile` module's :class:`ZipFile` class now has
1581 :meth:`extract` and :meth:`extractall` methods that will unpack
1582 a single file or all the files in the archive to the current directory, or
1583 to a specified directory::
1584
1585 z = zipfile.ZipFile('python-251.zip')
1586
1587 # Unpack a single file, writing it relative to the /tmp directory.
1588 z.extract('Python/sysmodule.c', '/tmp')
1589
1590 # Unpack all the files in the archive.
1591 z.extractall()
1592
1593 (Contributed by Alan McIntyre.)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001594
1595 .. Patch 467924
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001596
Georg Brandlb19be572007-12-29 10:57:00 +00001597.. ======================================================================
1598.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001599
1600Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00001601--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001602
1603Bill Janssen made extensive improvements to Python 2.6's support for
1604SSL.
1605
1606XXX use ssl.sslsocket - subclass of socket.socket.
1607
1608XXX Can specify if certificate is required, and obtain certificate info
1609by calling getpeercert method.
1610
1611XXX sslwrap() behaves like socket.ssl
1612
1613XXX Certain features require the OpenSSL package to be installed, notably
1614 the 'openssl' binary.
1615
1616.. seealso::
1617
1618 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001619
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001620
1621.. ======================================================================
1622
1623plistlib: A Property-List Parser
1624--------------------------------------------------
1625
1626A commonly-used format on MacOS X is the ``.plist`` format,
1627which stores basic data types (numbers, strings, lists,
1628and dictionaries) and serializes them into an XML-based format.
1629(It's a lot like the XML-RPC serialization of data types.)
1630
1631Despite being primarily used on MacOS X, the format
1632has nothing Mac-specific about it and the Python implementation works
1633on any platform that Python supports, so the :mod:`plistlib` module
1634has been promoted to the standard library.
1635
1636Using the module is simple::
1637
1638 import sys
1639 import plistlib
1640 import datetime
1641
1642 # Create data structure
1643 data_struct = dict(lastAccessed=datetime.datetime.now(),
1644 version=1,
1645 categories=('Personal', 'Shared', 'Private'))
1646
1647 # Create string containing XML.
1648 plist_str = plistlib.writePlistToString(data_struct)
1649 new_struct = plistlib.readPlistFromString(plist_str)
1650 print data_struct
1651 print new_struct
1652
1653 # Write data structure to a file and read it back.
1654 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
1655 new_struct = plistlib.readPlist('/tmp/customizations.plist')
1656
1657 # read/writePlist accepts file-like objects as well as paths.
1658 plistlib.writePlist(data_struct, sys.stdout)
1659
1660
Georg Brandlb19be572007-12-29 10:57:00 +00001661.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001662
1663
1664Build and C API Changes
1665=======================
1666
1667Changes to Python's build process and to the C API include:
1668
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001669* Python 2.6 can be built with Microsoft Visual Studio 2008.
1670 See the :file:`PCbuild9` directory for the build files.
1671 (Implemented by Christian Heimes.)
1672
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001673* The BerkeleyDB module now has a C API object, available as
1674 ``bsddb.db.api``. This object can be used by other C extensions
1675 that wish to use the :mod:`bsddb` module for their own purposes.
1676 (Contributed by Duncan Grisby.)
1677
Georg Brandlb19be572007-12-29 10:57:00 +00001678 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001679
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001680* Several functions return information about the platform's
1681 floating-point support. :cfunc:`PyFloat_GetMax` returns
1682 the maximum representable floating point value,
1683 and :cfunc:`PyFloat_GetMin` returns the minimum
1684 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1685 containing more information from the :file:`float.h` file, such as
1686 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1687 (smallest difference between 1.0 and the next largest value
1688 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001689 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001690
Georg Brandlb19be572007-12-29 10:57:00 +00001691 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001692
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001693* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00001694 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001695 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001696 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001697
1698 .. Issue 1635
1699
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001700* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
1701 they are macros,
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001702 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001703 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
Andrew M. Kuchling3710a132008-03-05 00:44:41 +00001704 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
1705 The mixed-case macros are still available
1706 in Python 2.6 for backward compatibility.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001707
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001708 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001709
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001710* Distutils now places C extensions it builds in a
1711 different directory when running on a debug version of Python.
1712 (Contributed by Collin Winter.)
1713
1714 .. Patch 1530959
1715
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001716* Several basic data types, such as integers and strings, maintain
1717 internal free lists of objects that can be re-used. The data
1718 structures for these free lists now follow a naming convention: the
1719 variable is always named ``free_list``, the counter is always named
1720 ``numfree``, and a macro :cmacro:`Py<typename>_MAXFREELIST` is
1721 always defined.
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001722
Georg Brandlb19be572007-12-29 10:57:00 +00001723.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001724
1725
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001726Port-Specific Changes: Windows
1727-----------------------------------
1728
1729* The :mod:`msvcrt` module now supports
1730 both the normal and wide char variants of the console I/O
1731 API. The :func:`getwch` function reads a keypress and returns a Unicode
1732 value, as does the :func:`getwche` function. The :func:`putwch` function
1733 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001734 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001735
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001736* :func:`os.path.expandvars` will now expand environment variables
1737 in the form "%var%", and "~user" will be expanded into the
1738 user's home directory path. (Contributed by Josiah Carlson.)
1739
1740* The :mod:`socket` module's socket objects now have an
1741 :meth:`ioctl` method that provides a limited interface to the
1742 :cfunc:`WSAIoctl` system interface.
1743
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001744* The :mod:`_winreg` module now has a function,
1745 :func:`ExpandEnvironmentStrings`,
1746 that expands environment variable references such as ``%NAME%``
1747 in an input string. The handle objects provided by this
1748 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001749 in :keyword:`with` statements. (Contributed by Christian Heimes.)
1750
1751* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
1752 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
1753 were moved into the PC/ directory. The new PCbuild directory supports
1754 cross compilation for X64, debug builds and Profile Guided Optimization
1755 (PGO). PGO builds are roughly 10% faster than normal builds.
1756 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
1757 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001758
Georg Brandlb19be572007-12-29 10:57:00 +00001759.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001760
1761
1762.. _section-other:
1763
1764Other Changes and Fixes
1765=======================
1766
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001767As usual, there were a bunch of other improvements and bugfixes
1768scattered throughout the source tree. A search through the change
1769logs finds there were XXX patches applied and YYY bugs fixed between
1770Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001771
1772Some of the more notable changes are:
1773
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001774* It's now possible to prevent Python from writing any :file:`.pyc`
1775 or :file:`.pyo` files by either supplying the :option:`-B` switch
1776 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
1777 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00001778 are also used to set the :data:`sys.dont_write_bytecode` attribute;
1779 Python code can change this variable to control whether bytecode
1780 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001781 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001782
Georg Brandlb19be572007-12-29 10:57:00 +00001783.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001784
1785
1786Porting to Python 2.6
1787=====================
1788
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001789This section lists previously described changes, and a few
1790esoteric bugfixes, that may require changes to your
Georg Brandl8ec7f652007-08-15 14:28:01 +00001791code:
1792
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001793* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001794 now clears any existing contents of the deque
1795 before adding elements from the iterable. This change makes the
1796 behavior match that of ``list.__init__()``.
1797
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001798* The :class:`Decimal` constructor now accepts leading and trailing
1799 whitespace when passed a string. Previously it would raise an
1800 :exc:`InvalidOperation` exception. On the other hand, the
1801 :meth:`create_decimal` method of :class:`Context` objects now
1802 explicitly disallows extra whitespace, raising a
1803 :exc:`ConversionSyntax` exception.
1804
1805* Due to an implementation accident, if you passed a file path to
1806 the built-in :func:`__import__` function, it would actually import
1807 the specified file. This was never intended to work, however, and
1808 the implementation now explicitly checks for this case and raises
1809 an :exc:`ImportError`.
1810
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001811* The :mod:`socket` module exception :exc:`socket.error` now inherits
1812 from :exc:`IOError`. Previously it wasn't a subclass of
1813 :exc:`StandardError` but now it is, through :exc:`IOError`.
1814 (Implemented by Gregory P. Smith.)
1815
Georg Brandlb19be572007-12-29 10:57:00 +00001816 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00001817
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00001818* The :mod:`xmlrpclib` module no longer automatically converts
1819 :class:`datetime.date` and :class:`datetime.time` to the
1820 :class:`xmlrpclib.DateTime` type; the conversion semantics were
1821 not necessarily correct for all applications. Code using
1822 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
1823 instances.
1824
1825 .. Issue 1330538
1826
Georg Brandlb19be572007-12-29 10:57:00 +00001827.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001828
1829
1830.. _acks:
1831
1832Acknowledgements
1833================
1834
1835The author would like to thank the following people for offering suggestions,
1836corrections and assistance with various drafts of this article: .
1837