blob: 3f89c03fe8cb930d4c3f658ff2147e8a06399e77 [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. Kuchlingf10878b2007-09-13 22:49:34 +0000453.. _pep-3110:
454
455PEP 3110: Exception-Handling Changes
456=====================================================
457
458One error that Python programmers occasionally make
459is the following::
460
461 try:
462 ...
463 except TypeError, ValueError:
464 ...
465
466The author is probably trying to catch both
467:exc:`TypeError` and :exc:`ValueError` exceptions, but this code
468actually does something different: it will catch
469:exc:`TypeError` and bind the resulting exception object
470to the local name ``"ValueError"``. The correct code
471would have specified a tuple::
472
473 try:
474 ...
475 except (TypeError, ValueError):
476 ...
477
478This error is possible because the use of the comma here is ambiguous:
479does it indicate two different nodes in the parse tree, or a single
480node that's a tuple.
481
482Python 3.0 changes the syntax to make this unambiguous by replacing
483the comma with the word "as". To catch an exception and store the
484exception object in the variable ``exc``, you must write::
485
486 try:
487 ...
488 except TypeError as exc:
489 ...
490
491Python 3.0 will only support the use of "as", and therefore interprets
492the first example as catching two different exceptions. Python 2.6
493supports both the comma and "as", so existing code will continue to
494work.
495
496.. seealso::
497
498 :pep:`3110` - Catching Exceptions in Python 3000
499 PEP written and implemented by Collin Winter.
500
Georg Brandlb19be572007-12-29 10:57:00 +0000501.. ======================================================================
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000502
503.. _pep-3119:
504
505PEP 3119: Abstract Base Classes
506=====================================================
507
508XXX
509
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000510How to identify a file object?
511
512ABCs are a collection of classes describing various interfaces.
513Classes can derive from an ABC to indicate they support that ABC's
514interface. Concrete classes should obey the semantics specified by
515an ABC, but Python can't check this; it's up to the implementor.
516
517A metaclass lets you declare that an existing class or type
518derives from a particular ABC. You can even
519
520class AppendableSequence:
521 __metaclass__ = ABCMeta
522
523AppendableSequence.register(list)
524assert issubclass(list, AppendableSequence)
525assert isinstance([], AppendableSequence)
526
527@abstractmethod decorator -- you can't instantiate classes w/
528an abstract method.
529
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +0000530::
531
532 @abstractproperty decorator
533 @abstractproperty
534 def readonly(self):
535 return self._x
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000536
537
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000538.. seealso::
539
540 :pep:`3119` - Introducing Abstract Base Classes
541 PEP written by Guido van Rossum and Talin.
542 Implemented by XXX.
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000543 Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000544
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000545.. ======================================================================
546
547.. _pep-3141:
548
549PEP 3141: A Type Hierarchy for Numbers
550=====================================================
551
552In Python 3.0, several abstract base classes for numeric types,
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000553inspired by Scheme's numeric tower, are being added.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000554This change was backported to 2.6 as the :mod:`numbers` module.
555
556The most general ABC is :class:`Number`. It defines no operations at
557all, and only exists to allow checking if an object is a number by
558doing ``isinstance(obj, Number)``.
559
560Numbers are further divided into :class:`Exact` and :class:`Inexact`.
561Exact numbers can represent values precisely and operations never
562round off the results or introduce tiny errors that may break the
Georg Brandl907a7202008-02-22 12:31:45 +0000563commutativity and associativity properties; inexact numbers may
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000564perform such rounding or introduce small errors. Integers, long
565integers, and rational numbers are exact, while floating-point
566and complex numbers are inexact.
567
568:class:`Complex` is a subclass of :class:`Number`. Complex numbers
569can undergo the basic operations of addition, subtraction,
570multiplication, division, and exponentiation, and you can retrieve the
571real and imaginary parts and obtain a number's conjugate. Python's built-in
572complex type is an implementation of :class:`Complex`.
573
574:class:`Real` further derives from :class:`Complex`, and adds
575operations that only work on real numbers: :func:`floor`, :func:`trunc`,
576rounding, taking the remainder mod N, floor division,
577and comparisons.
578
579:class:`Rational` numbers derive from :class:`Real`, have
580:attr:`numerator` and :attr:`denominator` properties, and can be
Mark Dickinsond058cd22008-02-10 21:29:51 +0000581converted to floats. Python 2.6 adds a simple rational-number class,
582:class:`Fraction`, in the :mod:`fractions` module.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000583
584:class:`Integral` numbers derive from :class:`Rational`, and
585can be shifted left and right with ``<<`` and ``>>``,
586combined using bitwise operations such as ``&`` and ``|``,
587and can be used as array indexes and slice boundaries.
588
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000589In Python 3.0, the PEP slightly redefines the existing built-ins
590:func:`math.floor`, :func:`math.ceil`, :func:`round`, and adds a new
591one, :func:`trunc`, that's been backported to Python 2.6.
592:func:`trunc` rounds toward zero, returning the closest
593:class:`Integral` that's between the function's argument and zero.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000594
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000595.. seealso::
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000596
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000597 XXX link: Discusses Scheme's numeric tower.
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000598
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +0000599
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000600
Mark Dickinsond058cd22008-02-10 21:29:51 +0000601The Fraction Module
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000602--------------------------------------------------
603
604To fill out the hierarchy of numeric types, a rational-number class
Mark Dickinsond058cd22008-02-10 21:29:51 +0000605has been added as the :mod:`fractions` module. Rational numbers are
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000606represented as a fraction; rational numbers can exactly represent
607numbers such as two-thirds that floating-point numbers can only
608approximate.
609
Mark Dickinsond058cd22008-02-10 21:29:51 +0000610The :class:`Fraction` constructor takes two :class:`Integral` values
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000611that will be the numerator and denominator of the resulting fraction. ::
612
Mark Dickinsond058cd22008-02-10 21:29:51 +0000613 >>> from fractions import Fraction
614 >>> a = Fraction(2, 3)
615 >>> b = Fraction(2, 5)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000616 >>> float(a), float(b)
617 (0.66666666666666663, 0.40000000000000002)
618 >>> a+b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000619 Fraction(16, 15)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000620 >>> a/b
Mark Dickinsoncd873fc2008-02-11 03:11:55 +0000621 Fraction(5, 3)
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000622
Mark Dickinsond058cd22008-02-10 21:29:51 +0000623The :mod:`fractions` module is based upon an implementation by Sjoerd
Andrew M. Kuchlingaa355542008-01-16 03:17:25 +0000624Mullender that was in Python's :file:`Demo/classes/` directory for a
625long time. This implementation was significantly updated by Jeffrey
626Yaskin.
627
628
Georg Brandl8ec7f652007-08-15 14:28:01 +0000629Other Language Changes
630======================
631
632Here are all of the changes that Python 2.6 makes to the core Python language.
633
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000634* When calling a function using the ``**`` syntax to provide keyword
635 arguments, you are no longer required to use a Python dictionary;
636 any mapping will now work::
637
638 >>> def f(**kw):
639 ... print sorted(kw)
640 ...
641 >>> ud=UserDict.UserDict()
642 >>> ud['a'] = 1
643 >>> ud['b'] = 'string'
644 >>> f(**ud)
645 ['a', 'b']
646
Georg Brandlb19be572007-12-29 10:57:00 +0000647 .. Patch 1686487
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000648
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000649* The built-in types now have improved support for extended slicing syntax,
650 where various combinations of ``(start, stop, step)`` are supplied.
651 Previously, the support was partial and certain corner cases wouldn't work.
652 (Implemented by Thomas Wouters.)
653
Georg Brandlb19be572007-12-29 10:57:00 +0000654 .. Revision 57619
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000655
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000656* Properties now have three attributes, :attr:`getter`,
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000657 :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000658 adding or modifying a getter, setter or deleter function to an
659 existing property. You would use them like this::
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000660
661 class C(object):
662 @property
663 def x(self):
664 return self._x
665
666 @x.setter
667 def x(self, value):
668 self._x = value
669
670 @x.deleter
671 def x(self):
672 del self._x
673
Christian Heimesff6cc6b2008-01-17 23:01:44 +0000674 class D(C):
675 @C.x.getter
676 def x(self):
677 return self._x * 2
678
679 @x.setter
680 def x(self, value):
681 self._x = value / 2
682
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000683
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000684* C functions and methods that use
685 :cfunc:`PyComplex_AsCComplex` will now accept arguments that
686 have a :meth:`__complex__` method. In particular, the functions in the
687 :mod:`cmath` module will now accept objects with this method.
688 This is a backport of a Python 3.0 change.
689 (Contributed by Mark Dickinson.)
690
Georg Brandlb19be572007-12-29 10:57:00 +0000691 .. Patch #1675423
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000692
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000693 A numerical nicety: when creating a complex number from two floats
694 on systems that support signed zeros (-0 and +0), the
695 :func:`complex()` constructor will now preserve the sign
696 of the zero.
697
Georg Brandlb19be572007-12-29 10:57:00 +0000698 .. Patch 1507
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000699
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000700* More floating-point features were also added. The :func:`float` function
701 will now turn the strings ``+nan`` and ``-nan`` into the corresponding
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000702 IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000703 positive or negative infinity. This works on any platform with
Christian Heimesd0d7d872008-01-04 02:03:25 +0000704 IEEE 754 semantics. (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +0000705
706 .. Patch 1635.
707
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000708 Other functions in the :mod:`math` module, :func:`isinf` and
709 :func:`isnan`, return true if their floating-point argument is
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000710 infinite or Not A Number.
711
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000712 .. Patch 1640
Georg Brandle1b8e9c2008-02-20 19:12:36 +0000713
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000714 The ``math.copysign(x, y)`` function
715 copies the sign bit of an IEEE 754 number, returning the absolute
716 value of *x* combined with the sign bit of *y*. For example,
717 ``math.copysign(1, -0.0)`` returns -1.0. (Contributed by Christian
718 Heimes.)
719
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000720* Changes to the :class:`Exception` interface
721 as dictated by :pep:`352` continue to be made. For 2.6,
722 the :attr:`message` attribute is being deprecated in favor of the
723 :attr:`args` attribute.
724
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000725* The :exc:`GeneratorExit` exception now subclasses
726 :exc:`BaseException` instead of :exc:`Exception`. This means
727 that an exception handler that does ``except Exception:``
728 will not inadvertently catch :exc:`GeneratorExit`.
729 (Contributed by Chad Austin.)
730
Georg Brandlb19be572007-12-29 10:57:00 +0000731 .. Patch #1537
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000732
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000733* The :func:`compile` built-in function now accepts keyword arguments
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000734 as well as positional parameters. (Contributed by Thomas Wouters.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000735
Georg Brandlb19be572007-12-29 10:57:00 +0000736 .. Patch 1444529
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000737
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000738* The :func:`complex` constructor now accepts strings containing
739 parenthesized complex numbers, letting ``complex(repr(cmplx))``
740 will now round-trip values. For example, ``complex('(3+4j)')``
741 now returns the value (3+4j).
742
Georg Brandlb19be572007-12-29 10:57:00 +0000743 .. Patch 1491866
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +0000744
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000745* The string :meth:`translate` method now accepts ``None`` as the
746 translation table parameter, which is treated as the identity
747 transformation. This makes it easier to carry out operations
748 that only delete characters. (Contributed by Bengt Richter.)
749
Georg Brandlb19be572007-12-29 10:57:00 +0000750 .. Patch 1193128
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000751
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000752* The built-in :func:`dir` function now checks for a :meth:`__dir__`
753 method on the objects it receives. This method must return a list
754 of strings containing the names of valid attributes for the object,
755 and lets the object control the value that :func:`dir` produces.
756 Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
Facundo Batistabd5b6232007-12-03 19:49:54 +0000757 methods can use this to advertise pseudo-attributes they will honor.
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000758
Georg Brandlb19be572007-12-29 10:57:00 +0000759 .. Patch 1591665
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000760
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761* An obscure change: when you use the the :func:`locals` function inside a
762 :keyword:`class` statement, the resulting dictionary no longer returns free
763 variables. (Free variables, in this case, are variables referred to in the
764 :keyword:`class` statement that aren't attributes of the class.)
765
Georg Brandlb19be572007-12-29 10:57:00 +0000766.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000767
768
769Optimizations
770-------------
771
Georg Brandlaf30b282008-01-15 06:55:56 +0000772* Type objects now have a cache of methods that can reduce
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000773 the amount of work required to find the correct method implementation
Andrew M. Kuchlinga01ed032008-01-15 01:55:32 +0000774 for a particular class; once cached, the interpreter doesn't need to
775 traverse base classes to figure out the right method to call.
776 The cache is cleared if a base class or the class itself is modified,
777 so the cache should remain correct even in the face of Python's dynamic
778 nature.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000779 (Original optimization implemented by Armin Rigo, updated for
780 Python 2.6 by Kevin Jacobs.)
781
782 .. % Patch 1700288
783
Andrew M. Kuchling3b554702008-01-04 02:31:40 +0000784* All of the functions in the :mod:`struct` module have been rewritten in
785 C, thanks to work at the Need For Speed sprint.
786 (Contributed by Raymond Hettinger.)
787
Georg Brandl8ec7f652007-08-15 14:28:01 +0000788* Internally, a bit is now set in type objects to indicate some of the standard
789 built-in types. This speeds up checking if an object is a subclass of one of
790 these types. (Contributed by Neal Norwitz.)
791
792The net result of the 2.6 optimizations is that Python 2.6 runs the pystone
793benchmark around XX% faster than Python 2.5.
794
Georg Brandlb19be572007-12-29 10:57:00 +0000795.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000796
797
798New, Improved, and Deprecated Modules
799=====================================
800
801As usual, Python's standard library received a number of enhancements and bug
802fixes. Here's a partial list of the most notable changes, sorted alphabetically
803by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
804complete list of changes, or look through the CVS logs for all the details.
805
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000806* The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
807 available, instead of restricting itself to protocol 1.
808 (Contributed by W. Barnes.)
809
Georg Brandlb19be572007-12-29 10:57:00 +0000810 .. Patch 1551443
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000811
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000812* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000813 fieldnames)` is a factory function that creates subclasses of the standard tuple
814 whose fields are accessible by name as well as index. For example::
815
Andrew M. Kuchling6d57c822007-10-23 20:55:47 +0000816 >>> var_type = collections.namedtuple('variable',
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000817 ... 'id name type size')
818 # Names are separated by spaces or commas.
819 # 'id, name, type, size' would also work.
Raymond Hettinger366523c2007-12-14 18:12:21 +0000820 >>> var_type._fields
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000821 ('id', 'name', 'type', 'size')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000823 >>> var = var_type(1, 'frequency', 'int', 4)
824 >>> print var[0], var.id # Equivalent
825 1 1
826 >>> print var[2], var.type # Equivalent
827 int int
Raymond Hettinger366523c2007-12-14 18:12:21 +0000828 >>> var._asdict()
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000829 {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
Raymond Hettingere9b9b352008-02-15 21:21:25 +0000830 >>> v2 = var._replace(name='amplitude')
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000831 >>> v2
832 variable(id=1, name='amplitude', type='int', size=4)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000833
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000834 Where the new :class:`namedtuple` type proved suitable, the standard
835 library has been modified to return them. For example,
836 the :meth:`Decimal.as_tuple` method now returns a named tuple with
837 :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
838
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839 (Contributed by Raymond Hettinger.)
840
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000841* Another change to the :mod:`collections` module is that the
Georg Brandle7d118a2007-12-08 11:05:05 +0000842 :class:`deque` type now supports an optional *maxlen* parameter;
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000843 if supplied, the deque's size will be restricted to no more
Georg Brandle7d118a2007-12-08 11:05:05 +0000844 than *maxlen* items. Adding more items to a full deque causes
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000845 old items to be discarded.
846
847 ::
848
849 >>> from collections import deque
850 >>> dq=deque(maxlen=3)
851 >>> dq
852 deque([], maxlen=3)
853 >>> dq.append(1) ; dq.append(2) ; dq.append(3)
854 >>> dq
855 deque([1, 2, 3], maxlen=3)
856 >>> dq.append(4)
857 >>> dq
858 deque([2, 3, 4], maxlen=3)
859
860 (Contributed by Raymond Hettinger.)
861
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000862* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
863 that represents the C99 ``bool`` type. (Contributed by David Remahl.)
864
Georg Brandlb19be572007-12-29 10:57:00 +0000865 .. Patch 1649190
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000866
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000867 The :mod:`ctypes` string, buffer and array types also have improved
868 support for extended slicing syntax,
869 where various combinations of ``(start, stop, step)`` are supplied.
870 (Implemented by Thomas Wouters.)
871
Georg Brandlb19be572007-12-29 10:57:00 +0000872 .. Revision 57769
Andrew M. Kuchling6edff592007-10-16 22:58:03 +0000873
Georg Brandl8ec7f652007-08-15 14:28:01 +0000874* A new method in the :mod:`curses` module: for a window, :meth:`chgat` changes
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000875 the display characters for a certain number of characters on a single line.
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +0000876 (Contributed by Fabian Kreutz.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000877 ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000878
879 # Boldface text starting at y=0,x=21
880 # and affecting the rest of the line.
881 stdscr.chgat(0,21, curses.A_BOLD)
882
Andrew M. Kuchling4a2762d2008-01-20 00:00:38 +0000883 The :class:`Textbox` class in the :mod:`curses.textpad` module
884 now supports editing in insert mode as well as overwrite mode.
885 Insert mode is enabled by supplying a true value for the *insert_mode*
886 parameter when creating the :class:`Textbox` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000887
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000888* The :mod:`decimal` module was updated to version 1.66 of
889 `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__. New features
890 include some methods for some basic mathematical functions such as
891 :meth:`exp` and :meth:`log10`::
892
893 >>> Decimal(1).exp()
894 Decimal("2.718281828459045235360287471")
895 >>> Decimal("2.7182818").ln()
896 Decimal("0.9999999895305022877376682436")
897 >>> Decimal(1000).log10()
898 Decimal("3")
899
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000900 The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
901 named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
902
903 (Implemented by Facundo Batista and Mark Dickinson. Named tuple
904 support added by Raymond Hettinger.)
905
906* The :mod:`difflib` module's :class:`SequenceMatcher` class
907 now returns named tuples representing matches.
908 In addition to behaving like tuples, the returned values
909 also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
910 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000911
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000912* An optional ``timeout`` parameter was added to the
913 :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
914 method, specifying a timeout measured in seconds. (Added by Facundo
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +0000915 Batista.) Also, the :class:`FTP` class's
916 :meth:`storbinary` and :meth:`storlines`
917 now take an optional *callback* parameter that will be called with
918 each block of data after the data has been sent.
919 (Contributed by Phil Schwartz.)
920
921 .. Patch 1221598
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +0000922
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000923* The :func:`reduce` built-in function is also available in the
924 :mod:`functools` module. In Python 3.0, the built-in is dropped and it's
925 only available from :mod:`functools`; currently there are no plans
926 to drop the built-in in the 2.x series. (Patched by
927 Christian Heimes.)
928
Georg Brandlb19be572007-12-29 10:57:00 +0000929 .. Patch 1739906
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000930
Georg Brandl8ec7f652007-08-15 14:28:01 +0000931* The :func:`glob.glob` function can now return Unicode filenames if
932 a Unicode path was used and Unicode filenames are matched within the directory.
933
Georg Brandlb19be572007-12-29 10:57:00 +0000934 .. Patch #1001604
Georg Brandl8ec7f652007-08-15 14:28:01 +0000935
936* The :mod:`gopherlib` module has been removed.
937
938* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
939 takes any number of iterables that return data *in sorted order*, and returns
940 a new iterator that returns the contents of all the iterators, also in sorted
941 order. For example::
942
943 heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
944 [1, 2, 3, 5, 8, 9, 16]
945
946 (Contributed by Raymond Hettinger.)
947
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000948* An optional ``timeout`` parameter was added to the
949 :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
950 class constructors, specifying a timeout measured in seconds.
951 (Added by Facundo Batista.)
952
Andrew M. Kuchling2e463552008-01-15 01:47:32 +0000953* Most of the :mod:`inspect` module's functions, such as
954 :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
955 In addition to behaving like tuples, the elements of the return value
956 can also be accessed as attributes.
957 (Contributed by Raymond Hettinger.)
958
Georg Brandl8ec7f652007-08-15 14:28:01 +0000959* A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2,
960 ...[, fillvalue])`` makes tuples from each of the elements; if some of the
961 iterables are shorter than others, the missing values are set to *fillvalue*.
962 For example::
963
964 itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
965 [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
966
967 (Contributed by Raymond Hettinger.)
968
969* The :mod:`macfs` module has been removed. This in turn required the
970 :func:`macostools.touched` function to be removed because it depended on the
971 :mod:`macfs` module.
972
Georg Brandlb19be572007-12-29 10:57:00 +0000973 .. Patch #1490190
Georg Brandl8ec7f652007-08-15 14:28:01 +0000974
Andrew M. Kuchling2686f4d2008-01-19 19:14:05 +0000975* :class:`mmap` objects now have a :meth:`rfind` method that finds
976 a substring, beginning at the end of the string and searching
977 backwards. The :meth:`find` method
978 also gained a *end* parameter containing the index at which to stop
979 the forward search.
980 (Contributed by John Lenton.)
981
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +0000982* The :mod:`new` module has been removed from Python 3.0.
983 Importing it therefore
984 triggers a warning message when Python is running in 3.0-warning
985 mode.
986
987* New functions in the :mod:`os` module include
988 ``fchmod(fd, mode)``, ``fchown(fd, uid, gid)``,
989 and ``lchmod(path, mode)``, on operating systems that support these
990 functions. :func:`fchmod` and :func:`fchown` let you change the mode
991 and ownership of an opened file, and :func:`lchmod` changes the mode
992 of a symlink.
993
994 (Contributed by Georg Brandl and Christian Heimes.)
995
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +0000996* The :func:`os.walk` function now has a ``followlinks`` parameter. If
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +0000997 set to True, it will follow symlinks pointing to directories and
998 visit the directory's contents. For backward compatibility, the
999 parameter's default value is false. Note that the function can fall
1000 into an infinite recursion if there's a symlink that points to a
1001 parent directory.
1002
Georg Brandlb19be572007-12-29 10:57:00 +00001003 .. Patch 1273829
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001004
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001005* The ``os.environ`` object's :meth:`clear` method will now unset the
1006 environment variables using :func:`os.unsetenv` in addition to clearing
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001007 the object's keys. (Contributed by Martin Horcicka.)
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001008
Georg Brandlb19be572007-12-29 10:57:00 +00001009 .. Patch #1181
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001010
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001011* In the :mod:`os.path` module, the :func:`splitext` function
1012 has been changed to not split on leading period characters.
1013 This produces better results when operating on Unix's dot-files.
1014 For example, ``os.path.splitext('.ipython')``
1015 now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
1016
Georg Brandlb19be572007-12-29 10:57:00 +00001017 .. Bug #115886
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001018
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001019 A new function, :func:`relpath(path, start)` returns a relative path
1020 from the ``start`` path, if it's supplied, or from the current
1021 working directory to the destination ``path``. (Contributed by
1022 Richard Barran.)
1023
Georg Brandlb19be572007-12-29 10:57:00 +00001024 .. Patch 1339796
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001025
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001026 On Windows, :func:`os.path.expandvars` will now expand environment variables
1027 in the form "%var%", and "~user" will be expanded into the
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001028 user's home directory path. (Contributed by Josiah Carlson.)
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001029
Georg Brandlb19be572007-12-29 10:57:00 +00001030 .. Patch 957650
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001031
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001032* The Python debugger provided by the :mod:`pdb` module
1033 gained a new command: "run" restarts the Python program being debugged,
1034 and can optionally take new command-line arguments for the program.
1035 (Contributed by Rocky Bernstein.)
1036
Georg Brandlb19be572007-12-29 10:57:00 +00001037 .. Patch #1393667
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001038
Georg Brandl8ec7f652007-08-15 14:28:01 +00001039* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
1040 are wrappers for the corresponding system calls (where they're available).
1041 Constants for the flag values are defined in the :mod:`stat` module; some
1042 possible values include :const:`UF_IMMUTABLE` to signal the file may not be
1043 changed and :const:`UF_APPEND` to indicate that data can only be appended to the
1044 file. (Contributed by M. Levinson.)
1045
Andrew M. Kuchlinge0a49b62008-01-08 14:30:55 +00001046* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
1047 their :attr:`buffer_size` attribute to change the size of the buffer
1048 used to hold character data.
1049 (Contributed by Achim Gaedke.)
1050
1051 .. Patch 1137
1052
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001053* The :mod:`Queue` module now provides queue classes that retrieve entries
1054 in different orders. The :class:`PriorityQueue` class stores
1055 queued items in a heap and retrieves them in priority order,
1056 and :class:`LifoQueue` retrieves the most recently added entries first,
1057 meaning that it behaves like a stack.
1058 (Contributed by Raymond Hettinger.)
1059
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001060* The :mod:`random` module's :class:`Random` objects can
1061 now be pickled on a 32-bit system and unpickled on a 64-bit
1062 system, and vice versa. Unfortunately, this change also means
1063 that Python 2.6's :class:`Random` objects can't be unpickled correctly
1064 on earlier versions of Python.
1065 (Contributed by Shawn Ligocki.)
1066
Georg Brandlb19be572007-12-29 10:57:00 +00001067 .. Issue 1727780
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001068
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001069* Long regular expression searches carried out by the :mod:`re`
1070 module will now check for signals being delivered, so especially
1071 long searches can now be interrupted.
1072 (Contributed by Josh Hoyt and Ralf Schmitt.)
1073
1074 .. % Patch 846388
1075
Georg Brandl8ec7f652007-08-15 14:28:01 +00001076* The :mod:`rgbimg` module has been removed.
1077
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001078* The :mod:`sets` module has been deprecated; it's better to
1079 use the built-in :class:`set` and :class:`frozenset` types.
1080
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001081* Integrating signal handling with GUI handling event loops
1082 like those used by Tkinter or GTk+ has long been a problem; most
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001083 software ends up polling, waking up every fraction of a second.
Andrew M. Kuchling2d60cf72007-12-22 17:27:02 +00001084 The :mod:`signal` module can now make this more efficient.
1085 Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
1086 to be used; when a signal is received, a byte is written to that
1087 file descriptor. There's also a C-level function,
1088 :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
1089
1090 Event loops will use this by opening a pipe to create two descriptors,
1091 one for reading and one for writing. The writeable descriptor
1092 will be passed to :func:`set_wakeup_fd`, and the readable descriptor
1093 will be added to the list of descriptors monitored by the event loop via
1094 :cfunc:`select` or :cfunc:`poll`.
1095 On receiving a signal, a byte will be written and the main event loop
1096 will be woken up, without the need to poll.
1097
1098 Contributed by Adam Olsen.
1099
1100 .. % Patch 1583
1101
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001102* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
1103 addition of the :class:`SMTP_SSL` class. This class supports an
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001104 interface identical to the existing :class:`SMTP` class. Both
1105 class constructors also have an optional ``timeout`` parameter
1106 that specifies a timeout for the initial connection attempt, measured in
1107 seconds.
1108
1109 An implementation of the LMTP protocol (:rfc:`2033`) was also added to
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001110 the module. LMTP is used in place of SMTP when transferring e-mail
1111 between agents that don't manage a mail queue.
Andrew M. Kuchlingb4c62952007-09-01 21:18:31 +00001112
1113 (SMTP over SSL contributed by Monty Taylor; timeout parameter
1114 added by Facundo Batista; LMTP implemented by Leif
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001115 Hedstrom.)
1116
Georg Brandlb19be572007-12-29 10:57:00 +00001117 .. Patch #957003
Georg Brandl8ec7f652007-08-15 14:28:01 +00001118
Gregory P. Smith63bfc1d2008-01-17 07:43:20 +00001119* In the :mod:`smtplib` module, SMTP.starttls() now complies with :rfc:`3207`
1120 and forgets any knowledge obtained from the server not obtained from
1121 the TLS negotiation itself. Patch contributed by Bill Fenner.
1122
1123 .. Issue 829951
1124
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001125* The :mod:`socket` module now supports TIPC (http://tipc.sf.net),
1126 a high-performance non-IP-based protocol designed for use in clustered
1127 environments. TIPC addresses are 4- or 5-tuples.
1128 (Contributed by Alberto Bertogli.)
1129
1130 .. Patch #1646
Andrew M. Kuchlingf60b6412008-01-19 16:34:09 +00001131
1132* The base classes in the :mod:`SocketServer` module now support
1133 calling a :meth:`handle_timeout` method after a span of inactivity
1134 specified by the server's :attr:`timeout` attribute. (Contributed
1135 by Michael Pomraning.)
1136
1137 .. Patch #742598
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001138
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001139* A new variable in the :mod:`sys` module,
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001140 :attr:`float_info`, is an object
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001141 containing information about the platform's floating-point support
Andrew M. Kuchling5d8b3792008-01-14 14:48:43 +00001142 derived from the :file:`float.h` file. Attributes of this object
1143 include
1144 :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001145 (smallest difference between 1.0 and the next largest value
1146 representable), and several others. (Contributed by Christian Heimes.)
1147
Georg Brandlb19be572007-12-29 10:57:00 +00001148 .. Patch 1534
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001149
Andrew M. Kuchling7b1e9172008-01-15 14:38:05 +00001150 Another new variable, :attr:`dont_write_bytecode`, controls whether Python
1151 writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
1152 If this variable is true, the compiled files are not written. The
1153 variable is initially set on start-up by supplying the :option:`-B`
1154 switch to the Python interpreter, or by setting the
1155 :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
1156 running the interpreter. Python code can subsequently
1157 change the value of this variable to control whether bytecode files
1158 are written or not.
1159 (Contributed by Neal Norwitz and Georg Brandl.)
1160
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001161 Information about the command-line arguments supplied to the Python
1162 interpreter are available as attributes of a ``sys.flags`` named
1163 tuple. For example, the :attr:`verbose` attribute is true if Python
1164 was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
1165 These attributes are all read-only.
1166 (Contributed by Christian Heimes.)
1167
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001168* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
1169 POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
1170 format that was already supported. The default format
1171 is GNU tar; specify the ``format`` parameter to open a file
1172 using a different format::
1173
1174 tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT)
1175
1176 The new ``errors`` parameter lets you specify an error handling
1177 scheme for character conversions: the three standard ways Python can
1178 handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the
1179 special value ``'utf-8'``, which replaces bad characters with their
1180 UTF-8 representation. Character conversions occur because the PAX
1181 format supports Unicode filenames, defaulting to UTF-8 encoding.
1182
1183 The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
1184 a function that can be used to exclude certain filenames from
1185 an archive.
1186 The function must take a filename and return true if the file
1187 should be excluded or false if it should be archived.
1188 The function is applied to both the name initially passed to :meth:`add`
1189 and to the names of files in recursively-added directories.
1190
1191 (All changes contributed by Lars Gustäbel).
1192
1193* An optional ``timeout`` parameter was added to the
1194 :class:`telnetlib.Telnet` class constructor, specifying a timeout
1195 measured in seconds. (Added by Facundo Batista.)
1196
1197* The :class:`tempfile.NamedTemporaryFile` class usually deletes
1198 the temporary file it created when the file is closed. This
1199 behaviour can now be changed by passing ``delete=False`` to the
1200 constructor. (Contributed by Damien Miller.)
1201
Georg Brandlb19be572007-12-29 10:57:00 +00001202 .. Patch #1537850
Andrew M. Kuchlingde37a8c2007-09-18 01:36:16 +00001203
1204* The :mod:`test.test_support` module now contains a
1205 :func:`EnvironmentVarGuard`
1206 context manager that supports temporarily changing environment variables and
1207 automatically restores them to their old values.
1208
1209 Another context manager, :class:`TransientResource`, can surround calls
1210 to resources that may or may not be available; it will catch and
1211 ignore a specified list of exceptions. For example,
1212 a network test may ignore certain failures when connecting to an
1213 external web site::
1214
1215 with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
1216 f = urllib.urlopen('https://sf.net')
1217 ...
1218
1219 (Contributed by Brett Cannon.)
1220
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001221* The :mod:`textwrap` module can now preserve existing whitespace
1222 at the beginnings and ends of the newly-created lines
1223 by specifying ``drop_whitespace=False``
1224 as an argument::
1225
1226 >>> S = """This sentence has a bunch of extra whitespace."""
1227 >>> print textwrap.fill(S, width=15)
1228 This sentence
1229 has a bunch
1230 of extra
1231 whitespace.
1232 >>> print textwrap.fill(S, drop_whitespace=False, width=15)
1233 This sentence
1234 has a bunch
1235 of extra
1236 whitespace.
1237 >>>
1238
Georg Brandlb19be572007-12-29 10:57:00 +00001239 .. Patch #1581073
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001240
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001241* The :mod:`timeit` module now accepts callables as well as strings
1242 for the statement being timed and for the setup code.
1243 Two convenience functions were added for creating
1244 :class:`Timer` instances:
1245 ``repeat(stmt, setup, time, repeat, number)`` and
1246 ``timeit(stmt, setup, time, number)`` create an instance and call
1247 the corresponding method. (Contributed by Erik Demaine.)
1248
Georg Brandlb19be572007-12-29 10:57:00 +00001249 .. Patch #1533909
Andrew M. Kuchling6c066dd2007-09-01 20:43:36 +00001250
Andrew M. Kuchlingf10878b2007-09-13 22:49:34 +00001251* An optional ``timeout`` parameter was added to the
1252 :func:`urllib.urlopen` function and the
1253 :class:`urllib.ftpwrapper` class constructor, as well as the
1254 :func:`urllib2.urlopen` function. The parameter specifies a timeout
1255 measured in seconds. For example::
1256
1257 >>> u = urllib2.urlopen("http://slow.example.com", timeout=3)
1258 Traceback (most recent call last):
1259 ...
1260 urllib2.URLError: <urlopen error timed out>
1261 >>>
1262
1263 (Added by Facundo Batista.)
1264
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001265* The XML-RPC classes :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001266 classes can now be prevented from immediately opening and binding to
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001267 their socket by passing True as the ``bind_and_activate``
1268 constructor parameter. This can be used to modify the instance's
1269 :attr:`allow_reuse_address` attribute before calling the
1270 :meth:`server_bind` and :meth:`server_activate` methods to
1271 open the socket and begin listening for connections.
1272 (Contributed by Peter Parente.)
1273
Georg Brandlb19be572007-12-29 10:57:00 +00001274 .. Patch 1599845
Andrew M. Kuchling99479eb2007-09-25 00:09:42 +00001275
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001276 :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
1277 attribute; if true, the exception and formatted traceback are returned
1278 as HTTP headers "X-Exception" and "X-Traceback". This feature is
1279 for debugging purposes only and should not be used on production servers
1280 because the tracebacks could possibly reveal passwords or other sensitive
1281 information. (Contributed by Alan McIntyre as part of his
1282 project for Google's Summer of Code 2007.)
1283
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001284* The :mod:`zipfile` module's :class:`ZipFile` class now has
1285 :meth:`extract` and :meth:`extractall` methods that will unpack
1286 a single file or all the files in the archive to the current directory, or
1287 to a specified directory::
1288
1289 z = zipfile.ZipFile('python-251.zip')
1290
1291 # Unpack a single file, writing it relative to the /tmp directory.
1292 z.extract('Python/sysmodule.c', '/tmp')
1293
1294 # Unpack all the files in the archive.
1295 z.extractall()
1296
1297 (Contributed by Alan McIntyre.)
Georg Brandle1b8e9c2008-02-20 19:12:36 +00001298
1299 .. Patch 467924
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001300
Georg Brandlb19be572007-12-29 10:57:00 +00001301.. ======================================================================
1302.. whole new modules get described in subsections here
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001303
1304Improved SSL Support
Andrew M. Kuchling27a44982007-10-20 19:39:35 +00001305--------------------------------------------------
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001306
1307Bill Janssen made extensive improvements to Python 2.6's support for
1308SSL.
1309
1310XXX use ssl.sslsocket - subclass of socket.socket.
1311
1312XXX Can specify if certificate is required, and obtain certificate info
1313by calling getpeercert method.
1314
1315XXX sslwrap() behaves like socket.ssl
1316
1317XXX Certain features require the OpenSSL package to be installed, notably
1318 the 'openssl' binary.
1319
1320.. seealso::
1321
1322 SSL module documentation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001323
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001324
1325.. ======================================================================
1326
1327plistlib: A Property-List Parser
1328--------------------------------------------------
1329
1330A commonly-used format on MacOS X is the ``.plist`` format,
1331which stores basic data types (numbers, strings, lists,
1332and dictionaries) and serializes them into an XML-based format.
1333(It's a lot like the XML-RPC serialization of data types.)
1334
1335Despite being primarily used on MacOS X, the format
1336has nothing Mac-specific about it and the Python implementation works
1337on any platform that Python supports, so the :mod:`plistlib` module
1338has been promoted to the standard library.
1339
1340Using the module is simple::
1341
1342 import sys
1343 import plistlib
1344 import datetime
1345
1346 # Create data structure
1347 data_struct = dict(lastAccessed=datetime.datetime.now(),
1348 version=1,
1349 categories=('Personal', 'Shared', 'Private'))
1350
1351 # Create string containing XML.
1352 plist_str = plistlib.writePlistToString(data_struct)
1353 new_struct = plistlib.readPlistFromString(plist_str)
1354 print data_struct
1355 print new_struct
1356
1357 # Write data structure to a file and read it back.
1358 plistlib.writePlist(data_struct, '/tmp/customizations.plist')
1359 new_struct = plistlib.readPlist('/tmp/customizations.plist')
1360
1361 # read/writePlist accepts file-like objects as well as paths.
1362 plistlib.writePlist(data_struct, sys.stdout)
1363
1364
Georg Brandlb19be572007-12-29 10:57:00 +00001365.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001366
1367
1368Build and C API Changes
1369=======================
1370
1371Changes to Python's build process and to the C API include:
1372
Andrew M. Kuchlingf7b462f2007-11-23 13:37:39 +00001373* Python 2.6 can be built with Microsoft Visual Studio 2008.
1374 See the :file:`PCbuild9` directory for the build files.
1375 (Implemented by Christian Heimes.)
1376
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001377* The BerkeleyDB module now has a C API object, available as
1378 ``bsddb.db.api``. This object can be used by other C extensions
1379 that wish to use the :mod:`bsddb` module for their own purposes.
1380 (Contributed by Duncan Grisby.)
1381
Georg Brandlb19be572007-12-29 10:57:00 +00001382 .. Patch 1551895
Andrew M. Kuchling6edff592007-10-16 22:58:03 +00001383
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001384* Several functions return information about the platform's
1385 floating-point support. :cfunc:`PyFloat_GetMax` returns
1386 the maximum representable floating point value,
1387 and :cfunc:`PyFloat_GetMin` returns the minimum
1388 positive value. :cfunc:`PyFloat_GetInfo` returns a dictionary
1389 containing more information from the :file:`float.h` file, such as
1390 ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
1391 (smallest difference between 1.0 and the next largest value
1392 representable), and several others.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001393 (Contributed by Christian Heimes.)
Andrew M. Kuchlingd5865592007-12-19 02:02:04 +00001394
Georg Brandlb19be572007-12-29 10:57:00 +00001395 .. Issue 1534
Georg Brandl8ec7f652007-08-15 14:28:01 +00001396
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001397* Python's C API now includes two functions for case-insensitive string
Georg Brandl907a7202008-02-22 12:31:45 +00001398 comparisons, ``PyOS_stricmp(char*, char*)``
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001399 and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
Christian Heimesd0d7d872008-01-04 02:03:25 +00001400 (Contributed by Christian Heimes.)
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001401
1402 .. Issue 1635
1403
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001404* Some macros were renamed to make it clearer that they are macros,
1405 not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001406 :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
1407 :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. Macros for backward
Christian Heimesd0d7d872008-01-04 02:03:25 +00001408 compatibility are still available for Python 2.6.
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001409
Andrew M. Kuchling3b554702008-01-04 02:31:40 +00001410 .. Issue 1629
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001411
Andrew M. Kuchling0c3f1682008-01-26 13:50:51 +00001412* Distutils now places C extensions it builds in a
1413 different directory when running on a debug version of Python.
1414 (Contributed by Collin Winter.)
1415
1416 .. Patch 1530959
1417
1418
Georg Brandlb19be572007-12-29 10:57:00 +00001419.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001420
1421
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001422Port-Specific Changes: Windows
1423-----------------------------------
1424
1425* The :mod:`msvcrt` module now supports
1426 both the normal and wide char variants of the console I/O
1427 API. The :func:`getwch` function reads a keypress and returns a Unicode
1428 value, as does the :func:`getwche` function. The :func:`putwch` function
1429 takes a Unicode character and writes it to the console.
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001430 (Contributed by Christian Heimes.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001431
Andrew M. Kuchlingd2219562008-01-17 12:00:15 +00001432* :func:`os.path.expandvars` will now expand environment variables
1433 in the form "%var%", and "~user" will be expanded into the
1434 user's home directory path. (Contributed by Josiah Carlson.)
1435
1436* The :mod:`socket` module's socket objects now have an
1437 :meth:`ioctl` method that provides a limited interface to the
1438 :cfunc:`WSAIoctl` system interface.
1439
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001440* The :mod:`_winreg` module now has a function,
1441 :func:`ExpandEnvironmentStrings`,
1442 that expands environment variable references such as ``%NAME%``
1443 in an input string. The handle objects provided by this
1444 module now support the context protocol, so they can be used
Christian Heimesff6cc6b2008-01-17 23:01:44 +00001445 in :keyword:`with` statements. (Contributed by Christian Heimes.)
1446
1447* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
1448 build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
1449 were moved into the PC/ directory. The new PCbuild directory supports
1450 cross compilation for X64, debug builds and Profile Guided Optimization
1451 (PGO). PGO builds are roughly 10% faster than normal builds.
1452 (Contributed by Christian Heimes with help from Amaury Forgeot d'Arc and
1453 Martin von Loewis.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001454
Georg Brandlb19be572007-12-29 10:57:00 +00001455.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001456
1457
1458.. _section-other:
1459
1460Other Changes and Fixes
1461=======================
1462
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001463As usual, there were a bunch of other improvements and bugfixes
1464scattered throughout the source tree. A search through the change
1465logs finds there were XXX patches applied and YYY bugs fixed between
1466Python 2.5 and 2.6. Both figures are likely to be underestimates.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001467
1468Some of the more notable changes are:
1469
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001470* It's now possible to prevent Python from writing any :file:`.pyc`
1471 or :file:`.pyo` files by either supplying the :option:`-B` switch
1472 or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
1473 to any non-empty string when running the Python interpreter. These
Georg Brandlca9c6e42008-01-15 06:58:15 +00001474 are also used to set the :data:`sys.dont_write_bytecode` attribute;
1475 Python code can change this variable to control whether bytecode
1476 files are subsequently written.
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001477 (Contributed by Neal Norwitz and Georg Brandl.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001478
Georg Brandlb19be572007-12-29 10:57:00 +00001479.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001480
1481
1482Porting to Python 2.6
1483=====================
1484
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001485This section lists previously described changes, and a few
1486esoteric bugfixes, that may require changes to your
Georg Brandl8ec7f652007-08-15 14:28:01 +00001487code:
1488
Andrew M. Kuchling73835bd2008-01-04 18:24:41 +00001489* The :meth:`__init__` method of :class:`collections.deque`
Andrew M. Kuchling654ede72008-01-04 01:16:12 +00001490 now clears any existing contents of the deque
1491 before adding elements from the iterable. This change makes the
1492 behavior match that of ``list.__init__()``.
1493
Andrew M. Kuchling2e463552008-01-15 01:47:32 +00001494* The :class:`Decimal` constructor now accepts leading and trailing
1495 whitespace when passed a string. Previously it would raise an
1496 :exc:`InvalidOperation` exception. On the other hand, the
1497 :meth:`create_decimal` method of :class:`Context` objects now
1498 explicitly disallows extra whitespace, raising a
1499 :exc:`ConversionSyntax` exception.
1500
1501* Due to an implementation accident, if you passed a file path to
1502 the built-in :func:`__import__` function, it would actually import
1503 the specified file. This was never intended to work, however, and
1504 the implementation now explicitly checks for this case and raises
1505 an :exc:`ImportError`.
1506
Andrew M. Kuchlinge34d2892007-10-20 19:35:18 +00001507* The :mod:`socket` module exception :exc:`socket.error` now inherits
1508 from :exc:`IOError`. Previously it wasn't a subclass of
1509 :exc:`StandardError` but now it is, through :exc:`IOError`.
1510 (Implemented by Gregory P. Smith.)
1511
Georg Brandlb19be572007-12-29 10:57:00 +00001512 .. Issue 1706815
Georg Brandl8ec7f652007-08-15 14:28:01 +00001513
Georg Brandlb19be572007-12-29 10:57:00 +00001514.. ======================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001515
1516
1517.. _acks:
1518
1519Acknowledgements
1520================
1521
1522The author would like to thank the following people for offering suggestions,
1523corrections and assistance with various drafts of this article: .
1524