| |
| |
| .. seealso:: |
| |
| http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm |
| "What's So Special About Python 2.2?" is also about the new 2.2 features, and |
| was written by Cameron Laird and Kathryn Soraiz. |
| |
n | .. % ====================================================================== |
n | .. ====================================================================== |
| |
| |
| PEPs 252 and 253: Type and Class Changes |
| ======================================== |
| |
| The largest and most far-reaching changes in Python 2.2 are to Python's model of |
| objects and classes. The changes should be backward compatible, so it's likely |
| that your code will continue to run unchanged, but the changes provide some |
| amazing new capabilities. Before beginning this, the longest and most |
| complicated section of this article, I'll provide an overview of the changes and |
| offer some comments. |
| |
n | A long time ago I wrote a Web page |
n | A long time ago I wrote a Web page (http://www.amk.ca/python/writing/warts.html) |
| (`<http://www.amk.ca/python/writing/warts.html>`_) listing flaws in Python's |
| listing flaws in Python's design. One of the most significant flaws was that |
| design. One of the most significant flaws was that it's impossible to subclass |
| it's impossible to subclass Python types implemented in C. In particular, it's |
| Python types implemented in C. In particular, it's not possible to subclass |
| not possible to subclass built-in types, so you can't just subclass, say, lists |
| built-in types, so you can't just subclass, say, lists in order to add a single |
| in order to add a single useful method to them. The :mod:`UserList` module |
| useful method to them. The :mod:`UserList` module provides a class that supports |
| provides a class that supports all of the methods of lists and that can be |
| all of the methods of lists and that can be subclassed further, but there's lots |
| subclassed further, but there's lots of C code that expects a regular Python |
| of C code that expects a regular Python list and won't accept a |
| list and won't accept a :class:`UserList` instance. |
| :class:`UserList` instance. |
| |
| Python 2.2 fixes this, and in the process adds some exciting new capabilities. |
| A brief summary: |
| |
| * You can subclass built-in types such as lists and even integers, and your |
| subclasses should work in every place that requires the original type. |
| |
| * It's now possible to define static and class methods, in addition to the |
| to get at a class's superclasses without having to reimplement Python's |
| algorithm. The most commonly used form will be :func:`super(class, obj)`, which |
| returns a bound superclass object (not the actual class object). This form |
| will be used in methods to call a method in the superclass; for example, |
| :class:`D`'s :meth:`save` method would look like this:: |
| |
| class D (B,C): |
| def save (self): |
n | # Call superclass .save() |
n | # Call superclass .save() |
| super(D, self).save() |
| # Save D's private information here |
| ... |
| |
| :func:`super` can also return unbound superclass objects when called as |
| :func:`super(class)` or :func:`super(class1, class2)`, but this probably won't |
| often be useful. |
| |
| |
| Related Links |
| ------------- |
| |
| This section has just been a quick overview of the new features, giving enough |
| of an explanation to start you programming, but many details have been |
| simplified or ignored. Where should you go to get a more complete picture? |
| |
n | `<http://www.python.org/2.2/descrintro.html>`_ is a lengthy tutorial |
n | http://www.python.org/2.2/descrintro.html is a lengthy tutorial introduction to |
| introduction to the descriptor features, written by Guido van Rossum. If my |
| the descriptor features, written by Guido van Rossum. If my description has |
| description has whetted your appetite, go read this tutorial next, because it |
| whetted your appetite, go read this tutorial next, because it goes into much |
| goes into much more detail about the new features while still remaining quite |
| more detail about the new features while still remaining quite easy to read. |
| easy to read. |
| |
| Next, there are two relevant PEPs, :pep:`252` and :pep:`253`. :pep:`252` is |
| titled "Making Types Look More Like Classes", and covers the descriptor API. |
| :pep:`253` is titled "Subtyping Built-in Types", and describes the changes to |
| type objects that make it possible to subtype built-in objects. :pep:`253` is |
| the more complicated PEP of the two, and at a few points the necessary |
| explanations of types and meta-types may cause your head to explode. Both PEPs |
| were written and implemented by Guido van Rossum, with substantial assistance |
| from the rest of the Zope Corp. team. |
| |
| Finally, there's the ultimate authority: the source code. Most of the machinery |
| for the type handling is in :file:`Objects/typeobject.c`, but you should only |
| resort to it after all other avenues have been exhausted, including posting a |
| question to python-list or python-dev. |
| |
n | .. % ====================================================================== |
n | .. ====================================================================== |
| |
| |
| PEP 234: Iterators |
| ================== |
| |
| Another significant addition to 2.2 is an iteration interface at both the C and |
| Python levels. Objects can define how they can be looped over by callers. |
| |
| >>> i.next() |
| 2 |
| >>> i.next() |
| 3 |
| >>> i.next() |
| Traceback (most recent call last): |
| File "<stdin>", line 1, in ? |
| StopIteration |
n | >>> |
n | >>> |
| |
| In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it |
| expects something for which :func:`iter` will return an iterator. For backward |
| compatibility and convenience, an iterator is automatically constructed for |
| sequences that don't implement :meth:`__iter__` or a :attr:`tp_iter` slot, so |
| ``for i in [1,2,3]`` will still work. Wherever the Python interpreter loops |
| over a sequence, it's been changed to use the iterator protocol. This means you |
| can do things like this:: |
| yield x |
| |
| Two other examples in :file:`Lib/test/test_generators.py` produce solutions for |
| the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no |
| queen threatens another) and the Knight's Tour (a route that takes a knight to |
| every square of an $NxN$ chessboard without visiting any square twice). |
| |
| The idea of generators comes from other programming languages, especially Icon |
n | (`<http://www.cs.arizona.edu/icon/>`_), where the idea of generators is central. |
n | (http://www.cs.arizona.edu/icon/), where the idea of generators is central. In |
| In Icon, every expression and function call behaves like a generator. One |
| Icon, every expression and function call behaves like a generator. One example |
| example from "An Overview of the Icon Programming Language" at |
| from "An Overview of the Icon Programming Language" at |
| `<http://www.cs.arizona.edu/icon/docs/ipd266.htm>`_ gives an idea of what this |
| http://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks |
| looks like:: |
| like:: |
| |
| sentence := "Store it in the neighboring harbor" |
| if (i := find("or", sentence)) > 5 then write(i) |
| |
| In Icon the :func:`find` function returns the indexes at which the substring |
| "or" is found: 3, 23, 33. In the :keyword:`if` statement, ``i`` is first |
| assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon |
| retries it with the second value of 23. 23 is greater than 5, so the comparison |
| |
| |
| .. seealso:: |
| |
| :pep:`255` - Simple Generators |
| Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly |
| by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew. |
| |
n | .. % ====================================================================== |
n | .. ====================================================================== |
| |
| |
| PEP 237: Unifying Long Integers and Integers |
| ============================================ |
| |
| In recent versions, the distinction between regular integers, which are 32-bit |
| values on most machines, and long integers, which can be of arbitrary size, was |
| becoming an annoyance. For example, on platforms that support files larger than |
| |
| |
| .. seealso:: |
| |
| :pep:`237` - Unifying Long Integers and Integers |
| Written by Moshe Zadka and Guido van Rossum. Implemented mostly by Guido van |
| Rossum. |
| |
n | .. % ====================================================================== |
n | .. ====================================================================== |
| |
| |
| PEP 238: Changing the Division Operator |
| ======================================= |
| |
| The most controversial change in Python 2.2 heralds the start of an effort to |
| fix an old design flaw that's been in Python from the beginning. Currently |
| Python's division operator, ``/``, behaves like C's division operator when |
| presented with two integer arguments: it returns an integer result that's |
| truncated down when there would be a fractional part. For example, ``3/2`` is |
| 1, not 1.5, and ``(-1)/2`` is -1, not -0.5. This means that the results of |
n | divison can vary unexpectedly depending on the type of the two operands and |
n | division can vary unexpectedly depending on the type of the two operands and |
| because Python is dynamically typed, it can be difficult to determine the |
| possible types of the operands. |
| |
| (The controversy is over whether this is *really* a design flaw, and whether |
| it's worth breaking existing code to fix this. It's caused endless discussions |
| on python-dev, and in July 2001 erupted into an storm of acidly sarcastic |
| postings on :newsgroup:`comp.lang.python`. I won't argue for either side here |
| and will stick to describing what's implemented in 2.2. Read :pep:`238` for a |
| # [{'id': 4, 'title': 'Freshmeat Daily News'} |
| # {'id': 190, 'title': '32Bits Online'}, |
| # {'id': 4549, 'title': '3DGamers'}, ... ] |
| |
| # Get the items for one channel |
| items = s.meerkat.getItems( {'channel': 4} ) |
| |
| # 'items' is another list of dictionaries, like this: |
n | # [{'link': 'http://freshmeat.net/releases/52719/', |
n | # [{'link': 'http://freshmeat.net/releases/52719/', |
| # 'description': 'A utility which converts HTML to XSL FO.', |
| # 'description': 'A utility which converts HTML to XSL FO.', |
| # 'title': 'html2fo 0.3 (Default)'}, ... ] |
| |
| The :mod:`SimpleXMLRPCServer` module makes it easy to create straightforward |
n | XML-RPC servers. See `<http://www.xmlrpc.com/>`_ for more information about |
n | XML-RPC servers. See http://www.xmlrpc.com/ for more information about XML-RPC. |
| XML-RPC. |
| |
| * The new :mod:`hmac` module implements the HMAC algorithm described by |
| :rfc:`2104`. (Contributed by Gerhard Häring.) |
| |
| * Several functions that originally returned lengthy tuples now return pseudo- |
| sequences that still behave like tuples but also have mnemonic attributes such |
| as memberst_mtime or :attr:`tm_year`. The enhanced functions include |
| :func:`stat`, :func:`fstat`, :func:`statvfs`, and :func:`fstatvfs` in the |
| * The :mod:`mimetypes` module now makes it easier to use alternative MIME-type |
| databases by the addition of a :class:`MimeTypes` class, which takes a list of |
| filenames to be parsed. (Contributed by Fred L. Drake, Jr.) |
| |
| * A :class:`Timer` class was added to the :mod:`threading` module that allows |
| scheduling an activity to happen at some future time. (Contributed by Itamar |
| Shtull-Trauring.) |
| |
n | .. % ====================================================================== |
n | .. ====================================================================== |
| |
| |
| Interpreter Changes and Fixes |
| ============================= |
| |
| Some of the changes only affect people who deal with the Python interpreter at |
| the C level because they're writing Python extension modules, embedding the |
| interpreter, or just hacking on the interpreter itself. If you only write Python |
| :cfunc:`sprintf` and :cfunc:`vsprintf` functions, the Python versions check the |
| bounds of the buffer used to protect against buffer overruns. (Contributed by |
| M.-A. Lemburg.) |
| |
| * The :cfunc:`_PyTuple_Resize` function has lost an unused parameter, so now it |
| takes 2 parameters instead of 3. The third argument was never used, and can |
| simply be discarded when porting code from earlier versions to Python 2.2. |
| |
n | .. % ====================================================================== |
n | .. ====================================================================== |
| |
| |
| Other Changes and Fixes |
| ======================= |
| |
| As usual there were a bunch of other improvements and bugfixes scattered |
| throughout the source tree. A search through the CVS change logs finds there |
| were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1 |
| MacPython IDE, possibly using Python as a standard OSA scripting language and |
| much more." |
| |
| Most of the MacPython toolbox modules, which interface to MacOS APIs such as |
| windowing, QuickTime, scripting, etc. have been ported to OS X, but they've been |
| left commented out in :file:`setup.py`. People who want to experiment with |
| these modules can uncomment them manually. |
| |
n | .. % Jack's original comments: |
n | .. Jack's original comments: |
| .. % The main change is the possibility to build Python as a |
| The main change is the possibility to build Python as a |
| .. % framework. This installs a self-contained Python installation plus the |
| framework. This installs a self-contained Python installation plus the |
| .. % OSX framework "glue" into /Library/Frameworks/Python.framework (or |
| OSX framework "glue" into /Library/Frameworks/Python.framework (or |
| .. % another location of choice). For now there is little immedeate added |
| another location of choice). For now there is little immedeate added |
| .. % benefit to this (actually, there is the disadvantage that you have to |
| benefit to this (actually, there is the disadvantage that you have to |
| .. % change your PATH to be able to find Python), but it is the basis for |
| change your PATH to be able to find Python), but it is the basis for |
| .. % creating a fullblown Python application, porting the MacPython IDE, |
| creating a fullblown Python application, porting the MacPython IDE, |
| .. % possibly using Python as a standard OSA scripting language and much |
| possibly using Python as a standard OSA scripting language and much |
| .. % more. You enable this with "configure --enable-framework". |
| more. You enable this with "configure --enable-framework". |
| .. % The other change is that most MacPython toolbox modules, which |
| The other change is that most MacPython toolbox modules, which |
| .. % interface to all the MacOS APIs such as windowing, quicktime, |
| interface to all the MacOS APIs such as windowing, quicktime, |
| .. % scripting, etc. have been ported. Again, most of these are not of |
| scripting, etc. have been ported. Again, most of these are not of |
| .. % immedeate use, as they need a full application to be really useful, so |
| immedeate use, as they need a full application to be really useful, so |
| .. % they have been commented out in setup.py. People wanting to experiment |
| they have been commented out in setup.py. People wanting to experiment |
| .. % can uncomment them. Gestalt and Internet Config modules are enabled by |
| can uncomment them. Gestalt and Internet Config modules are enabled by |
| .. % default. |
| default. |
| |
| * Keyword arguments passed to builtin functions that don't take them now cause a |
| :exc:`TypeError` exception to be raised, with the message "*function* takes no |
| keyword arguments". |
| |
| * Weak references, added in Python 2.1 as an extension module, are now part of |
| the core because they're used in the implementation of new-style classes. The |
| :exc:`ReferenceError` exception has therefore moved from the :mod:`weakref` |
| (Contributed by Bram Stolk.) |
| |
| * The :func:`pow` built-in function no longer supports 3 arguments when |
| floating-point numbers are supplied. ``pow(x, y, z)`` returns ``(x**y) % z``, |
| but this is never useful for floating point numbers, and the final result varies |
| unpredictably depending on the platform. A call such as ``pow(2.0, 8.0, 7.0)`` |
| will now raise a :exc:`TypeError` exception. |
| |
t | .. % ====================================================================== |
t | .. ====================================================================== |
| |
| |
| Acknowledgements |
| ================ |
| |
| The author would like to thank the following people for offering suggestions, |
| corrections and assistance with various drafts of this article: Fred Bremmer, |
| Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger, |