blob: b45b7be1be8fc3b6074850fe8e3dbcd96083ee39 [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
120XXX write this.
121
122
123New Documentation Format: ReStructured Text
124--------------------------------------------------
125
126Python's documentation had been written using LaTeX since the
127project's inception around 1989. At that time, most documentation was
128printed out for later study, not viewed online. LaTeX was widely used
129because it provided attractive printed output while
130remaining straightforward to write, once the basic rules
131of the markup have been learned.
132
133LaTeX is still used today for writing technical publications destined
134for printing, but the landscape for programming tools has shifted. We
135no longer print out reams of documentation; instead, we browse through
136it online and HTML is the most important format to support.
137Unfortunately, converting LaTeX to HTML is fairly complicated, and
138Fred L. Drake Jr., the Python documentation editor for many years,
139spent a lot of time wrestling the conversion process into shape.
140Occasionally people would suggest converting the documentation into
141SGML or, later, XML, but performing a good conversion is a major task
142and no one pursued the task to completion.
143
144During the 2.6 development cycle, Georg Brandl put a substantial
145effort into building a new toolchain called Sphinx
146for processing the documentation.
147The input format is reStructured Text,
148a markup commonly used in the Python community that supports
149custom extensions and directives. Sphinx concentrates
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +0000150on HTML output, producing attractively styled
151and modern HTML, but printed output is still supported through
152conversion to LaTeX as an output format.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000153
154.. seealso::
155
156 `Docutils <http://docutils.sf.net>`__: The fundamental
157 reStructured Text parser and toolset.
158
Georg Brandlb19be572007-12-29 10:57:00 +0000159 :ref:`documenting-index`: Describes how to write for
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000160 Python's documentation.
161
162
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000163PEP 343: The 'with' statement
164=============================
165
166The previous version, Python 2.5, added the ':keyword:`with`'
167statement an optional feature, to be enabled by a ``from __future__
Andrew M. Kuchling6e751f42007-12-03 21:28:41 +0000168import with_statement`` directive. In 2.6 the statement no longer needs to
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000169be specially enabled; this means that :keyword:`with` is now always a
170keyword. The rest of this section is a copy of the corresponding
171section from "What's New in Python 2.5" document; if you read
172it back when Python 2.5 came out, you can skip the rest of this
173section.
174
175The ':keyword:`with`' statement clarifies code that previously would use
176``try...finally`` blocks to ensure that clean-up code is executed. In this
177section, I'll discuss the statement as it will commonly be used. In the next
178section, I'll examine the implementation details and show how to write objects
179for use with this statement.
180
181The ':keyword:`with`' statement is a new control-flow structure whose basic
182structure is::
183
184 with expression [as variable]:
185 with-block
186
187The expression is evaluated, and it should result in an object that supports the
188context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
189methods.
190
191The object's :meth:`__enter__` is called before *with-block* is executed and
192therefore can run set-up code. It also may return a value that is bound to the
193name *variable*, if given. (Note carefully that *variable* is *not* assigned
194the result of *expression*.)
195
196After execution of the *with-block* is finished, the object's :meth:`__exit__`
197method is called, even if the block raised an exception, and can therefore run
198clean-up code.
199
200Some standard Python objects now support the context management protocol and can
201be used with the ':keyword:`with`' statement. File objects are one example::
202
203 with open('/etc/passwd', 'r') as f:
204 for line in f:
205 print line
206 ... more processing code ...
207
208After this statement has executed, the file object in *f* will have been
209automatically closed, even if the :keyword:`for` loop raised an exception part-
210way through the block.
211
212.. note::
213
214 In this case, *f* is the same object created by :func:`open`, because
215 :meth:`file.__enter__` returns *self*.
216
217The :mod:`threading` module's locks and condition variables also support the
218':keyword:`with`' statement::
219
220 lock = threading.Lock()
221 with lock:
222 # Critical section of code
223 ...
224
225The lock is acquired before the block is executed and always released once the
226block is complete.
227
228The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
229to save and restore the current decimal context, which encapsulates the desired
230precision and rounding characteristics for computations::
231
232 from decimal import Decimal, Context, localcontext
233
234 # Displays with default precision of 28 digits
235 v = Decimal('578')
236 print v.sqrt()
237
238 with localcontext(Context(prec=16)):
239 # All code in this block uses a precision of 16 digits.
240 # The original context is restored on exiting the block.
241 print v.sqrt()
242
243
244.. _new-26-context-managers:
245
246Writing Context Managers
247------------------------
248
249Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
250people will only use ':keyword:`with`' in company with existing objects and
251don't need to know these details, so you can skip the rest of this section if
252you like. Authors of new objects will need to understand the details of the
253underlying implementation and should keep reading.
254
255A high-level explanation of the context management protocol is:
256
257* The expression is evaluated and should result in an object called a "context
258 manager". The context manager must have :meth:`__enter__` and :meth:`__exit__`
259 methods.
260
261* The context manager's :meth:`__enter__` method is called. The value returned
Georg Brandld41b8dc2007-12-16 23:15:07 +0000262 is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000263 discarded.
264
265* The code in *BLOCK* is executed.
266
267* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)`
268 is called with the exception details, the same values returned by
269 :func:`sys.exc_info`. The method's return value controls whether the exception
270 is re-raised: any false value re-raises the exception, and ``True`` will result
271 in suppressing it. You'll only rarely want to suppress the exception, because
272 if you do the author of the code containing the ':keyword:`with`' statement will
273 never realize anything went wrong.
274
275* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still
276 called, but *type*, *value*, and *traceback* are all ``None``.
277
278Let's think through an example. I won't present detailed code but will only
279sketch the methods necessary for a database that supports transactions.
280
281(For people unfamiliar with database terminology: a set of changes to the
282database are grouped into a transaction. Transactions can be either committed,
283meaning that all the changes are written into the database, or rolled back,
284meaning that the changes are all discarded and the database is unchanged. See
285any database textbook for more information.)
286
287Let's assume there's an object representing a database connection. Our goal will
288be to let the user write code like this::
289
290 db_connection = DatabaseConnection()
291 with db_connection as cursor:
292 cursor.execute('insert into ...')
293 cursor.execute('delete from ...')
294 # ... more operations ...
295
296The transaction should be committed if the code in the block runs flawlessly or
297rolled back if there's an exception. Here's the basic interface for
298:class:`DatabaseConnection` that I'll assume::
299
300 class DatabaseConnection:
301 # Database interface
Georg Brandl9f72d232007-12-16 23:13:29 +0000302 def cursor(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000303 "Returns a cursor object and starts a new transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000304 def commit(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000305 "Commits current transaction"
Georg Brandl9f72d232007-12-16 23:13:29 +0000306 def rollback(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000307 "Rolls back current transaction"
308
309The :meth:`__enter__` method is pretty easy, having only to start a new
310transaction. For this application the resulting cursor object would be a useful
311result, so the method will return it. The user can then add ``as cursor`` to
312their ':keyword:`with`' statement to bind the cursor to a variable name. ::
313
314 class DatabaseConnection:
315 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000316 def __enter__(self):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000317 # Code to start a new transaction
318 cursor = self.cursor()
319 return cursor
320
321The :meth:`__exit__` method is the most complicated because it's where most of
322the work has to be done. The method has to check if an exception occurred. If
323there was no exception, the transaction is committed. The transaction is rolled
324back if there was an exception.
325
326In the code below, execution will just fall off the end of the function,
327returning the default value of ``None``. ``None`` is false, so the exception
328will be re-raised automatically. If you wished, you could be more explicit and
329add a :keyword:`return` statement at the marked location. ::
330
331 class DatabaseConnection:
332 ...
Georg Brandl9f72d232007-12-16 23:13:29 +0000333 def __exit__(self, type, value, tb):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000334 if tb is None:
335 # No exception, so commit
336 self.commit()
337 else:
338 # Exception occurred, so rollback.
339 self.rollback()
340 # return False
341
342
343.. _module-contextlib:
344
345The contextlib module
346---------------------
347
348The new :mod:`contextlib` module provides some functions and a decorator that
349are useful for writing objects for use with the ':keyword:`with`' statement.
350
351The decorator is called :func:`contextmanager`, and lets you write a single
352generator function instead of defining a new class. The generator should yield
353exactly one value. The code up to the :keyword:`yield` will be executed as the
354:meth:`__enter__` method, and the value yielded will be the method's return
355value that will get bound to the variable in the ':keyword:`with`' statement's
356:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
357executed in the :meth:`__exit__` method. Any exception raised in the block will
358be raised by the :keyword:`yield` statement.
359
360Our database example from the previous section could be written using this
361decorator as::
362
363 from contextlib import contextmanager
364
365 @contextmanager
Georg Brandl9f72d232007-12-16 23:13:29 +0000366 def db_transaction(connection):
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000367 cursor = connection.cursor()
368 try:
369 yield cursor
370 except:
371 connection.rollback()
372 raise
373 else:
374 connection.commit()
375
376 db = DatabaseConnection()
377 with db_transaction(db) as cursor:
378 ...
379
380The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function
381that combines a number of context managers so you don't need to write nested
382':keyword:`with`' statements. In this example, the single ':keyword:`with`'
383statement both starts a database transaction and acquires a thread lock::
384
385 lock = threading.Lock()
386 with nested (db_transaction(db), lock) as (cursor, locked):
387 ...
388
389Finally, the :func:`closing(object)` function returns *object* so that it can be
390bound to a variable, and calls ``object.close`` at the end of the block. ::
391
392 import urllib, sys
393 from contextlib import closing
394
395 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
396 for line in f:
397 sys.stdout.write(line)
398
399
400.. seealso::
401
402 :pep:`343` - The "with" statement
403 PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
404 Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
405 ':keyword:`with`' statement, which can be helpful in learning how the statement
406 works.
407
408 The documentation for the :mod:`contextlib` module.
409
Georg Brandlb19be572007-12-29 10:57:00 +0000410.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000411
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000412.. _pep-0366:
413
414PEP 366: Explicit Relative Imports From a Main Module
415============================================================
416
417Python's :option:`-m` switch allows running a module as a script.
418When you ran a module that was located inside a package, relative
419imports didn't work correctly.
420
421The fix in Python 2.6 adds a :attr:`__package__` attribute to modules.
422When present, relative imports will be relative to the value of this
423attribute instead of the :attr:`__name__` attribute. PEP 302-style
424importers can then set :attr:`__package__`. The :mod:`runpy` module
425that implements the :option:`-m` switch now does this, so relative imports
426can now be used in scripts running from inside a package.
427
Georg Brandlb19be572007-12-29 10:57:00 +0000428.. ======================================================================
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000429
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000430.. ::
431
432 .. _pep-0370:
433
434 PEP 370: XXX
435 =====================================================
436
437 When you run Python, the module search page ``sys.modules`` usually
438 includes a directory whose path ends in ``"site-packages"``. This
439 directory is intended to hold locally-installed packages available to
440 all users on a machine or using a particular site installation.
441
442 Python 2.6 introduces a convention for user-specific site directories.
443
444 .. seealso::
445
446 :pep:`370` - XXX
447
448 PEP written by XXX; implemented by Christian Heimes.
449
450
451.. ======================================================================
452
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000453.. _pep-3101:
454
455PEP 3101: Advanced String Formatting
456=====================================================
457
458XXX write this
459
460.. ======================================================================
461
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000462.. _pep-3110:
463
464PEP 3110: Exception-Handling Changes
465=====================================================
466
467One error that Python programmers occasionally make
468is the following::
469
470 try:
471 ...
472 except TypeError, ValueError:
473 ...
474
475The author is probably trying to catch both
476:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
477actually does something different: it will catch
478:exc:`TypeError` and bind the resulting exception object
479to the local name ``"ValueError"``. The correct code
480would have specified a tuple::
481
482 try:
483 ...
484 except (TypeError, ValueError):
485 ...
486
487This error is possible because the use of the comma here is ambiguous:
488does it indicate two different nodes in the parse tree, or a single
489node that's a tuple.
490
491Python 3.0 changes the syntax to make this unambiguous by replacing
492the comma with the word "as". To catch an exception and store the
493exception object in the variable ``exc``, you must write::
494
495 try:
496 ...
497 except TypeError as exc:
498 ...
499
500Python 3.0 will only support the use of "as", and therefore interprets
501the first example as catching two different exceptions. Python 2.6
502supports both the comma and "as", so existing code will continue to
503work.
504
505.. seealso::
506
507 :pep:`3110` - Catching Exceptions in Python 3000
508 PEP written and implemented by Collin Winter.
509
Georg Brandlb19be572007-12-29 10:57:00 +0000510.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000511
512.. _pep-3119:
513
514PEP 3119: Abstract Base Classes
515=====================================================
516
517XXX
518
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000519How to identify a file object?
520
521ABCs are a collection of classes describing various interfaces.
522Classes can derive from an ABC to indicate they support that ABC's
523interface. Concrete classes should obey the semantics specified by
524an ABC, but Python can't check this; it's up to the implementor.
525
526A metaclass lets you declare that an existing class or type
527derives from a particular ABC. You can even
528
529class AppendableSequence:
530 __metaclass__ = ABCMeta
531
532AppendableSequence.register(list)
533assert issubclass(list, AppendableSequence)
534assert isinstance([], AppendableSequence)
535
536@abstractmethod decorator -- you can't instantiate classes w/
537an abstract method.
538
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000539::
540
541 @abstractproperty decorator
542 @abstractproperty
543 def readonly(self):
544 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000545
546
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000547.. seealso::
548
549 :pep:`3119` - Introducing Abstract Base Classes
550 PEP written by Guido van Rossum and Talin.
551 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000552 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000553
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000554.. ======================================================================
555
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000556.. _pep-3127:
557
558PEP 3127: Integer Literal Support and Syntax
559=====================================================
560
561XXX write this
562
563Python 3.0 changes the syntax for octal integer literals, and
564adds supports for binary integers: 0o instad of 0,
565and 0b for binary. Python 2.6 doesn't support this, but a bin()
566builtin was added, and
567
568
569New bin() built-in returns the binary form of a number.
570
571.. ======================================================================
572
573.. _pep-3129:
574
575PEP 3129: Class Decorators
576=====================================================
577
578XXX write this.
579
580.. ======================================================================
581
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000582.. _pep-3141:
583
584PEP 3141: A Type Hierarchy for Numbers
585=====================================================
586
587In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000588inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000589This change was backported to 2.6 as the :mod:`numbers` module.
590
591The most general ABC is :class:`Number`. It defines no operations at
592all, and only exists to allow checking if an object is a number by
593doing ``isinstance(obj, Number)``.
594
595Numbers are further divided into :class:`Exact` and :class:`Inexact`.
596Exact numbers can represent values precisely and operations never
597round off the results or introduce tiny errors that may break the
Georg Brandl907a7202008-02-22 12:31:45 +0000598commutativity and associativity properties; inexact numbers may
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000599perform such rounding or introduce small errors. Integers, long
600integers, and rational numbers are exact, while floating-point
601and complex numbers are inexact.
602
603:class:`Complex` is a subclass of :class:`Number`. Complex numbers
604can undergo the basic operations of addition, subtraction,
605multiplication, division, and exponentiation, and you can retrieve the
606real and imaginary parts and obtain a number's conjugate. Python's built-in
607complex type is an implementation of :class:`Complex`.
608
609:class:`Real` further derives from :class:`Complex`, and adds
610operations that only work on real numbers: :func:`floor`, :func:`trunc`,
611rounding, taking the remainder mod N, floor division,
612and comparisons.
613
614:class:`Rational` numbers derive from :class:`Real`, have
615:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +0000616converted to floats. Python 2.6 adds a simple rational-number class,
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000617:class:`Fraction`, in the :mod:`fractions` module. (It's called
618:class:`Fraction` instead of :class:`Rational` to avoid
619a name clash with :class:`numbers.Rational`.)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000620
621:class:`Integral` numbers derive from :class:`Rational`, and
622can be shifted left and right with ``<<`` and ``>>``,
623combined using bitwise operations such as ``&`` and ``|``,
624and can be used as array indexes and slice boundaries.
625
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000626In Python 3.0, the PEP slightly redefines the existing built-ins
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000627:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
628one, :func:`math.trunc`, that's been backported to Python 2.6.
629:func:`math.trunc` rounds toward zero, returning the closest
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000630:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000631
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000632.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000633
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000634 XXX link: Discusses Scheme's numeric tower.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000635
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000636
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000637
Mark Dickinsond058cd22008-02-10 21:29:51 +0000638The Fraction Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000639--------------------------------------------------
640
641To fill out the hierarchy of numeric types, a rational-number class
Mark Dickinsond058cd22008-02-10 21:29:51 +0000642has been added as the :mod:`fractions` module. Rational numbers are
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000643represented as a fraction, and can exactly represent
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000644numbers such as two-thirds that floating-point numbers can only
645approximate.
646
Mark Dickinsond058cd22008-02-10 21:29:51 +0000647The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000648that will be the numerator and denominator of the resulting fraction. ::
649
Mark Dickinsond058cd22008-02-10 21:29:51 +0000650 >>> from fractions import Fraction
651 >>> a = Fraction(2, 3)
652 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000653 >>> float(a), float(b)
654 (0.66666666666666663, 0.40000000000000002)
655 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000656 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000657 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000658 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000659
Mark Dickinsond058cd22008-02-10 21:29:51 +0000660The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000661Mullender that was in Python's :file:`Demo/classes/` directory for a
662long time. This implementation was significantly updated by Jeffrey
663Yaskin.
664
665
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666Other Language Changes
667======================
668
669Here are all of the changes that Python 2.6 makes to the core Python language.
670
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000671* When calling a function using the ``**`` syntax to provide keyword
672 arguments, you are no longer required to use a Python dictionary;
673 any mapping will now work::
674
675 >>> def f(**kw):
676 ... print sorted(kw)
677 ...
678 >>> ud=UserDict.UserDict()
679 >>> ud['a'] = 1
680 >>> ud['b'] = 'string'
681 >>> f(**ud)
682 ['a', 'b']
683
Georg Brandlb19be572007-12-29 10:57:00 +0000684 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000685
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000686* The built-in types now have improved support for extended slicing syntax,
687 where various combinations of ``(start, stop, step)`` are supplied.
688 Previously, the support was partial and certain corner cases wouldn't work.
689 (Implemented by Thomas Wouters.)
690
Georg Brandlb19be572007-12-29 10:57:00 +0000691 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000692
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000693* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000694 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000695 adding or modifying a getter, setter or deleter function to an
696 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000697
698 class C(object):
699 @property
700 def x(self):
701 return self._x
702
703 @x.setter
704 def x(self, value):
705 self._x = value
706
707 @x.deleter
708 def x(self):
709 del self._x
710
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000711 class D(C):
712 @C.x.getter
713 def x(self):
714 return self._x * 2
715
716 @x.setter
717 def x(self, value):
718 self._x = value / 2
719
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000720
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000721* C functions and methods that use
722 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
723 have a :meth:`__complex__` method. In particular, the functions in the
724 :mod:`cmath` module will now accept objects with this method.
725 This is a backport of a Python 3.0 change.
726 (Contributed by Mark Dickinson.)
727
Georg Brandlb19be572007-12-29 10:57:00 +0000728 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000729
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000730 A numerical nicety: when creating a complex number from two floats
731 on systems that support signed zeros (-0 and +0), the
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000732 :func:`complex` constructor will now preserve the sign
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000733 of the zero.
734
Georg Brandlb19be572007-12-29 10:57:00 +0000735 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000736
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000737* More floating-point features were also added. The :func:`float` function
738 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000739 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000740 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +0000741 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000742
743 .. Patch 1635.
744
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000745 Other functions in the :mod:`math` module, :func:`isinf` and
746 :func:`isnan`, return true if their floating-point argument is
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000747 infinite or Not A Number.
748
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000749 .. Patch 1640
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000750
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000751 The ``math.copysign(x, y)`` function
752 copies the sign bit of an IEEE 754 number, returning the absolute
753 value of *x* combined with the sign bit of *y*. For example,
754 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
755 Heimes.)
756
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000757* Changes to the :class:`Exception` interface
758 as dictated by :pep:`352` continue to be made. For 2.6,
759 the :attr:`message` attribute is being deprecated in favor of the
760 :attr:`args` attribute.
761
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000762* The :exc:`GeneratorExit` exception now subclasses
763 :exc:`BaseException` instead of :exc:`Exception`. This means
764 that an exception handler that does ``except Exception:``
765 will not inadvertently catch :exc:`GeneratorExit`.
766 (Contributed by Chad Austin.)
767
Georg Brandlb19be572007-12-29 10:57:00 +0000768 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000769
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000770* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000771 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000772
Georg Brandlb19be572007-12-29 10:57:00 +0000773 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000774
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000775* The :func:`complex` constructor now accepts strings containing
776 parenthesized complex numbers, letting ``complex(repr(cmplx))``
777 will now round-trip values. For example, ``complex('(3+4j)')``
778 now returns the value (3+4j).
779
Georg Brandlb19be572007-12-29 10:57:00 +0000780 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000781
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000782* The string :meth:`translate` method now accepts ``None`` as the
783 translation table parameter, which is treated as the identity
784 transformation. This makes it easier to carry out operations
785 that only delete characters. (Contributed by Bengt Richter.)
786
Georg Brandlb19be572007-12-29 10:57:00 +0000787 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000788
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000789* The built-in :func:`dir` function now checks for a :meth:`__dir__`
790 method on the objects it receives. This method must return a list
791 of strings containing the names of valid attributes for the object,
792 and lets the object control the value that :func:`dir` produces.
793 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +0000794 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000795
Georg Brandlb19be572007-12-29 10:57:00 +0000796 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000797
Georg Brandl8ec7f652007-08-15 14:28:01 +0000798* An obscure change: when you use the the :func:`locals` function inside a
799 :keyword:`class` statement, the resulting dictionary no longer returns free
800 variables. (Free variables, in this case, are variables referred to in the
801 :keyword:`class` statement that aren't attributes of the class.)
802
Georg Brandlb19be572007-12-29 10:57:00 +0000803.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000804
805
806Optimizations
807-------------
808
Georg Brandlaf30b282008-01-15 06:55:56 +0000809* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000810 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +0000811 for a particular class; once cached, the interpreter doesn't need to
812 traverse base classes to figure out the right method to call.
813 The cache is cleared if a base class or the class itself is modified,
814 so the cache should remain correct even in the face of Python's dynamic
815 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000816 (Original optimization implemented by Armin Rigo, updated for
817 Python 2.6 by Kevin Jacobs.)
818
819 .. % Patch 1700288
820
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000821* All of the functions in the :mod:`struct` module have been rewritten in
822 C, thanks to work at the Need For Speed sprint.
823 (Contributed by Raymond Hettinger.)
824
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825* Internally, a bit is now set in type objects to indicate some of the standard
826 built-in types. This speeds up checking if an object is a subclass of one of
827 these types. (Contributed by Neal Norwitz.)
828
Andrew M. Kuchling378586a2008-03-04 01:50:32 +0000829* Unicode strings now uses faster code for detecting
830 whitespace and line breaks; this speeds up the :meth:`split` method
831 by about 25% and :meth:`splitlines` by 35%.
832 (Contributed by Antoine Pitrou.)
833
834* To reduce memory usage, the garbage collector will now clear internal
835 free lists when garbage-collecting the highest generation of objects.
836 This may return memory to the OS sooner.
837
Georg Brandl8ec7f652007-08-15 14:28:01 +0000838The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
839benchmark around XX% faster than Python 2.5.
840
Georg Brandlb19be572007-12-29 10:57:00 +0000841.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000842
843
844New, Improved, and Deprecated Modules
845=====================================
846
847As usual, Python's standard library received a number of enhancements and bug
848fixes. Here's a partial list of the most notable changes, sorted alphabetically
849by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
850complete list of changes, or look through the CVS logs for all the details.
851
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000852* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
853 available, instead of restricting itself to protocol 1.
854 (Contributed by W. Barnes.)
855
Georg Brandlb19be572007-12-29 10:57:00 +0000856 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000857
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000858* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859 fieldnames)` is a factory function that creates subclasses of the standard tuple
860 whose fields are accessible by name as well as index. For example::
861
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000862 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000863 ... 'id name type size')
864 # Names are separated by spaces or commas.
865 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +0000866 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000867 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000869 >>> var = var_type(1, 'frequency', 'int', 4)
870 >>> print var[0], var.id # Equivalent
871 1 1
872 >>> print var[2], var.type # Equivalent
873 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +0000874 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000875 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +0000876 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000877 >>> v2
878 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000879
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000880 Where the new :class:`namedtuple` type proved suitable, the standard
881 library has been modified to return them. For example,
882 the :meth:`Decimal.as_tuple` method now returns a named tuple with
883 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
884
Georg Brandl8ec7f652007-08-15 14:28:01 +0000885 (Contributed by Raymond Hettinger.)
886
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000887* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +0000888 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000889 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +0000890 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000891 old items to be discarded.
892
893 ::
894
895 >>> from collections import deque
896 >>> dq=deque(maxlen=3)
897 >>> dq
898 deque([], maxlen=3)
899 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
900 >>> dq
901 deque([1, 2, 3], maxlen=3)
902 >>> dq.append(4)
903 >>> dq
904 deque([2, 3, 4], maxlen=3)
905
906 (Contributed by Raymond Hettinger.)
907
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000908* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
909 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
910
Georg Brandlb19be572007-12-29 10:57:00 +0000911 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000912
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000913 The :mod:`ctypes` string, buffer and array types also have improved
914 support for extended slicing syntax,
915 where various combinations of ``(start, stop, step)`` are supplied.
916 (Implemented by Thomas Wouters.)
917
Georg Brandlb19be572007-12-29 10:57:00 +0000918 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000919
Georg Brandl8ec7f652007-08-15 14:28:01 +0000920* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000921 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +0000922 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000923 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000924
925 # Boldface text starting at y=0,x=21
926 # and affecting the rest of the line.
927 stdscr.chgat(0,21, curses.A_BOLD)
928
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +0000929 The :class:`Textbox` class in the :mod:`curses.textpad` module
930 now supports editing in insert mode as well as overwrite mode.
931 Insert mode is enabled by supplying a true value for the *insert_mode*
932 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000933
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000934* The :mod:`decimal` module was updated to version 1.66 of
935 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
936 include some methods for some basic mathematical functions such as
937 :meth:`exp` and :meth:`log10`::
938
939 >>> Decimal(1).exp()
940 Decimal("2.718281828459045235360287471")
941 >>> Decimal("2.7182818").ln()
942 Decimal("0.9999999895305022877376682436")
943 >>> Decimal(1000).log10()
944 Decimal("3")
945
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000946 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
947 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
948
949 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
950 support added by Raymond Hettinger.)
951
952* The :mod:`difflib` module's :class:`SequenceMatcher` class
953 now returns named tuples representing matches.
954 In addition to behaving like tuples, the returned values
955 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
956 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000957
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000958* An optional ``timeout`` parameter was added to the
959 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
960 method, specifying a timeout measured in seconds. (Added by Facundo
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +0000961 Batista.) Also, the :class:`FTP` class's
962 :meth:`storbinary` and :meth:`storlines`
963 now take an optional *callback* parameter that will be called with
964 each block of data after the data has been sent.
965 (Contributed by Phil Schwartz.)
966
967 .. Patch 1221598
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000968
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000969* The :func:`reduce` built-in function is also available in the
970 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
971 only available from :mod:`functools`; currently there are no plans
972 to drop the built-in in the 2.x series. (Patched by
973 Christian Heimes.)
974
Georg Brandlb19be572007-12-29 10:57:00 +0000975 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000976
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977* The :func:`glob.glob` function can now return Unicode filenames if
978 a Unicode path was used and Unicode filenames are matched within the directory.
979
Georg Brandlb19be572007-12-29 10:57:00 +0000980 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
982* The :mod:`gopherlib` module has been removed.
983
984* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
985 takes any number of iterables that return data *in sorted order*, and returns
986 a new iterator that returns the contents of all the iterators, also in sorted
987 order. For example::
988
989 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
990 [1, 2, 3, 5, 8, 9, 16]
991
992 (Contributed by Raymond Hettinger.)
993
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000994* An optional ``timeout`` parameter was added to the
995 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
996 class constructors, specifying a timeout measured in seconds.
997 (Added by Facundo Batista.)
998
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000999* Most of the :mod:`inspect` module's functions, such as
1000 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
1001 In addition to behaving like tuples, the elements of the return value
1002 can also be accessed as attributes.
1003 (Contributed by Raymond Hettinger.)
1004
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001005 Some new functions in the module include
1006 :func:`isgenerator`, :func:`isgeneratorfunction`,
1007 and :func:`isabstract`.
1008
1009* The :mod:`itertools` module gained several new functions.
1010
1011 ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
1012 each of the elements; if some of the iterables are shorter than
1013 others, the missing values are set to *fillvalue*. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001014
1015 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
1016 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
1017
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001018 ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
1019 of the supplied iterables, a set of tuples containing
1020 every possible combination of the elements returned from each iterable. ::
1021
1022 itertools.product([1,2,3], [4,5,6]) ->
1023 [(1, 4), (1, 5), (1, 6),
1024 (2, 4), (2, 5), (2, 6),
1025 (3, 4), (3, 5), (3, 6)]
1026
1027 The optional *repeat* keyword argument is used for taking the
1028 product of an iterable or a set of iterables with themselves,
1029 repeated *N* times. With a single iterable argument, *N*-tuples
1030 are returned::
1031
1032 itertools.product([1,2], repeat=3)) ->
1033 [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
1034 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
1035
1036 With two iterables, *2N*-tuples are returned. ::
1037
1038 itertools(product([1,2], [3,4], repeat=2) ->
1039 [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
1040 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
1041 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
1042 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
1043
1044 ``combinations(iter, r)`` returns combinations of length *r* from
1045 the elements of *iterable*. ::
1046
1047 itertools.combinations('123', 2) ->
1048 [('1', '2'), ('1', '3'), ('2', '3')]
1049
1050 itertools.combinations('123', 3) ->
1051 [('1', '2', '3')]
1052
1053 itertools.combinations('1234', 3) ->
1054 [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
1055 ('2', '3', '4')]
1056
1057 ``itertools.chain(*iterables)` is an existing function in
1058 :mod:`itertools` that gained a new constructor.
1059 ``itertools.chain.from_iterable(iterable)`` takes a single
1060 iterable that should return other iterables. :func:`chain` will
1061 then return all the elements of the first iterable, then
1062 all the elements of the second, and so on. ::
1063
1064 chain.from_iterable([[1,2,3], [4,5,6]]) ->
1065 [1, 2, 3, 4, 5, 6]
1066
1067 (All contributed by Raymond Hettinger.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001068
1069* The :mod:`macfs` module has been removed. This in turn required the
1070 :func:`macostools.touched` function to be removed because it depended on the
1071 :mod:`macfs` module.
1072
Georg Brandlb19be572007-12-29 10:57:00 +00001073 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +00001074
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001075* :class:`mmap` objects now have a :meth:`rfind` method that finds
1076 a substring, beginning at the end of the string and searching
1077 backwards. The :meth:`find` method
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001078 also gained an *end* parameter containing the index at which to stop
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +00001079 the forward search.
1080 (Contributed by John Lenton.)
1081
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001082* The :mod:`new` module has been removed from Python 3.0.
1083 Importing it therefore
1084 triggers a warning message when Python is running in 3.0-warning
1085 mode.
1086
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001087* The :mod:`operator` module gained a
1088 :func:`methodcaller` function that takes a name and an optional
1089 set of arguments, returning a callable that will call
1090 the named function on any arguments passed to it. For example::
1091
1092 >>> # Equivalent to lambda s: s.replace('old', 'new')
1093 >>> replacer = operator.methodcaller('replace', 'old', 'new')
1094 >>> replacer('old wine in old bottles')
1095 'new wine in new bottles'
1096
1097 (Contributed by Gregory Petrosyan.)
1098
1099 The :func:`attrgetter` function now accepts dotted names and performs
1100 the corresponding attribute lookups::
1101
1102 >>> inst_name = operator.attrgetter('__class__.__name__')
1103 >>> inst_name('')
1104 'str'
1105 >>> inst_name(help)
1106 '_Helper'
1107
1108 (Contributed by Scott Dial, after a suggestion by Barry Warsaw.)
1109
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001110* New functions in the :mod:`os` module include
1111 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
1112 and ``lchmod(path, mode)``, on operating systems that support these
1113 functions. :func:`fchmod` and :func:`fchown` let you change the mode
1114 and ownership of an opened file, and :func:`lchmod` changes the mode
1115 of a symlink.
1116
1117 (Contributed by Georg Brandl and Christian Heimes.)
1118
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001119* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001120 set to True, it will follow symlinks pointing to directories and
1121 visit the directory's contents. For backward compatibility, the
1122 parameter's default value is false. Note that the function can fall
1123 into an infinite recursion if there's a symlink that points to a
1124 parent directory.
1125
Georg Brandlb19be572007-12-29 10:57:00 +00001126 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001127
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001128* The ``os.environ`` object's :meth:`clear` method will now unset the
1129 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001130 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001131
Georg Brandlb19be572007-12-29 10:57:00 +00001132 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001133
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001134* In the :mod:`os.path` module, the :func:`splitext` function
1135 has been changed to not split on leading period characters.
1136 This produces better results when operating on Unix's dot-files.
1137 For example, ``os.path.splitext('.ipython')``
1138 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
1139
Georg Brandlb19be572007-12-29 10:57:00 +00001140 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001141
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001142 A new function, :func:`relpath(path, start)` returns a relative path
1143 from the ``start`` path, if it's supplied, or from the current
1144 working directory to the destination ``path``. (Contributed by
1145 Richard Barran.)
1146
Georg Brandlb19be572007-12-29 10:57:00 +00001147 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001148
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001149 On Windows, :func:`os.path.expandvars` will now expand environment variables
1150 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001151 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001152
Georg Brandlb19be572007-12-29 10:57:00 +00001153 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001154
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001155* The Python debugger provided by the :mod:`pdb` module
1156 gained a new command: "run" restarts the Python program being debugged,
1157 and can optionally take new command-line arguments for the program.
1158 (Contributed by Rocky Bernstein.)
1159
Georg Brandlb19be572007-12-29 10:57:00 +00001160 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001161
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001162* The :mod:`pickletools` module now has an :func:`optimize` function
1163 that takes a string containing a pickle and removes some unused
1164 opcodes, returning a shorter pickle that contains the same data structure.
1165 (Contributed by Raymond Hettinger.)
1166
Georg Brandl8ec7f652007-08-15 14:28:01 +00001167* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
1168 are wrappers for the corresponding system calls (where they're available).
1169 Constants for the flag values are defined in the :mod:`stat` module; some
1170 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
1171 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
1172 file. (Contributed by M. Levinson.)
1173
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00001174* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
1175 their :attr:`buffer_size` attribute to change the size of the buffer
1176 used to hold character data.
1177 (Contributed by Achim Gaedke.)
1178
1179 .. Patch 1137
1180
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001181* The :mod:`Queue` module now provides queue classes that retrieve entries
1182 in different orders. The :class:`PriorityQueue` class stores
1183 queued items in a heap and retrieves them in priority order,
1184 and :class:`LifoQueue` retrieves the most recently added entries first,
1185 meaning that it behaves like a stack.
1186 (Contributed by Raymond Hettinger.)
1187
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001188* The :mod:`random` module's :class:`Random` objects can
1189 now be pickled on a 32-bit system and unpickled on a 64-bit
1190 system, and vice versa. Unfortunately, this change also means
1191 that Python 2.6's :class:`Random` objects can't be unpickled correctly
1192 on earlier versions of Python.
1193 (Contributed by Shawn Ligocki.)
1194
Georg Brandlb19be572007-12-29 10:57:00 +00001195 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001196
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001197* Long regular expression searches carried out by the :mod:`re`
1198 module will now check for signals being delivered, so especially
1199 long searches can now be interrupted.
1200 (Contributed by Josh Hoyt and Ralf Schmitt.)
1201
1202 .. % Patch 846388
1203
Georg Brandl8ec7f652007-08-15 14:28:01 +00001204* The :mod:`rgbimg` module has been removed.
1205
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001206* The :mod:`sets` module has been deprecated; it's better to
1207 use the built-in :class:`set` and :class:`frozenset` types.
1208
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001209* Integrating signal handling with GUI handling event loops
1210 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001211 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001212 The :mod:`signal` module can now make this more efficient.
1213 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
1214 to be used; when a signal is received, a byte is written to that
1215 file descriptor. There's also a C-level function,
1216 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
1217
1218 Event loops will use this by opening a pipe to create two descriptors,
1219 one for reading and one for writing. The writeable descriptor
1220 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
1221 will be added to the list of descriptors monitored by the event loop via
1222 :cfunc:`select` or :cfunc:`poll`.
1223 On receiving a signal, a byte will be written and the main event loop
1224 will be woken up, without the need to poll.
1225
1226 Contributed by Adam Olsen.
1227
1228 .. % Patch 1583
1229
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001230 The :func:`siginterrupt` function is now available from Python code,
1231 and allows changing whether signals can interrupt system calls or not.
1232 (Contributed by Ralf Schmitt.)
1233
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001234* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
1235 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001236 interface identical to the existing :class:`SMTP` class. Both
1237 class constructors also have an optional ``timeout`` parameter
1238 that specifies a timeout for the initial connection attempt, measured in
1239 seconds.
1240
1241 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001242 the module. LMTP is used in place of SMTP when transferring e-mail
1243 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001244
1245 (SMTP over SSL contributed by Monty Taylor; timeout parameter
1246 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001247 Hedstrom.)
1248
Georg Brandlb19be572007-12-29 10:57:00 +00001249 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +00001250
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001251* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
1252 and forgets any knowledge obtained from the server not obtained from
1253 the TLS negotiation itself. Patch contributed by Bill Fenner.
1254
1255 .. Issue 829951
1256
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001257* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1258 a high-performance non-IP-based protocol designed for use in clustered
1259 environments. TIPC addresses are 4- or 5-tuples.
1260 (Contributed by Alberto Bertogli.)
1261
1262 .. Patch #1646
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00001263
1264* The base classes in the :mod:`SocketServer` module now support
1265 calling a :meth:`handle_timeout` method after a span of inactivity
1266 specified by the server's :attr:`timeout` attribute. (Contributed
1267 by Michael Pomraning.)
1268
1269 .. Patch #742598
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001270
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001271* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001272 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001273 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001274 derived from the :file:`float.h` file. Attributes of this object
1275 include
1276 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001277 (smallest difference between 1.0 and the next largest value
1278 representable), and several others. (Contributed by Christian Heimes.)
1279
Georg Brandlb19be572007-12-29 10:57:00 +00001280 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001281
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00001282 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
1283 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1284 If this variable is true, the compiled files are not written. The
1285 variable is initially set on start-up by supplying the :option:`-B`
1286 switch to the Python interpreter, or by setting the
1287 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
1288 running the interpreter. Python code can subsequently
1289 change the value of this variable to control whether bytecode files
1290 are written or not.
1291 (Contributed by Neal Norwitz and Georg Brandl.)
1292
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001293 Information about the command-line arguments supplied to the Python
1294 interpreter are available as attributes of a ``sys.flags`` named
1295 tuple. For example, the :attr:`verbose` attribute is true if Python
1296 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1297 These attributes are all read-only.
1298 (Contributed by Christian Heimes.)
1299
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001300* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1301 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1302 format that was already supported. The default format
1303 is GNU tar; specify the ``format`` parameter to open a file
1304 using a different format::
1305
1306 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1307
1308 The new ``errors`` parameter lets you specify an error handling
1309 scheme for character conversions: the three standard ways Python can
1310 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1311 special value ``'utf-8'``, which replaces bad characters with their
1312 UTF-8 representation. Character conversions occur because the PAX
1313 format supports Unicode filenames, defaulting to UTF-8 encoding.
1314
1315 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1316 a function that can be used to exclude certain filenames from
1317 an archive.
1318 The function must take a filename and return true if the file
1319 should be excluded or false if it should be archived.
1320 The function is applied to both the name initially passed to :meth:`add`
1321 and to the names of files in recursively-added directories.
1322
1323 (All changes contributed by Lars Gustäbel).
1324
1325* An optional ``timeout`` parameter was added to the
1326 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1327 measured in seconds. (Added by Facundo Batista.)
1328
1329* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1330 the temporary file it created when the file is closed. This
1331 behaviour can now be changed by passing ``delete=False`` to the
1332 constructor. (Contributed by Damien Miller.)
1333
Georg Brandlb19be572007-12-29 10:57:00 +00001334 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001335
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001336 A new class, :class:`SpooledTemporaryFile`, behaves like
1337 a temporary file but stores its data in memory until a maximum size is
1338 exceeded. On reaching that limit, the contents will be written to
1339 an on-disk temporary file. (Contributed by Dustin J. Mitchell.)
1340
1341 The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
1342 both work as context managers, so you can write
1343 ``with tempfile.NamedTemporaryFile() as tmp: ...``.
1344 (Contributed by Alexander Belopolsky.)
1345
1346 .. Issue #2021
1347
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001348* The :mod:`test.test_support` module now contains a
1349 :func:`EnvironmentVarGuard`
1350 context manager that supports temporarily changing environment variables and
1351 automatically restores them to their old values.
1352
1353 Another context manager, :class:`TransientResource`, can surround calls
1354 to resources that may or may not be available; it will catch and
1355 ignore a specified list of exceptions. For example,
1356 a network test may ignore certain failures when connecting to an
1357 external web site::
1358
1359 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
1360 f = urllib.urlopen('https://sf.net')
1361 ...
1362
1363 (Contributed by Brett Cannon.)
1364
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001365* The :mod:`textwrap` module can now preserve existing whitespace
1366 at the beginnings and ends of the newly-created lines
1367 by specifying ``drop_whitespace=False``
1368 as an argument::
1369
1370 >>> S = """This sentence has a bunch of extra whitespace."""
1371 >>> print textwrap.fill(S, width=15)
1372 This sentence
1373 has a bunch
1374 of extra
1375 whitespace.
1376 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
1377 This sentence
1378 has a bunch
1379 of extra
1380 whitespace.
1381 >>>
1382
Georg Brandlb19be572007-12-29 10:57:00 +00001383 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001384
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001385* The :mod:`timeit` module now accepts callables as well as strings
1386 for the statement being timed and for the setup code.
1387 Two convenience functions were added for creating
1388 :class:`Timer` instances:
1389 ``repeat(stmt, setup, time, repeat, number)`` and
1390 ``timeit(stmt, setup, time, number)`` create an instance and call
1391 the corresponding method. (Contributed by Erik Demaine.)
1392
Georg Brandlb19be572007-12-29 10:57:00 +00001393 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001394
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001395* An optional ``timeout`` parameter was added to the
1396 :func:`urllib.urlopen` function and the
1397 :class:`urllib.ftpwrapper` class constructor, as well as the
1398 :func:`urllib2.urlopen` function. The parameter specifies a timeout
1399 measured in seconds. For example::
1400
1401 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
1402 Traceback (most recent call last):
1403 ...
1404 urllib2.URLError: <urlopen error timed out>
1405 >>>
1406
1407 (Added by Facundo Batista.)
1408
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001409* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001410 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001411 their socket by passing True as the ``bind_and_activate``
1412 constructor parameter. This can be used to modify the instance's
1413 :attr:`allow_reuse_address` attribute before calling the
1414 :meth:`server_bind` and :meth:`server_activate` methods to
1415 open the socket and begin listening for connections.
1416 (Contributed by Peter Parente.)
1417
Georg Brandlb19be572007-12-29 10:57:00 +00001418 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001419
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001420 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
1421 attribute; if true, the exception and formatted traceback are returned
1422 as HTTP headers "X-Exception" and "X-Traceback". This feature is
1423 for debugging purposes only and should not be used on production servers
1424 because the tracebacks could possibly reveal passwords or other sensitive
1425 information. (Contributed by Alan McIntyre as part of his
1426 project for Google's Summer of Code 2007.)
1427
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001428* The :mod:`zipfile` module's :class:`ZipFile` class now has
1429 :meth:`extract` and :meth:`extractall` methods that will unpack
1430 a single file or all the files in the archive to the current directory, or
1431 to a specified directory::
1432
1433 z = zipfile.ZipFile('python-251.zip')
1434
1435 # Unpack a single file, writing it relative to the /tmp directory.
1436 z.extract('Python/sysmodule.c', '/tmp')
1437
1438 # Unpack all the files in the archive.
1439 z.extractall()
1440
1441 (Contributed by Alan McIntyre.)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001442
1443 .. Patch 467924
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001444
Georg Brandlb19be572007-12-29 10:57:00 +00001445.. ======================================================================
1446.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001447
1448Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00001449--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001450
1451Bill Janssen made extensive improvements to Python 2.6's support for
1452SSL.
1453
1454XXX use ssl.sslsocket - subclass of socket.socket.
1455
1456XXX Can specify if certificate is required, and obtain certificate info
1457by calling getpeercert method.
1458
1459XXX sslwrap() behaves like socket.ssl
1460
1461XXX Certain features require the OpenSSL package to be installed, notably
1462 the 'openssl' binary.
1463
1464.. seealso::
1465
1466 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001467
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001468
1469.. ======================================================================
1470
1471plistlib: A Property-List Parser
1472--------------------------------------------------
1473
1474A commonly-used format on MacOS X is the ``.plist`` format,
1475which stores basic data types (numbers, strings, lists,
1476and dictionaries) and serializes them into an XML-based format.
1477(It's a lot like the XML-RPC serialization of data types.)
1478
1479Despite being primarily used on MacOS X, the format
1480has nothing Mac-specific about it and the Python implementation works
1481on any platform that Python supports, so the :mod:`plistlib` module
1482has been promoted to the standard library.
1483
1484Using the module is simple::
1485
1486 import sys
1487 import plistlib
1488 import datetime
1489
1490 # Create data structure
1491 data_struct = dict(lastAccessed=datetime.datetime.now(),
1492 version=1,
1493 categories=('Personal', 'Shared', 'Private'))
1494
1495 # Create string containing XML.
1496 plist_str = plistlib.writePlistToString(data_struct)
1497 new_struct = plistlib.readPlistFromString(plist_str)
1498 print data_struct
1499 print new_struct
1500
1501 # Write data structure to a file and read it back.
1502 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
1503 new_struct = plistlib.readPlist('/tmp/customizations.plist')
1504
1505 # read/writePlist accepts file-like objects as well as paths.
1506 plistlib.writePlist(data_struct, sys.stdout)
1507
1508
Georg Brandlb19be572007-12-29 10:57:00 +00001509.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001510
1511
1512Build and C API Changes
1513=======================
1514
1515Changes to Python's build process and to the C API include:
1516
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001517* Python 2.6 can be built with Microsoft Visual Studio 2008.
1518 See the :file:`PCbuild9` directory for the build files.
1519 (Implemented by Christian Heimes.)
1520
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001521* The BerkeleyDB module now has a C API object, available as
1522 ``bsddb.db.api``. This object can be used by other C extensions
1523 that wish to use the :mod:`bsddb` module for their own purposes.
1524 (Contributed by Duncan Grisby.)
1525
Georg Brandlb19be572007-12-29 10:57:00 +00001526 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001527
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001528* Several functions return information about the platform's
1529 floating-point support. :cfunc:`PyFloat_GetMax` returns
1530 the maximum representable floating point value,
1531 and :cfunc:`PyFloat_GetMin` returns the minimum
1532 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1533 containing more information from the :file:`float.h` file, such as
1534 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1535 (smallest difference between 1.0 and the next largest value
1536 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001537 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001538
Georg Brandlb19be572007-12-29 10:57:00 +00001539 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001540
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001541* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00001542 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001543 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001544 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001545
1546 .. Issue 1635
1547
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001548* Some macros were renamed to make it clearer that they are macros,
1549 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001550 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
1551 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. Macros for backward
Christian Heimesd0d7d872008-01-04 02:03:25 +00001552 compatibility are still available for Python 2.6.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001553
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001554 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001555
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001556* Distutils now places C extensions it builds in a
1557 different directory when running on a debug version of Python.
1558 (Contributed by Collin Winter.)
1559
1560 .. Patch 1530959
1561
Andrew M. Kuchling378586a2008-03-04 01:50:32 +00001562* Several basic data types, such as integers and strings, maintain
1563 internal free lists of objects that can be re-used. The data
1564 structures for these free lists now follow a naming convention: the
1565 variable is always named ``free_list``, the counter is always named
1566 ``numfree``, and a macro :cmacro:`Py<typename>_MAXFREELIST` is
1567 always defined.
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001568
Georg Brandlb19be572007-12-29 10:57:00 +00001569.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001570
1571
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001572Port-Specific Changes: Windows
1573-----------------------------------
1574
1575* The :mod:`msvcrt` module now supports
1576 both the normal and wide char variants of the console I/O
1577 API. The :func:`getwch` function reads a keypress and returns a Unicode
1578 value, as does the :func:`getwche` function. The :func:`putwch` function
1579 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001580 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001581
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001582* :func:`os.path.expandvars` will now expand environment variables
1583 in the form "%var%", and "~user" will be expanded into the
1584 user's home directory path. (Contributed by Josiah Carlson.)
1585
1586* The :mod:`socket` module's socket objects now have an
1587 :meth:`ioctl` method that provides a limited interface to the
1588 :cfunc:`WSAIoctl` system interface.
1589
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001590* The :mod:`_winreg` module now has a function,
1591 :func:`ExpandEnvironmentStrings`,
1592 that expands environment variable references such as ``%NAME%``
1593 in an input string. The handle objects provided by this
1594 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001595 in :keyword:`with` statements. (Contributed by Christian Heimes.)
1596
1597* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
1598 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
1599 were moved into the PC/ directory. The new PCbuild directory supports
1600 cross compilation for X64, debug builds and Profile Guided Optimization
1601 (PGO). PGO builds are roughly 10% faster than normal builds.
1602 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
1603 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001604
Georg Brandlb19be572007-12-29 10:57:00 +00001605.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001606
1607
1608.. _section-other:
1609
1610Other Changes and Fixes
1611=======================
1612
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001613As usual, there were a bunch of other improvements and bugfixes
1614scattered throughout the source tree. A search through the change
1615logs finds there were XXX patches applied and YYY bugs fixed between
1616Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001617
1618Some of the more notable changes are:
1619
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001620* It's now possible to prevent Python from writing any :file:`.pyc`
1621 or :file:`.pyo` files by either supplying the :option:`-B` switch
1622 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
1623 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00001624 are also used to set the :data:`sys.dont_write_bytecode` attribute;
1625 Python code can change this variable to control whether bytecode
1626 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001627 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001628
Georg Brandlb19be572007-12-29 10:57:00 +00001629.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001630
1631
1632Porting to Python 2.6
1633=====================
1634
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001635This section lists previously described changes, and a few
1636esoteric bugfixes, that may require changes to your
Georg Brandl8ec7f652007-08-15 14:28:01 +00001637code:
1638
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001639* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001640 now clears any existing contents of the deque
1641 before adding elements from the iterable. This change makes the
1642 behavior match that of ``list.__init__()``.
1643
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001644* The :class:`Decimal` constructor now accepts leading and trailing
1645 whitespace when passed a string. Previously it would raise an
1646 :exc:`InvalidOperation` exception. On the other hand, the
1647 :meth:`create_decimal` method of :class:`Context` objects now
1648 explicitly disallows extra whitespace, raising a
1649 :exc:`ConversionSyntax` exception.
1650
1651* Due to an implementation accident, if you passed a file path to
1652 the built-in :func:`__import__` function, it would actually import
1653 the specified file. This was never intended to work, however, and
1654 the implementation now explicitly checks for this case and raises
1655 an :exc:`ImportError`.
1656
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001657* The :mod:`socket` module exception :exc:`socket.error` now inherits
1658 from :exc:`IOError`. Previously it wasn't a subclass of
1659 :exc:`StandardError` but now it is, through :exc:`IOError`.
1660 (Implemented by Gregory P. Smith.)
1661
Georg Brandlb19be572007-12-29 10:57:00 +00001662 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00001663
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +00001664* The :mod:`xmlrpclib` module no longer automatically converts
1665 :class:`datetime.date` and :class:`datetime.time` to the
1666 :class:`xmlrpclib.DateTime` type; the conversion semantics were
1667 not necessarily correct for all applications. Code using
1668 :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
1669 instances.
1670
1671 .. Issue 1330538
1672
Georg Brandlb19be572007-12-29 10:57:00 +00001673.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001674
1675
1676.. _acks:
1677
1678Acknowledgements
1679================
1680
1681The author would like to thank the following people for offering suggestions,
1682corrections and assistance with various drafts of this article: .
1683