rest25/whatsnew/2.2.rst => rest262/whatsnew/2.2.rst
f1****************************
n2-  What's New in Python 2.2  
n2+  What's New in Python 2.2
3****************************
4
5:Author: A.M. Kuchling
6
7.. |release| replace:: 1.02
8
n9-.. % $Id: whatsnew22.tex 37315 2004-09-10 19:33:00Z akuchling $
n9+.. $Id: whatsnew22.tex 37315 2004-09-10 19:33:00Z akuchling $
10
11
12Introduction
13============
14
15This article explains the new features in Python 2.2.2, released on October 14,
162002.  Python 2.2.2 is a bugfix release of Python 2.2, originally released on
17December 21, 2001.
31
32
33.. seealso::
34
35   http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm
36      "What's So Special About Python 2.2?" is also about the new 2.2 features, and
37      was written by Cameron Laird and Kathryn Soraiz.
38
n39-.. % ======================================================================
n39+.. ======================================================================
40
41
42PEPs 252 and 253: Type and Class Changes
43========================================
44
45The largest and most far-reaching changes in Python 2.2 are to Python's model of
46objects and classes.  The changes should be backward compatible, so it's likely
47that your code will continue to run unchanged, but the changes provide some
48amazing new capabilities. Before beginning this, the longest and most
49complicated section of this article, I'll provide an overview of the changes and
50offer some comments.
51
n52-A long time ago I wrote a Web page
n52+A long time ago I wrote a Web page (http://www.amk.ca/python/writing/warts.html)
53-(`<http://www.amk.ca/python/writing/warts.html>`_) listing flaws in Python's
53+listing flaws in Python's design.  One of the most significant flaws was that
54-design.  One of the most significant flaws was that it's impossible to subclass
54+it's impossible to subclass Python types implemented in C.  In particular, it's
55-Python types implemented in C.  In particular, it's not possible to subclass
55+not possible to subclass built-in types, so you can't just subclass, say, lists
56-built-in types, so you can't just subclass, say, lists in order to add a single
56+in order to add a single useful method to them. The :mod:`UserList` module
57-useful method to them. The :mod:`UserList` module provides a class that supports
57+provides a class that supports all of the methods of lists and that can be
58-all of the methods of lists and that can be subclassed further, but there's lots
58+subclassed further, but there's lots of C code that expects a regular Python
59-of C code that expects a regular Python list and won't accept a
59+list and won't accept a :class:`UserList` instance.
60-:class:`UserList` instance.
61
62Python 2.2 fixes this, and in the process adds some exciting new capabilities.
63A brief summary:
64
65* You can subclass built-in types such as lists and even integers, and your
66  subclasses should work in every place that requires the original type.
67
68* It's now possible to define static and class methods, in addition to the
291to get at a class's superclasses without having to reimplement Python's
292algorithm. The most commonly used form will be  :func:`super(class, obj)`, which
293returns  a bound superclass object (not the actual class object).  This form
294will be used in methods to call a method in the superclass; for example,
295:class:`D`'s :meth:`save` method would look like this::
296
297   class D (B,C):
298       def save (self):
n299-        # Call superclass .save()
n298+           # Call superclass .save()
300           super(D, self).save()
301           # Save D's private information here
302           ...
303
304:func:`super` can also return unbound superclass objects when called as
305:func:`super(class)` or :func:`super(class1, class2)`, but this probably won't
306often be useful.
307
391
392Related Links
393-------------
394
395This section has just been a quick overview of the new features, giving enough
396of an explanation to start you programming, but many details have been
397simplified or ignored.  Where should you go to get a more complete picture?
398
n399-`<http://www.python.org/2.2/descrintro.html>`_ is a lengthy tutorial
n398+http://www.python.org/2.2/descrintro.html is a lengthy tutorial introduction to
400-introduction to the descriptor features, written by Guido van Rossum. If my
399+the descriptor features, written by Guido van Rossum. If my description has
401-description has whetted your appetite, go read this tutorial next, because it
400+whetted your appetite, go read this tutorial next, because it goes into much
402-goes into much more detail about the new features while still remaining quite
401+more detail about the new features while still remaining quite easy to read.
403-easy to read.
404
405Next, there are two relevant PEPs, :pep:`252` and :pep:`253`.  :pep:`252` is
406titled "Making Types Look More Like Classes", and covers the descriptor API.
407:pep:`253` is titled "Subtyping Built-in Types", and describes the changes to
408type objects that make it possible to subtype built-in objects.  :pep:`253` is
409the more complicated PEP of the two, and at a few points the necessary
410explanations of types and meta-types may cause your head to explode.  Both PEPs
411were written and implemented by Guido van Rossum, with substantial assistance
412from the rest of the Zope Corp. team.
413
414Finally, there's the ultimate authority: the source code.  Most of the machinery
415for the type handling is in :file:`Objects/typeobject.c`, but you should only
416resort to it after all other avenues have been exhausted, including posting a
417question to python-list or python-dev.
418
n419-.. % ======================================================================
n417+.. ======================================================================
420
421
422PEP 234: Iterators
423==================
424
425Another significant addition to 2.2 is an iteration interface at both the C and
426Python levels.  Objects can define how they can be looped over by callers.
427
470   >>> i.next()
471   2
472   >>> i.next()
473   3
474   >>> i.next()
475   Traceback (most recent call last):
476     File "<stdin>", line 1, in ?
477   StopIteration
n478-   >>>      
n476+   >>>
479
480In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it
481expects something for which :func:`iter` will return an iterator. For backward
482compatibility and convenience, an iterator is automatically constructed for
483sequences that don't implement :meth:`__iter__` or a :attr:`tp_iter` slot, so
484``for i in [1,2,3]`` will still work.  Wherever the Python interpreter loops
485over a sequence, it's been changed to use the iterator protocol.  This means you
486can do things like this::
532
533
534.. seealso::
535
536   :pep:`234` - Iterators
537      Written by Ka-Ping Yee and GvR; implemented  by the Python Labs crew, mostly by
538      GvR and Tim Peters.
539
n540-.. % ======================================================================
n538+.. ======================================================================
541
542
543PEP 255: Simple Generators
544==========================
545
546Generators are another new feature, one that interacts with the introduction of
547iterators.
548
629               yield x
630
631Two other examples in :file:`Lib/test/test_generators.py` produce solutions for
632the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
633queen threatens another) and the Knight's Tour (a route that takes a knight to
634every square of an $NxN$ chessboard without visiting any square twice).
635
636The idea of generators comes from other programming languages, especially Icon
n637-(`<http://www.cs.arizona.edu/icon/>`_), where the idea of generators is central.
n635+(http://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
638-In Icon, every expression and function call behaves like a generator.  One
636+Icon, every expression and function call behaves like a generator.  One example
639-example from "An Overview of the Icon Programming Language" at
637+from "An Overview of the Icon Programming Language" at
640-`<http://www.cs.arizona.edu/icon/docs/ipd266.htm>`_ gives an idea of what this
638+http://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
641-looks like::
639+like::
642
643   sentence := "Store it in the neighboring harbor"
644   if (i := find("or", sentence)) > 5 then write(i)
645
646In Icon the :func:`find` function returns the indexes at which the substring
647"or" is found: 3, 23, 33.  In the :keyword:`if` statement, ``i`` is first
648assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
649retries it with the second value of 23.  23 is greater than 5, so the comparison
659
660
661.. seealso::
662
663   :pep:`255` - Simple Generators
664      Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
665      by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
666
n667-.. % ======================================================================
n665+.. ======================================================================
668
669
670PEP 237: Unifying Long Integers and Integers
671============================================
672
673In recent versions, the distinction between regular integers, which are 32-bit
674values on most machines, and long integers, which can be of arbitrary size, was
675becoming an annoyance.  For example, on platforms that support files larger than
699
700
701.. seealso::
702
703   :pep:`237` - Unifying Long Integers and Integers
704      Written by Moshe Zadka and Guido van Rossum.  Implemented mostly by Guido van
705      Rossum.
706
n707-.. % ======================================================================
n705+.. ======================================================================
708
709
710PEP 238: Changing the Division Operator
711=======================================
712
713The most controversial change in Python 2.2 heralds the start of an effort to
714fix an old design flaw that's been in Python from the beginning. Currently
715Python's division operator, ``/``, behaves like C's division operator when
716presented with two integer arguments: it returns an integer result that's
717truncated down when there would be a fractional part.  For example, ``3/2`` is
7181, not 1.5, and ``(-1)/2`` is -1, not -0.5.  This means that the results of
n719-divison can vary unexpectedly depending on the type of the two operands and
n717+division can vary unexpectedly depending on the type of the two operands and
720because Python is dynamically typed, it can be difficult to determine the
721possible types of the operands.
722
723(The controversy is over whether this is *really* a design flaw, and whether
724it's worth breaking existing code to fix this.  It's caused endless discussions
725on python-dev, and in July 2001 erupted into an storm of acidly sarcastic
726postings on :newsgroup:`comp.lang.python`. I won't argue for either side here
727and will stick to describing what's  implemented in 2.2.  Read :pep:`238` for a
767  warning; the warning will be turned on by default in Python 2.3.
768
769
770.. seealso::
771
772   :pep:`238` - Changing the Division Operator
773      Written by Moshe Zadka and  Guido van Rossum.  Implemented by Guido van Rossum..
774
n775-.. % ======================================================================
n773+.. ======================================================================
776
777
778Unicode Changes
779===============
780
781Python's Unicode support has been enhanced a bit in 2.2.  Unicode strings are
782usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be
783compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by
829implemented by Fredrik Lundh and Martin von Löwis.
830
831
832.. seealso::
833
834   :pep:`261` - Support for 'wide' Unicode characters
835      Written by Paul Prescod.
836
n837-.. % ======================================================================
n835+.. ======================================================================
838
839
840PEP 227: Nested Scopes
841======================
842
843In Python 2.1, statically nested scopes were added as an optional feature, to be
844enabled by a ``from __future__ import nested_scopes`` directive.  In 2.2 nested
845scopes no longer need to be specially enabled, and are now always present.  The
906definitions or :keyword:`lambda` expressions with free variables, the compiler
907will flag this by raising a :exc:`SyntaxError` exception.
908
909To make the preceding explanation a bit clearer, here's an example::
910
911   x = 1
912   def f():
913       # The next line is a syntax error
n914-       exec 'x=2'  
n912+       exec 'x=2'
915       def g():
916           return x
917
918Line 4 containing the :keyword:`exec` statement is a syntax error, since
919:keyword:`exec` would define a new local variable named ``x`` whose value should
920be accessed by :func:`g`.
921
922This shouldn't be much of a limitation, since :keyword:`exec` is rarely used in
924anyway).
925
926
927.. seealso::
928
929   :pep:`227` - Statically Nested Scopes
930      Written and implemented by Jeremy Hylton.
931
n932-.. % ======================================================================
n930+.. ======================================================================
933
934
935New and Improved Modules
936========================
937
938* The :mod:`xmlrpclib` module was contributed to the standard library by Fredrik
939  Lundh, providing support for writing XML-RPC clients.  XML-RPC is a simple
940  remote procedure call protocol built on top of HTTP and XML. For example, the
949     # [{'id': 4, 'title': 'Freshmeat Daily News'}
950     #  {'id': 190, 'title': '32Bits Online'},
951     #  {'id': 4549, 'title': '3DGamers'}, ... ]
952
953     # Get the items for one channel
954     items = s.meerkat.getItems( {'channel': 4} )
955
956     # 'items' is another list of dictionaries, like this:
n957-     # [{'link': 'http://freshmeat.net/releases/52719/', 
n955+     # [{'link': 'http://freshmeat.net/releases/52719/',
958-     #   'description': 'A utility which converts HTML to XSL FO.', 
956+     #   'description': 'A utility which converts HTML to XSL FO.',
959     #   'title': 'html2fo 0.3 (Default)'}, ... ]
960
961  The :mod:`SimpleXMLRPCServer` module makes it easy to create straightforward
n962-  XML-RPC servers.  See `<http://www.xmlrpc.com/>`_ for more information about
n960+  XML-RPC servers.  See http://www.xmlrpc.com/ for more information about XML-RPC.
963-  XML-RPC.
964
965* The new :mod:`hmac` module implements the HMAC algorithm described by
966  :rfc:`2104`. (Contributed by Gerhard Häring.)
967
968* Several functions that originally returned lengthy tuples now return pseudo-
969  sequences that still behave like tuples but also have mnemonic attributes such
970  as memberst_mtime or :attr:`tm_year`. The enhanced functions include
971  :func:`stat`, :func:`fstat`, :func:`statvfs`, and :func:`fstatvfs` in the
1040* The :mod:`mimetypes` module now makes it easier to use alternative MIME-type
1041  databases by the addition of a :class:`MimeTypes` class, which takes a list of
1042  filenames to be parsed.  (Contributed by Fred L. Drake, Jr.)
1043
1044* A :class:`Timer` class was added to the :mod:`threading` module that allows
1045  scheduling an activity to happen at some future time.  (Contributed by Itamar
1046  Shtull-Trauring.)
1047
n1048-.. % ======================================================================
n1045+.. ======================================================================
1049
1050
1051Interpreter Changes and Fixes
1052=============================
1053
1054Some of the changes only affect people who deal with the Python interpreter at
1055the C level because they're writing Python extension modules, embedding the
1056interpreter, or just hacking on the interpreter itself. If you only write Python
1120  :cfunc:`sprintf` and :cfunc:`vsprintf` functions, the Python versions check the
1121  bounds of the buffer used to protect against buffer overruns. (Contributed by
1122  M.-A. Lemburg.)
1123
1124* The :cfunc:`_PyTuple_Resize` function has lost an unused parameter, so now it
1125  takes 2 parameters instead of 3.  The third argument was never used, and can
1126  simply be discarded when porting code from earlier versions to Python 2.2.
1127
n1128-.. % ======================================================================
n1125+.. ======================================================================
1129
1130
1131Other Changes and Fixes
1132=======================
1133
1134As usual there were a bunch of other improvements and bugfixes scattered
1135throughout the source tree.  A search through the CVS change logs finds there
1136were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1
1153  MacPython IDE, possibly using Python as a standard OSA scripting language and
1154  much more."
1155
1156  Most of the MacPython toolbox modules, which interface to MacOS APIs such as
1157  windowing, QuickTime, scripting, etc. have been ported to OS X, but they've been
1158  left commented out in :file:`setup.py`.  People who want to experiment with
1159  these modules can uncomment them manually.
1160
n1161-  .. % Jack's original comments:
n1158+  .. Jack's original comments:
1162-  .. % The main change is the possibility to build Python as a
1159+     The main change is the possibility to build Python as a
1163-  .. % framework. This installs a self-contained Python installation plus the
1160+     framework. This installs a self-contained Python installation plus the
1164-  .. % OSX framework "glue" into /Library/Frameworks/Python.framework (or
1161+     OSX framework "glue" into /Library/Frameworks/Python.framework (or
1165-  .. % another location of choice). For now there is little immedeate added
1162+     another location of choice). For now there is little immedeate added
1166-  .. % benefit to this (actually, there is the disadvantage that you have to
1163+     benefit to this (actually, there is the disadvantage that you have to
1167-  .. % change your PATH to be able to find Python), but it is the basis for
1164+     change your PATH to be able to find Python), but it is the basis for
1168-  .. % creating a fullblown Python application, porting the MacPython IDE,
1165+     creating a fullblown Python application, porting the MacPython IDE,
1169-  .. % possibly using Python as a standard OSA scripting language and much
1166+     possibly using Python as a standard OSA scripting language and much
1170-  .. % more. You enable this with "configure --enable-framework".
1167+     more. You enable this with "configure --enable-framework".
1171-  .. % The other change is that most MacPython toolbox modules, which
1168+     The other change is that most MacPython toolbox modules, which
1172-  .. % interface to all the MacOS APIs such as windowing, quicktime,
1169+     interface to all the MacOS APIs such as windowing, quicktime,
1173-  .. % scripting, etc. have been ported. Again, most of these are not of
1170+     scripting, etc. have been ported. Again, most of these are not of
1174-  .. % immedeate use, as they need a full application to be really useful, so
1171+     immedeate use, as they need a full application to be really useful, so
1175-  .. % they have been commented out in setup.py. People wanting to experiment
1172+     they have been commented out in setup.py. People wanting to experiment
1176-  .. % can uncomment them. Gestalt and Internet Config modules are enabled by
1173+     can uncomment them. Gestalt and Internet Config modules are enabled by
1177-  .. % default.
1174+     default.
1178
1179* Keyword arguments passed to builtin functions that don't take them now cause a
1180  :exc:`TypeError` exception to be raised, with the message "*function* takes no
1181  keyword arguments".
1182
1183* Weak references, added in Python 2.1 as an extension module, are now part of
1184  the core because they're used in the implementation of new-style classes.  The
1185  :exc:`ReferenceError` exception has therefore moved from the :mod:`weakref`
1251  (Contributed by Bram Stolk.)
1252
1253* The :func:`pow` built-in function no longer supports 3 arguments when
1254  floating-point numbers are supplied. ``pow(x, y, z)`` returns ``(x**y) % z``,
1255  but this is never useful for floating point numbers, and the final result varies
1256  unpredictably depending on the platform.  A call such as ``pow(2.0, 8.0, 7.0)``
1257  will now raise a :exc:`TypeError` exception.
1258
t1259-.. % ======================================================================
t1256+.. ======================================================================
1260
1261
1262Acknowledgements
1263================
1264
1265The author would like to thank the following people for offering suggestions,
1266corrections and assistance with various drafts of this article: Fred Bremmer,
1267Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger,
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op