diff options
author | Christian Heimes <christian@cheimes.de> | 2008-03-23 21:54:12 (GMT) |
---|---|---|
committer | Christian Heimes <christian@cheimes.de> | 2008-03-23 21:54:12 (GMT) |
commit | fe337bfd0d89c62917e3625111c65f4aa187c6b4 (patch) | |
tree | 5b2b30e195ce4e9b43fc6defe9482fb9f6eabd21 /Doc/library/collections.rst | |
parent | fae759fb276b9e17fe09ecf37ecce618bc9bbb58 (diff) | |
download | cpython-fe337bfd0d89c62917e3625111c65f4aa187c6b4.zip cpython-fe337bfd0d89c62917e3625111c65f4aa187c6b4.tar.gz cpython-fe337bfd0d89c62917e3625111c65f4aa187c6b4.tar.bz2 |
Merged revisions 61724-61725,61731-61735,61737,61739,61741,61743-61744,61753,61761,61765-61767,61769,61773,61776-61778,61780-61783,61788,61793,61796,61807,61813 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
................
r61724 | martin.v.loewis | 2008-03-22 01:01:12 +0100 (Sat, 22 Mar 2008) | 49 lines
Merged revisions 61602-61723 via svnmerge from
svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
........
r61626 | david.wolever | 2008-03-19 17:19:16 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line
Added fixer for implicit local imports. See #2414.
........
r61628 | david.wolever | 2008-03-19 17:57:43 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line
Added a class for tests which should not run if a particular import is found.
........
r61629 | collin.winter | 2008-03-19 17:58:19 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line
Two more relative import fixes in pgen2.
........
r61635 | david.wolever | 2008-03-19 20:16:03 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line
Fixed print fixer so it will do the Right Thing when it encounters __future__.print_function. 2to3 gets upset, though, so the tests have been commented out.
........
r61637 | david.wolever | 2008-03-19 21:37:17 +0100 (Mi, 19 M?\195?\164r 2008) | 3 lines
Added a fixer for itertools imports (from itertools import imap, ifilterfalse --> from itertools import filterfalse)
........
r61645 | david.wolever | 2008-03-19 23:22:35 +0100 (Mi, 19 M?\195?\164r 2008) | 1 line
SVN is happier when you add the files you create... -_-'
........
r61654 | david.wolever | 2008-03-20 01:09:56 +0100 (Do, 20 M?\195?\164r 2008) | 1 line
Added an explicit sort order to fixers -- fixes problems like #2427
........
r61664 | david.wolever | 2008-03-20 04:32:40 +0100 (Do, 20 M?\195?\164r 2008) | 3 lines
Fixes #2428 -- comments are no longer eatten by __future__ fixer.
........
r61673 | david.wolever | 2008-03-20 17:22:40 +0100 (Do, 20 M?\195?\164r 2008) | 1 line
Added 2to3 node pretty-printer
........
r61679 | david.wolever | 2008-03-20 20:50:42 +0100 (Do, 20 M?\195?\164r 2008) | 1 line
Made node printing a little bit prettier
........
r61723 | martin.v.loewis | 2008-03-22 00:59:27 +0100 (Sa, 22 M?\195?\164r 2008) | 2 lines
Fix whitespace.
........
................
r61725 | martin.v.loewis | 2008-03-22 01:02:41 +0100 (Sat, 22 Mar 2008) | 2 lines
Install lib2to3.
................
r61731 | facundo.batista | 2008-03-22 03:45:37 +0100 (Sat, 22 Mar 2008) | 4 lines
Small fix that complicated the test actually when that
test failed.
................
r61732 | alexandre.vassalotti | 2008-03-22 05:08:44 +0100 (Sat, 22 Mar 2008) | 2 lines
Added warning for the removal of 'hotshot' in Py3k.
................
r61733 | georg.brandl | 2008-03-22 11:07:29 +0100 (Sat, 22 Mar 2008) | 4 lines
#1918: document that weak references *to* an object are
cleared before the object's __del__ is called, to ensure that the weak
reference callback (if any) finds the object healthy.
................
r61734 | georg.brandl | 2008-03-22 11:56:23 +0100 (Sat, 22 Mar 2008) | 2 lines
Activate the Sphinx doctest extension and convert howto/functional to use it.
................
r61735 | georg.brandl | 2008-03-22 11:58:38 +0100 (Sat, 22 Mar 2008) | 2 lines
Allow giving source names on the cmdline.
................
r61737 | georg.brandl | 2008-03-22 12:00:48 +0100 (Sat, 22 Mar 2008) | 2 lines
Fixup this HOWTO's doctest blocks so that they can be run with sphinx' doctest builder.
................
r61739 | georg.brandl | 2008-03-22 12:47:10 +0100 (Sat, 22 Mar 2008) | 2 lines
Test decimal.rst doctests as far as possible with sphinx doctest.
................
r61741 | georg.brandl | 2008-03-22 13:04:26 +0100 (Sat, 22 Mar 2008) | 2 lines
Make doctests in re docs usable with sphinx' doctest.
................
r61743 | georg.brandl | 2008-03-22 13:59:37 +0100 (Sat, 22 Mar 2008) | 2 lines
Make more doctests in pprint docs testable.
................
r61744 | georg.brandl | 2008-03-22 14:07:06 +0100 (Sat, 22 Mar 2008) | 2 lines
No need to specify explicit "doctest_block" anymore.
................
r61753 | georg.brandl | 2008-03-22 21:08:43 +0100 (Sat, 22 Mar 2008) | 2 lines
Fix-up syntax problems.
................
r61761 | georg.brandl | 2008-03-22 22:06:20 +0100 (Sat, 22 Mar 2008) | 4 lines
Make collections' doctests executable.
(The <BLANKLINE>s will be stripped from presentation output.)
................
r61765 | georg.brandl | 2008-03-22 22:21:57 +0100 (Sat, 22 Mar 2008) | 2 lines
Test doctests in datetime docs.
................
r61766 | georg.brandl | 2008-03-22 22:26:44 +0100 (Sat, 22 Mar 2008) | 2 lines
Test doctests in operator docs.
................
r61767 | georg.brandl | 2008-03-22 22:38:33 +0100 (Sat, 22 Mar 2008) | 2 lines
Enable doctests in functions.rst. Already found two errors :)
................
r61769 | georg.brandl | 2008-03-22 23:04:10 +0100 (Sat, 22 Mar 2008) | 3 lines
Enable doctest running for several other documents.
We have now over 640 doctests that are run with "make doctest".
................
r61773 | raymond.hettinger | 2008-03-23 01:55:46 +0100 (Sun, 23 Mar 2008) | 1 line
Simplify demo code.
................
r61776 | neal.norwitz | 2008-03-23 04:43:33 +0100 (Sun, 23 Mar 2008) | 7 lines
Try to make this test a little more robust and not fail with:
timeout (10.0025) is more than 2 seconds more than expected (0.001)
I'm assuming this problem is caused by DNS lookup. This change
does a DNS lookup of the hostname before trying to connect, so the time
is not included.
................
r61777 | neal.norwitz | 2008-03-23 05:08:30 +0100 (Sun, 23 Mar 2008) | 1 line
Speed up the test by avoiding socket timeouts.
................
r61778 | neal.norwitz | 2008-03-23 05:43:09 +0100 (Sun, 23 Mar 2008) | 1 line
Skip the epoll test if epoll() does not work
................
r61780 | neal.norwitz | 2008-03-23 06:47:20 +0100 (Sun, 23 Mar 2008) | 1 line
Suppress failure (to avoid a flaky test) if we cannot connect to svn.python.org
................
r61781 | neal.norwitz | 2008-03-23 07:13:25 +0100 (Sun, 23 Mar 2008) | 4 lines
Move itertools before future_builtins since the latter depends on the former.
From a clean build importing future_builtins would fail since itertools
wasn't built yet.
................
r61782 | neal.norwitz | 2008-03-23 07:16:04 +0100 (Sun, 23 Mar 2008) | 1 line
Try to prevent the alarm going off early in tearDown
................
r61783 | neal.norwitz | 2008-03-23 07:19:57 +0100 (Sun, 23 Mar 2008) | 4 lines
Remove compiler warnings (on Alpha at least) about using chars as
array subscripts. Using chars are dangerous b/c they are signed
on some platforms and unsigned on others.
................
r61788 | georg.brandl | 2008-03-23 09:05:30 +0100 (Sun, 23 Mar 2008) | 2 lines
Make the doctests presentation-friendlier.
................
r61793 | amaury.forgeotdarc | 2008-03-23 10:55:29 +0100 (Sun, 23 Mar 2008) | 4 lines
#1477: ur'\U0010FFFF' raised in narrow unicode builds.
Corrected the raw-unicode-escape codec to use UTF-16 surrogates in
this case, just like the unicode-escape codec.
................
r61796 | raymond.hettinger | 2008-03-23 14:32:32 +0100 (Sun, 23 Mar 2008) | 1 line
Issue 1681432: Add triangular distribution the random module.
................
r61807 | raymond.hettinger | 2008-03-23 20:37:53 +0100 (Sun, 23 Mar 2008) | 4 lines
Adopt Nick's suggestion for useful default arguments.
Clean-up floating point issues by adding true division and float constants.
................
r61813 | gregory.p.smith | 2008-03-23 22:04:43 +0100 (Sun, 23 Mar 2008) | 6 lines
Fix gzip to deal with CRC's being signed values in Python 2.x properly and to
read 32bit values as unsigned to start with rather than applying signedness
fixups allover the place afterwards.
This hopefully fixes the test_tarfile failure on the alpha/tru64 buildbot.
................
Diffstat (limited to 'Doc/library/collections.rst')
-rw-r--r-- | Doc/library/collections.rst | 88 |
1 files changed, 48 insertions, 40 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 55b6f37..7966a2e 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -7,6 +7,11 @@ .. moduleauthor:: Raymond Hettinger <python@rcn.com> .. sectionauthor:: Raymond Hettinger <python@rcn.com> +.. testsetup:: * + + from collections import * + import itertools + __name__ = '<doctest>' This module implements high-performance container datatypes. Currently, there are two datatypes, :class:`deque` and :class:`defaultdict`, and @@ -16,14 +21,14 @@ be useful when inheriting directly from :class:`dict` or :class:`list` isn't convenient. The specialized containers provided in this module provide alternatives -to Python's general purpose built-in containers, :class:`dict`, +to Python's general purpose built-in containers, :class:`dict`, :class:`list`, :class:`set`, and :class:`tuple`. Besides the containers provided here, the optional :mod:`bsddb` -module offers the ability to create in-memory or file based ordered +module offers the ability to create in-memory or file based ordered dictionaries with string keys using the :meth:`bsddb.btopen` method. In addition to containers, the collections module provides some ABCs -(abstract base classes). These can be used to test whether a class +(abstract base classes) that can be used to test whether a class provides a particular interface, for example, is it hashable or a mapping, and some of them can also be used as mixin classes. @@ -104,15 +109,15 @@ The ABC supplies the remaining methods such as :meth:`__and__` and Notes on using :class:`Set` and :class:`MutableSet` as a mixin: -(1) +(1) Since some set operations create new sets, the default mixin methods need - a way to create new instances from an iterable. The class constructor is - assumed to have a signature in the form ``ClassName(iterable)``. + a way to create new instances from an iterable. The class constructor is + assumed to have a signature in the form ``ClassName(iterable)``. That assumption is factored-out to a single internal classmethod called :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set. If the :class:`Set` mixin is being used in a class with a different - constructor signature, you will need to override :meth:`from_iterable` - with a classmethod that can construct new instances from + constructor signature, you will need to override :meth:`from_iterable` + with a classmethod that can construct new instances from an iterable argument. (2) @@ -219,12 +224,14 @@ In addition to the above, deques support iteration, pickling, ``len(d)``, ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with the :keyword:`in` operator, and subscript references such as ``d[-1]``. -Example:: +Example: + +.. doctest:: >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements - ... print(elem.upper()) + ... print elem.upper() G H I @@ -303,7 +310,7 @@ 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:: +two adjacent nodes into one by grouping them in a list: >>> def maketree(iterable): ... d = deque(iterable) @@ -375,7 +382,7 @@ standard :class:`dict` operations: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Using :class:`list` as the :attr:`default_factory`, it is easy to group a -sequence of key-value pairs into a dictionary of lists:: +sequence of key-value pairs into a dictionary of lists: >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) @@ -391,7 +398,7 @@ function which returns an empty :class:`list`. The :meth:`list.append` operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the :meth:`list.append` operation adds another value to the list. This technique is -simpler and faster than an equivalent technique using :meth:`dict.setdefault`:: +simpler and faster than an equivalent technique using :meth:`dict.setdefault`: >>> d = {} >>> for k, v in s: @@ -402,7 +409,7 @@ simpler and faster than an equivalent technique using :meth:`dict.setdefault`:: Setting the :attr:`default_factory` to :class:`int` makes the :class:`defaultdict` useful for counting (like a bag or multiset in other -languages):: +languages): >>> s = 'mississippi' >>> d = defaultdict(int) @@ -419,7 +426,7 @@ zero. The increment operation then builds up the count for each letter. The function :func:`int` which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just -zero):: +zero): >>> def constant_factory(value): ... return lambda: value @@ -429,7 +436,7 @@ zero):: 'John ran to <missing>' Setting the :attr:`default_factory` to :class:`set` makes the -:class:`defaultdict` useful for building a dictionary of sets:: +:class:`defaultdict` useful for building a dictionary of sets: >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) @@ -472,41 +479,44 @@ they add the ability to access fields by name instead of position index. Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples. -Example:: +Example: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> Point = namedtuple('Point', 'x y', verbose=True) class Point(tuple): 'Point(x, y)' - + <BLANKLINE> __slots__ = () - + <BLANKLINE> _fields = ('x', 'y') - + <BLANKLINE> def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) - + <BLANKLINE> @classmethod - def _make(cls, iterable): + def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Point object from a sequence or iterable' - result = tuple.__new__(cls, iterable) + result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result - + <BLANKLINE> def __repr__(self): return 'Point(x=%r, y=%r)' % self - + <BLANKLINE> def _asdict(t): 'Return a new dict which maps field names to their values' return {'x': t[0], 'y': t[1]} - + <BLANKLINE> def _replace(self, **kwds): 'Return a new Point object replacing specified fields with new values' result = self._make(map(kwds.pop, ('x', 'y'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result - + <BLANKLINE> x = property(itemgetter(0)) y = property(itemgetter(1)) @@ -545,7 +555,7 @@ field names, the method and attribute names start with an underscore. Class method that makes a new instance from an existing sequence or iterable. -:: +.. doctest:: >>> t = [11, 22] >>> Point._make(t) @@ -553,16 +563,15 @@ field names, the method and attribute names start with an underscore. .. method:: somenamedtuple._asdict() - Return a new dict which maps field names to their corresponding values: - -:: + Return a new dict which maps field names to their corresponding values:: >>> p._asdict() {'x': 11, 'y': 22} - + .. method:: somenamedtuple._replace(kwargs) - Return a new instance of the named tuple replacing specified fields with new values: + Return a new instance of the named tuple replacing specified fields with new + values: :: @@ -578,7 +587,7 @@ field names, the method and attribute names start with an underscore. Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples. -:: +.. doctest:: >>> p._fields # view the field names ('x', 'y') @@ -589,12 +598,12 @@ field names, the method and attribute names start with an underscore. 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:: +function: >>> getattr(p, 'x') 11 -To convert a dictionary to a named tuple, use the double-star-operator [#]_:: +To convert a dictionary to a named tuple, use the double-star-operator [#]_: >>> d = {'x': 11, 'y': 22} >>> Point(**d) @@ -602,7 +611,7 @@ To convert a dictionary to a named tuple, use the double-star-operator [#]_:: Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and -a fixed-width print format:: +a fixed-width print format: >>> class Point(namedtuple('Point', 'x y')): ... __slots__ = () @@ -614,7 +623,6 @@ a fixed-width print format:: >>> for p in Point(3, 4), Point(14, 5/7.): ... print(p) - Point: x= 3.000 y= 4.000 hypot= 5.000 Point: x=14.000 y= 0.714 hypot=14.018 @@ -623,12 +631,12 @@ keep memory requirements low by preventing the creation of instance dictionaries Subclassing is not useful for adding new, stored fields. Instead, simply -create a new named tuple type from the :attr:`_fields` attribute:: +create a new named tuple type from the :attr:`_fields` attribute: >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) Default values can be implemented by using :meth:`_replace` to -customize a prototype instance:: +customize a prototype instance: >>> Account = namedtuple('Account', 'owner balance transaction_count') >>> default_account = Account('<owner name>', 0.0, 0) |