diff options
author | Raymond Hettinger <python@rcn.com> | 2007-10-05 02:47:07 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2007-10-05 02:47:07 (GMT) |
commit | a7fc4b13e08430b14b2ac18555ba4dda315948d0 (patch) | |
tree | 36d96ea5ac95c1e83b5ad0ce56b31134a69673a4 /Doc/library | |
parent | c9b7163da511684c49f53fef7b9a49eb44fff5e8 (diff) | |
download | cpython-a7fc4b13e08430b14b2ac18555ba4dda315948d0.zip cpython-a7fc4b13e08430b14b2ac18555ba4dda315948d0.tar.gz cpython-a7fc4b13e08430b14b2ac18555ba4dda315948d0.tar.bz2 |
Add __asdict__() to NamedTuple and refine the docs.
Add maxlen support to deque() and fixup docs.
Partially fix __reduce__(). The None as a third arg was no longer supported.
Still needs work on __reduce__() to handle recursive inputs.
Diffstat (limited to 'Doc/library')
-rw-r--r-- | Doc/library/collections.rst | 93 |
1 files changed, 48 insertions, 45 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index fa5dd64..fc5bbeb 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -34,7 +34,7 @@ ordered dictionaries. ---------------------- -.. class:: deque([iterable]) +.. class:: deque([iterable[, maxlen]]) Returns a new deque object initialized left-to-right (using :meth:`append`) with data from *iterable*. If *iterable* is not specified, the new deque is empty. @@ -51,6 +51,17 @@ ordered dictionaries. .. versionadded:: 2.4 + If *maxlen* is not specified or is *-1*, deques may grow to an + arbitrary length. Otherwise, the deque is bounded to the specified maximum + length. Once a bounded length deque is full, when new items are added, a + corresponding number of items are discarded from the opposite end. Bounded + length deques provide functionality similar to the ``tail`` filter in + Unix. They are also useful for tracking transactions and other pools of data + where only the most recent activity is of interest. + + .. versionchanged:: 2.6 + Added *maxlen* + Deque objects support the following methods: @@ -168,8 +179,8 @@ Example:: .. _deque-recipes: -Recipes -^^^^^^^ +:class:`deque` Recipes +^^^^^^^^^^^^^^^^^^^^^^ This section shows various approaches to working with deques. @@ -186,42 +197,14 @@ To implement :class:`deque` slicing, use a similar approach applying :meth:`rotate` to bring a target element to the left side of the deque. Remove old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then reverse the rotation. - With minor variations on that approach, it is easy to implement Forth style stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, ``rot``, and ``roll``. -A roundrobin task server can be built from a :class:`deque` using -:meth:`popleft` to select the current task and :meth:`append` to add it back to -the tasklist if the input stream is not exhausted:: - - >>> def roundrobin(*iterables): - ... pending = deque(iter(i) for i in iterables) - ... while pending: - ... task = pending.popleft() - ... try: - ... yield task.next() - ... except StopIteration: - ... continue - ... pending.append(task) - ... - >>> for value in roundrobin('abc', 'd', 'efgh'): - ... print value - - a - d - e - b - f - c - g - h - - Multi-pass data reduction algorithms can be succinctly expressed and efficiently coded by extracting elements with multiple calls to :meth:`popleft`, applying -the reduction function, and calling :meth:`append` to add the result back to the -queue. +a reduction function, and calling :meth:`append` to add the result back to the +deque. For example, building a balanced binary tree of nested lists entails reducing two adjacent nodes into one by grouping them in a list:: @@ -236,7 +219,12 @@ two adjacent nodes into one by grouping them in a list:: >>> print maketree('abcdefgh') [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] +Bounded length deques provide functionality similar to the ``tail`` filter +in Unix:: + def tail(filename, n=10): + 'Return the last n lines of a file' + return deque(open(filename), n) .. _defaultdict-objects: @@ -376,7 +364,8 @@ they add the ability to access fields by name instead of position index. method which lists the tuple contents in a ``name=value`` format. The *fieldnames* are specified in a single string with each fieldname separated by - a space and/or comma. Any valid Python identifier may be used for a fieldname. + a space and/or comma. Any valid Python identifier may be used for a fieldname + except for names starting and ending with double underscores. If *verbose* is true, will print the class definition. @@ -387,7 +376,7 @@ they add the ability to access fields by name instead of position index. Example:: - >>> Point = NamedTuple('Point', 'x y', True) + >>> Point = NamedTuple('Point', 'x y', verbose=True) class Point(tuple): 'Point(x, y)' __slots__ = () @@ -396,6 +385,9 @@ Example:: 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' + return dict(zip(('x', 'y'), self)) def __replace__(self, field, value): 'Return a new Point object replacing one field with a new value' return Point(**dict(zip(('x', 'y'), self) + [(field, value)])) @@ -429,10 +421,25 @@ the values:: >>> Point(*t) # the star-operator unpacks any iterable object Point(x=11, y=22) +When casting a dictionary to a *NamedTuple*, use the double-star-operator:: + + >>> d = {'x': 11, 'y': 22} + >>> Point(**d) + Point(x=11, y=22) + In addition to the methods inherited from tuples, named tuples support -an additonal method and an informational read-only attribute. +additonal methods and a read-only attribute. + +.. method:: somenamedtuple.__asdict__() + + Return a new dict which maps field names to their corresponding values: + +:: -.. method:: somenamedtuple.replace(field, value) + >>> p.__asdict__() + {'x': 11, 'y': 22} + +.. method:: somenamedtuple.__replace__(field, value) Return a new instance of the named tuple replacing the named *field* with a new *value*: @@ -447,20 +454,16 @@ an additonal method and an informational read-only attribute. .. attribute:: somenamedtuple.__fields__ - Return a tuple of strings listing the field names. This is useful for introspection, - for converting a named tuple instance to a dictionary, and for combining named tuple - types to create new named tuple types: + 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') - >>> dict(zip(p.__fields__, p)) # convert to a dictionary - {'y': 22, 'x': 11} >>> Color = NamedTuple('Color', 'red green blue') - >>> pixel_fields = ' '.join(Point.__fields__ + Color.__fields__) # combine fields - >>> Pixel = NamedTuple('Pixel', pixel_fields) + >>> Pixel = NamedTuple('Pixel', ' '.join(Point.__fields__ + Color.__fields__)) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0)' |