summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorChristian Heimes <christian@cheimes.de>2007-12-15 01:27:15 (GMT)
committerChristian Heimes <christian@cheimes.de>2007-12-15 01:27:15 (GMT)
commit0449f63f53fa0c2fcf779703d2db77d8a658cf7d (patch)
treef7e541fe54279a4b5954b79f529d652e659e6bd9 /Doc
parent54cc54c1fe26328d62c70fa55350ad89868c1d61 (diff)
downloadcpython-0449f63f53fa0c2fcf779703d2db77d8a658cf7d.zip
cpython-0449f63f53fa0c2fcf779703d2db77d8a658cf7d.tar.gz
cpython-0449f63f53fa0c2fcf779703d2db77d8a658cf7d.tar.bz2
Merged revisions 59488-59511 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r59489 | christian.heimes | 2007-12-14 03:33:57 +0100 (Fri, 14 Dec 2007) | 1 line Silence a warning about an unsed variable in debug builds ........ r59490 | christian.heimes | 2007-12-14 03:35:23 +0100 (Fri, 14 Dec 2007) | 2 lines Fixed bug #1620: New @spam.getter property syntax modifies the property in place. I added also the feature that a @prop.getter decorator does not overwrite the doc string of the property if it was given as an argument to property(). ........ r59491 | raymond.hettinger | 2007-12-14 03:49:47 +0100 (Fri, 14 Dec 2007) | 1 line Cleaner method naming convention ........ r59492 | christian.heimes | 2007-12-14 04:02:34 +0100 (Fri, 14 Dec 2007) | 1 line Fixed a warning in _codecs_iso2022.c and some non C89 conform // comments. ........ r59493 | christian.heimes | 2007-12-14 05:38:13 +0100 (Fri, 14 Dec 2007) | 1 line Fixed warning in ssl module ........ r59500 | raymond.hettinger | 2007-12-14 19:08:20 +0100 (Fri, 14 Dec 2007) | 1 line Add line spacing for readability ........ r59501 | raymond.hettinger | 2007-12-14 19:12:21 +0100 (Fri, 14 Dec 2007) | 3 lines Update method names for named tuples. ........ r59503 | georg.brandl | 2007-12-14 20:03:36 +0100 (Fri, 14 Dec 2007) | 3 lines Add a section about nested listcomps to the tutorial. Thanks to Ian Bruntlett and Robert Lehmann. ........ r59504 | raymond.hettinger | 2007-12-14 20:19:59 +0100 (Fri, 14 Dec 2007) | 1 line Faster and simpler _replace() method ........ r59505 | raymond.hettinger | 2007-12-14 22:51:50 +0100 (Fri, 14 Dec 2007) | 1 line Add usage note ........ r59507 | andrew.kuchling | 2007-12-14 23:41:18 +0100 (Fri, 14 Dec 2007) | 1 line Remove warning about URL ........ r59510 | andrew.kuchling | 2007-12-14 23:52:36 +0100 (Fri, 14 Dec 2007) | 1 line Bump the version number, and make a few small edits ........ r59511 | christian.heimes | 2007-12-15 00:42:36 +0100 (Sat, 15 Dec 2007) | 2 lines Fixed bug #1628 The detection now works on Unix with Makefile, Makefile with VPATH and on Windows. ........
Diffstat (limited to 'Doc')
-rw-r--r--Doc/ACKS.txt1
-rw-r--r--Doc/howto/functional.rst32
-rw-r--r--Doc/library/collections.rst53
-rw-r--r--Doc/tutorial/datastructures.rst42
-rw-r--r--Doc/whatsnew/2.6.rst6
5 files changed, 96 insertions, 38 deletions
diff --git a/Doc/ACKS.txt b/Doc/ACKS.txt
index d0c1f31..5f6e12f 100644
--- a/Doc/ACKS.txt
+++ b/Doc/ACKS.txt
@@ -28,6 +28,7 @@ docs@python.org), and we'll be glad to correct the problem.
* Aaron Brancotti
* Georg Brandl
* Keith Briggs
+ * Ian Bruntlett
* Lee Busby
* Lorenzo M. Catucci
* Carl Cerecke
diff --git a/Doc/howto/functional.rst b/Doc/howto/functional.rst
index 21272fa..1557f55 100644
--- a/Doc/howto/functional.rst
+++ b/Doc/howto/functional.rst
@@ -3,12 +3,10 @@
********************************
:Author: \A. M. Kuchling
-:Release: 0.30
+:Release: 0.31
(This is a first draft. Please send comments/error reports/suggestions to
-amk@amk.ca. This URL is probably not going to be the final location of the
-document, so be careful about linking to it -- you may want to add a
-disclaimer.)
+amk@amk.ca.)
In this document, we'll take a tour of Python's features suitable for
implementing programs in a functional style. After an introduction to the
@@ -49,17 +47,19 @@ Programming languages support decomposing problems in several different ways:
functional languages include the ML family (Standard ML, OCaml, and other
variants) and Haskell.
-The designers of some computer languages have chosen one approach to programming
-that's emphasized. This often makes it difficult to write programs that use a
-different approach. Other languages are multi-paradigm languages that support
-several different approaches. Lisp, C++, and Python are multi-paradigm; you can
-write programs or libraries that are largely procedural, object-oriented, or
-functional in all of these languages. In a large program, different sections
-might be written using different approaches; the GUI might be object-oriented
-while the processing logic is procedural or functional, for example.
+The designers of some computer languages choose to emphasize one
+particular approach to programming. This often makes it difficult to
+write programs that use a different approach. Other languages are
+multi-paradigm languages that support several different approaches.
+Lisp, C++, and Python are multi-paradigm; you can write programs or
+libraries that are largely procedural, object-oriented, or functional
+in all of these languages. In a large program, different sections
+might be written using different approaches; the GUI might be
+object-oriented while the processing logic is procedural or
+functional, for example.
In a functional program, input flows through a set of functions. Each function
-operates on its input and produces some output. Functional style frowns upon
+operates on its input and produces some output. Functional style discourages
functions with side effects that modify internal state or make other changes
that aren't visible in the function's return value. Functions that have no side
effects at all are called **purely functional**. Avoiding side effects means
@@ -616,7 +616,7 @@ Built-in functions
Let's look in more detail at built-in functions often used with iterators.
-Two Python's built-in functions, :func:`map` and :func:`filter`, are somewhat
+Two of Python's built-in functions, :func:`map` and :func:`filter`, are somewhat
obsolete; they duplicate the features of list comprehensions but return actual
lists instead of iterators.
@@ -842,8 +842,8 @@ Fredrik Lundh once suggested the following set of rules for refactoring uses of
4) Convert the lambda to a def statement, using that name.
5) Remove the comment.
-I really like these rules, but you're free to disagree that this lambda-free
-style is better.
+I really like these rules, but you're free to disagree
+about whether this lambda-free style is better.
The itertools module
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index 3ac95b1..1982187 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -403,8 +403,8 @@ they add the ability to access fields by name instead of position index.
can be specified as a list of strings (such as ['x', 'y']).
Any valid Python identifier may be used for a fieldname except for names
- starting and ending with double underscores. Valid identifiers consist of
- letters, digits, and underscores but do not start with a digit and cannot be
+ starting with an underscore. Valid identifiers consist of letters, digits,
+ and underscores but do not start with a digit or underscore and cannot be
a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
or *raise*.
@@ -418,18 +418,25 @@ Example::
>>> Point = namedtuple('Point', 'x y', verbose=True)
class Point(tuple):
'Point(x, y)'
+
__slots__ = ()
- __fields__ = ('x', 'y')
+
+ _fields = ('x', 'y')
+
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
+
def __repr__(self):
return 'Point(x=%r, y=%r)' % self
- def __asdict__(self):
- 'Return a new dict mapping field names to their values'
+
+ def _asdict(self):
+ 'Return a new dict which maps field names to their values'
return dict(zip(('x', 'y'), self))
- def __replace__(self, **kwds):
+
+ def _replace(self, **kwds):
'Return a new Point object replacing specified fields with new values'
- return Point(**dict(zip(('x', 'y'), self), **kwds))
+ return Point(*map(kwds.get, ('x', 'y'), self))
+
x = property(itemgetter(0))
y = property(itemgetter(1))
@@ -477,43 +484,51 @@ When casting a dictionary to a named tuple, use the double-star-operator::
In addition to the methods inherited from tuples, named tuples support
two additonal methods and a read-only attribute.
-.. method:: somenamedtuple.__asdict__()
+.. method:: somenamedtuple._asdict()
Return a new dict which maps field names to their corresponding values:
::
- >>> p.__asdict__()
+ >>> p._asdict()
{'x': 11, 'y': 22}
-.. method:: somenamedtuple.__replace__(kwargs)
+.. method:: somenamedtuple._replace(kwargs)
Return a new instance of the named tuple replacing specified fields with new values:
::
>>> p = Point(x=11, y=22)
- >>> p.__replace__(x=33)
+ >>> p._replace(x=33)
Point(x=33, y=22)
>>> for partnum, record in inventory.items():
- ... inventory[partnum] = record.__replace__(price=newprices[partnum], updated=time.now())
+ ... inventory[partnum] = record._replace(price=newprices[partnum], updated=time.now())
-.. attribute:: somenamedtuple.__fields__
+.. attribute:: somenamedtuple._fields
Return a tuple of strings listing the field names. This is useful for introspection
and for creating new named tuple types from existing named tuples.
::
- >>> p.__fields__ # view the field names
+ >>> p._fields # view the field names
('x', 'y')
>>> Color = namedtuple('Color', 'red green blue')
- >>> Pixel = namedtuple('Pixel', Point.__fields__ + Color.__fields__)
+ >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)'
+To retrieve a field whose name is stored in a string, use the :func:`getattr`
+function:
+
+::
+
+ >>> getattr(p, 'x')
+ 11
+
Since a named tuple is a regular Python class, it is easy to add or change
functionality. For example, the display format can be changed by overriding
the :meth:`__repr__` method:
@@ -522,17 +537,17 @@ the :meth:`__repr__` method:
>>> Point = namedtuple('Point', 'x y')
>>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
- >>> Point(x=10, y=20)
- Point(10.000, 20.000)
+ >>> Point(x=11, y=22)
+ Point(11.000, 22.000)
Default values can be implemented by starting with a prototype instance
-and customizing it with :meth:`__replace__`:
+and customizing it with :meth:`_replace`:
::
>>> Account = namedtuple('Account', 'owner balance transaction_count')
>>> model_account = Account('<owner name>', 0.0, 0)
- >>> johns_account = model_account.__replace__(owner='John')
+ >>> johns_account = model_account._replace(owner='John')
.. rubric:: Footnotes
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index 54d1922..cf9fea3 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -277,6 +277,48 @@ List comprehensions can be applied to complex expressions and nested functions::
['3.1', '3.14', '3.142', '3.1416', '3.14159']
+Nested List Comprehensions
+--------------------------
+
+If you've got the stomach for it, list comprehensions can be nested. They are a
+powerful tool but -- like all powerful tools -- they need to be used carefully,
+if at all.
+
+Consider the following example of a 3x3 matrix held as a list containing three
+lists, one list per row::
+
+ >>> mat = [
+ ... [1, 2, 3],
+ ... [4, 5, 6],
+ ... [7, 8, 9],
+ ... ]
+
+Now, if you wanted to swap rows and columns, you could use a list
+comprehension::
+
+ >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
+ [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
+
+Special care has to be taken for the *nested* list comprehension:
+
+ To avoid apprehension when nesting list comprehensions, read from right to
+ left.
+
+A more verbose version of this snippet shows the flow explicitly::
+
+ for i in [0, 1, 2]:
+ for row in mat:
+ print row[i],
+ print
+
+In real world, you should prefer builtin functions to complex flow statements.
+The :func:`zip` function would do a great job for this use case::
+
+ >>> zip(*mat)
+ [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
+
+See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
+
.. _tut-del:
The :keyword:`del` statement
diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst
index 65cf3d1..c63cc32 100644
--- a/Doc/whatsnew/2.6.rst
+++ b/Doc/whatsnew/2.6.rst
@@ -528,7 +528,7 @@ complete list of changes, or look through the CVS logs for all the details.
... 'id name type size')
# Names are separated by spaces or commas.
# 'id, name, type, size' would also work.
- >>> var_type.__fields__
+ >>> var_type._fields
('id', 'name', 'type', 'size')
>>> var = var_type(1, 'frequency', 'int', 4)
@@ -536,9 +536,9 @@ complete list of changes, or look through the CVS logs for all the details.
1 1
>>> print var[2], var.type # Equivalent
int int
- >>> var.__asdict__()
+ >>> var._asdict()
{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
- >>> v2 = var.__replace__('name', 'amplitude')
+ >>> v2 = var._replace('name', 'amplitude')
>>> v2
variable(id=1, name='amplitude', type='int', size=4)