rest25/whatsnew/2.1.rst => rest262/whatsnew/2.1.rst
f1****************************
n2-  What's New in Python 2.1  
n2+  What's New in Python 2.1
3****************************
4
5:Author: A.M. Kuchling
6
7.. |release| replace:: 1.01
8
n9-.. % $Id: whatsnew21.tex 50964 2006-07-30 03:03:43Z fred.drake $
n9+.. $Id: whatsnew21.tex 50964 2006-07-30 03:03:43Z fred.drake $
10
11
12Introduction
13============
14
15This article explains the new features in Python 2.1.  While there aren't as
16many changes in 2.1 as there were in Python 2.0, there are still some pleasant
17surprises in store.  2.1 is the first release to be steered through the use of
24
25One recent goal of the Python development team has been to accelerate the pace
26of new releases, with a new release coming every 6 to 9 months. 2.1 is the first
27release to come out at this faster pace, with the first alpha appearing in
28January, 3 months after the final version of 2.0 was released.
29
30The final release of Python 2.1 was made on April 17, 2001.
31
n32-.. % ======================================================================
n32+.. ======================================================================
33
34
35PEP 227: Nested Scopes
36======================
37
38The largest change in Python 2.1 is to Python's scoping rules.  In Python 2.0,
39at any given time there are at most three namespaces used to look up variable
40names: local, module-level, and the built-in namespace.  This often surprised
93definitions or :keyword:`lambda` expressions with free variables, the compiler
94will flag this by raising a :exc:`SyntaxError` exception.
95
96To make the preceding explanation a bit clearer, here's an example::
97
98   x = 1
99   def f():
100       # The next line is a syntax error
n101-       exec 'x=2'  
n101+       exec 'x=2'
102       def g():
103           return x
104
105Line 4 containing the :keyword:`exec` statement is a syntax error, since
106:keyword:`exec` would define a new local variable named ``x`` whose value should
107be accessed by :func:`g`.
108
109This shouldn't be much of a limitation, since :keyword:`exec` is rarely used in
118all of 2.1's lifetime to fix any breakage resulting from their introduction.
119
120
121.. seealso::
122
123   :pep:`227` - Statically Nested Scopes
124      Written and implemented by Jeremy Hylton.
125
n126-.. % ======================================================================
n126+.. ======================================================================
127
128
129PEP 236: __future__ Directives
130==============================
131
132The reaction to nested scopes was widespread concern about the dangers of
133breaking code with the 2.1 release, and it was strong enough to make the
134Pythoneers take a more conservative approach.  This approach consists of
148precede any statement that will result in bytecodes being produced.
149
150
151.. seealso::
152
153   :pep:`236` - Back to the :mod:`__future__`
154      Written by Tim Peters, and primarily implemented by Jeremy Hylton.
155
n156-.. % ======================================================================
n156+.. ======================================================================
157
158
159PEP 207: Rich Comparisons
160=========================
161
162In earlier versions, Python's support for implementing comparisons on user-
163defined classes and extension types was quite simple. Classes could implement a
164:meth:`__cmp__` method that was given two instances of a class, and could only
218
219
220.. seealso::
221
222   :pep:`207` - Rich Comparisions
223      Written by Guido van Rossum, heavily based on earlier work by David Ascher, and
224      implemented by Guido van Rossum.
225
n226-.. % ======================================================================
n226+.. ======================================================================
227
228
229PEP 230: Warning Framework
230==========================
231
232Over its 10 years of existence, Python has accumulated a certain number of
233obsolete modules and features along the way.  It's difficult to know when a
234feature is safe to remove, since there's no way of knowing how much code uses it
290      Written by Paul Prescod, to specify procedures to be followed when removing old
291      features from Python.  The policy described in this PEP hasn't been officially
292      adopted, but the eventual policy probably won't be too different from Prescod's
293      proposal.
294
295   :pep:`230` - Warning Framework
296      Written and implemented by Guido van Rossum.
297
n298-.. % ======================================================================
n298+.. ======================================================================
299
300
301PEP 229: New Build System
302=========================
303
304When compiling Python, the user had to go in and edit the :file:`Modules/Setup`
305file in order to enable various additional modules; the default set is
306relatively small and limited to modules that compile on most Unix platforms.
330simpler.
331
332
333.. seealso::
334
335   :pep:`229` - Using Distutils to Build Python
336      Written and implemented by A.M. Kuchling.
337
n338-.. % ======================================================================
n338+.. ======================================================================
339
340
341PEP 205: Weak References
342========================
343
344Weak references, available through the :mod:`weakref` module, are a minor but
345useful new data type in the Python programmer's toolbox.
346
411   proxy.attr   # raises weakref.ReferenceError
412
413
414.. seealso::
415
416   :pep:`205` - Weak References
417      Written and implemented by Fred L. Drake, Jr.
418
n419-.. % ======================================================================
n419+.. ======================================================================
420
421
422PEP 232: Function Attributes
423============================
424
425In Python 2.1, functions can now have arbitrary information attached to them.
426People were often using docstrings to hold information about functions and
427methods, because the ``__doc__`` attribute was the only way of attaching any
449that behaves like a mapping.
450
451
452.. seealso::
453
454   :pep:`232` - Function Attributes
455      Written and implemented by Barry Warsaw.
456
n457-.. % ======================================================================
n457+.. ======================================================================
458
459
460PEP 235: Importing Modules on Case-Insensitive Platforms
461========================================================
462
463Some operating systems have filesystems that are case-insensitive, MacOS and
464Windows being the primary examples; on these systems, it's impossible to
465distinguish the filenames ``FILE.PY`` and ``file.py``, even though they do store
467
468In Python 2.1, the :keyword:`import` statement will work to simulate case-
469sensitivity on case-insensitive platforms.  Python will now search for the first
470case-sensitive match by default, raising an :exc:`ImportError` if no such file
471is found, so ``import file`` will not import a module named ``FILE.PY``.  Case-
472insensitive matching can be requested by setting the :envvar:`PYTHONCASEOK`
473environment variable before starting the Python interpreter.
474
n475-.. % ======================================================================
n475+.. ======================================================================
476
477
478PEP 217: Interactive Display Hook
479=================================
480
481When using the Python interpreter interactively, the output of commands is
482displayed using the built-in :func:`repr` function. In Python 2.1, the variable
483:func:`sys.displayhook` can be set to a callable object which will be called
497   >>>
498
499
500.. seealso::
501
502   :pep:`217` - Display Hook for Interactive Use
503      Written and implemented by Moshe Zadka.
504
n505-.. % ======================================================================
n505+.. ======================================================================
506
507
508PEP 208: New Coercion Model
509===========================
510
511How numeric coercion is done at the C level was significantly modified.  This
512will only affect the authors of C extensions to Python, allowing them more
513flexibility in writing extension types that support numeric operations.
529
530.. seealso::
531
532   :pep:`208` - Reworking the Coercion Model
533      Written and implemented by Neil Schemenauer, heavily based upon earlier work by
534      Marc-AndrĂ© Lemburg.  Read this to understand the fine points of how numeric
535      operations will now be processed at the C level.
536
n537-.. % ======================================================================
n537+.. ======================================================================
538
539
540PEP 241: Metadata in Python Packages
541====================================
542
543A common complaint from Python users is that there's no single catalog of all
544the Python modules in existence.  T. Middleton's Vaults of Parnassus at
n545-`<http://www.vex.net/parnassus/>`_ are the largest catalog of Python modules,
n545+http://www.vex.net/parnassus/ are the largest catalog of Python modules, but
546-but registering software at the Vaults is optional, and many people don't
546+registering software at the Vaults is optional, and many people don't bother.
547-bother.
548
549As a first small step toward fixing the problem, Python software packaged using
550the Distutils :command:`sdist` command will include a file named
551:file:`PKG-INFO` containing information about the package such as its name,
552version, and author (metadata, in cataloguing terminology).  PEP 241 contains
553the full list of fields that can be present in the :file:`PKG-INFO` file.  As
554people began to package their software using Python 2.1, more and more packages
555will include metadata, making it possible to build automated cataloguing systems
558For example, the Distutils :command:`sdist` and :command:`bdist_\*` commands
559could support a :option:`upload` option that would automatically upload your
560package to a catalog server.
561
562You can start creating packages containing :file:`PKG-INFO` even if you're not
563using Python 2.1, since a new release of the Distutils will be made for users of
564earlier Python versions.  Version 1.0.2 of the Distutils includes the changes
565described in PEP 241, as well as various bugfixes and enhancements.  It will be
n566-available from  the Distutils SIG at
n565+available from  the Distutils SIG at http://www.python.org/sigs/distutils-sig/.
567-`<http://www.python.org/sigs/distutils-sig/>`_.
568
569
570.. seealso::
571
572   :pep:`241` - Metadata for Python Software Packages
573      Written and implemented by A.M. Kuchling.
574
575   :pep:`243` - Module Repository Upload Mechanism
576      Written by Sean Reifschneider, this draft PEP describes a proposed mechanism for
577      uploading  Python packages to a central server.
578
n579-.. % ======================================================================
n577+.. ======================================================================
580
581
582New and Improved Modules
583========================
584
585* Ka-Ping Yee contributed two new modules: :mod:`inspect.py`, a module for
586  getting information about live Python code, and :mod:`pydoc.py`, a module for
587  interactively converting docstrings to HTML or text.  As a bonus,
607  :file:`pydoc` also includes a Tk-based interactive help browser.   :file:`pydoc`
608  quickly becomes addictive; try it out!
609
610* Two different modules for unit testing were added to the standard library.
611  The :mod:`doctest` module, contributed by Tim Peters, provides a testing
612  framework based on running embedded examples in docstrings and comparing the
613  results against the expected output.  PyUnit, contributed by Steve Purcell, is a
614  unit testing framework inspired by JUnit, which was in turn an adaptation of
n615-  Kent Beck's Smalltalk testing framework.  See
n613+  Kent Beck's Smalltalk testing framework.  See http://pyunit.sourceforge.net/ for
616-  `<http://pyunit.sourceforge.net/>`_ for more information about PyUnit.
614+  more information about PyUnit.
617
618* The :mod:`difflib` module contains a class, :class:`SequenceMatcher`, which
619  compares two sequences and computes the changes required to transform one
620  sequence into the other.  For example, this module can be used to write a tool
621  similar to the Unix :program:`diff` program, and in fact the sample program
622  :file:`Tools/scripts/ndiff.py` demonstrates how to write such a script.
623
624* :mod:`curses.panel`, a wrapper for the panel library, part of ncurses and of
674  optional integer argument *depth* is supplied, the function returns the frame
675  that is *depth* calls below the top of the stack.  For example,
676  ``sys._getframe(1)`` returns the caller's frame object.
677
678  This function is only present in CPython, not in Jython or the .NET
679  implementation.  Use it for debugging, and resist the temptation to put it into
680  production code.
681
n682-.. % ======================================================================
n680+.. ======================================================================
683
684
685Other Changes and Fixes
686=======================
687
688There were relatively few smaller changes made in Python 2.1 due to the shorter
689release cycle.  A search through the CVS change logs turns up 117 patches
690applied, and 136 bugs fixed; both figures are likely to be underestimates.  Some
728  not reading the entire file into memory as the existing :meth:`readlines` method
729  does. You'd use it like this::
730
731     for line in sys.stdin.xreadlines():
732         # ... do something for each line ...
733         ...
734
735  For a fuller discussion of the line I/O changes, see the python-dev summary for
n736-  January 1-15, 2001 at `<http://www.python.org/dev/summary/2001-01-1.html>`_.
n734+  January 1-15, 2001 at http://www.python.org/dev/summary/2001-01-1.html.
737
738* A new method, :meth:`popitem`, was added to dictionaries to enable
739  destructively iterating through the contents of a dictionary; this can be faster
740  for large dictionaries because there's no need to construct a list containing
741  all the keys or values. ``D.popitem()`` removes a random ``(key, value)`` pair
742  from the dictionary ``D`` and returns it as a 2-tuple.  This was implemented
743  mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary
744  patch by Moshe Zadka.
752
753     # List public names
754     __all__ = ['Database', 'open']
755
756  A stricter version of this patch was first suggested and implemented by Ben
757  Wolfson, but after some python-dev discussion, a weaker final version was
758  checked in.
759
n760-* Applying :func:`repr` to strings previously used octal escapes for non-
n758+* Applying :func:`repr` to strings previously used octal escapes for
761-  printable characters; for example, a newline was ``'\012'``.  This was a
759+  non-printable characters; for example, a newline was ``'\012'``.  This was a
762  vestigial trace of Python's C ancestry, but today octal is of very little
763  practical use.  Ka-Ping Yee suggested using hex escapes instead of octal ones,
n764-  and using the ``\n``, ``\t``, ``\r`` escapes for the appropriate characters, and
n762+  and using the ``\n``, ``\t``, ``\r`` escapes for the appropriate characters,
765-  implemented this new formatting.
763+  and implemented this new formatting.
766
767* Syntax errors detected at compile-time can now raise exceptions containing the
768  filename and line number of the error, a pleasant side effect of the compiler
769  reorganization done by Jeremy Hylton.
770
771* C extensions which import other modules have been changed to use
772  :func:`PyImport_ImportModule`, which means that they will use any import hooks
773  that have been installed.  This is also encouraged for third-party extensions
779* Some new ports were contributed: MacOS X (by Steven Majewski), Cygwin (by
780  Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7  (by Billy G.
781  Allie).
782
783And there's the usual list of minor bugfixes, minor memory leaks, docstring
784edits, and other tweaks, too lengthy to be worth itemizing; see the CVS logs for
785the full details if you want them.
786
t787-.. % ======================================================================
t785+.. ======================================================================
788
789
790Acknowledgements
791================
792
793The author would like to thank the following people for offering suggestions on
794various drafts of this article: Graeme Cross, David Goodger, Jay Graves, Michael
795Hudson, Marc-AndrĂ© Lemburg, Fredrik Lundh, Neil Schemenauer, Thomas Wouters.
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op