Py2.4 updates.

This commit is contained in:
Raymond Hettinger 2004-01-10 10:24:27 +00:00
parent 778f8da1d3
commit ec5920194a
1 changed files with 82 additions and 0 deletions

View File

@ -98,6 +98,88 @@ Modernization Procedures
Procedures are grouped by the Python version required to be able to
take advantage of the modernization.
Python 2.4 or Later
-------------------
Simplifying Custom Sorts
''''''''''''''''''''''''
In Python 2.4, the ``sort`` method for lists and the new ``sorted``
built-in function both accept a ``key`` function for computing sort
keys. Unlike the ``cmp`` function which gets applied to every
comparison, the key function gets applied only once to each record.
It is much faster than cmp and typically more readable while using
less code. The key function also maintains the stability of the
sort (records with the same key are left in their original order.
Original code using a comparison function::
names.sort(lambda x,y: cmp(x.lower(), y.lower()))
Alternative original code with explicit decoration::
tempnames = [(n.lower(), n) for n in names]
tempnames.sort()
names = [original for decorated, original in tempnames]
Revised code using a key function::
names.sort(key=str.lower) # case-insensitive sort
Locating: ``grep sort *.py``
Replacing Common Uses of Lambda
'''''''''''''''''''''''''''''''
In Python 2.4, the ``operator`` module gained two new functions,
itemgetter() and attrgetter() that can replace common uses of
the ``lambda`` keyword. The new functions run faster and
are considered by some to improve readability.
Pattern::
lambda r: r[2] --> itemgetter(2)
lambda r: r.myattr --> attrgetter('myattr')
Typical contexts::
sort(studentrecords, key=attrgetter('gpa')) # set a sort field
map(studentrecords, attrgetter('lastname')) # extract a field
Locating: ``grep lambda *.py``
Simplified Reverse Iteration
''''''''''''''''''''''''''''
Python 2.4 introduced the ``reversed`` builtin function for reverse
iteration. The existing approaches to reverse iteration suffered
from wordiness, performance issues (speed and memory consumption),
and/or lack of clarity. A preferred style is to express the
sequence in a forwards direction, apply ``reversed`` to the result,
and then loop over the resulting fast, memory friendly iterator.
Original code expressed with half-open intervals::
for i in range(n-1, -1, -1):
print seqn[i]
Alternative original code reversed in multiple steps::
rseqn = list(seqn)
rseqn.reverse()
for value in rseqn:
print value
Alternative original code expressed with extending slicing:
for value in seqn[::-1]:
print value
Revised code using the ``reversed`` function:
for value in reversed(seqn):
print value
Python 2.3 or Later
-------------------