Mercurial > cpython-lru_cache-weakref
annotate Lib/collections.py @ 54294:dba767bc3155 legacy-trunk
remove mention of old ctypes version
| author | Benjamin Peterson <benjamin@python.org> |
|---|---|
| date | Sat, 23 May 2009 20:59:09 +0000 |
| parents | 639a79fa6a23 |
| children | 23a373c8ec1b |
| rev | line source |
|---|---|
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
1 __all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict'] |
|
44330
4a6c06a77deb
Add more namedtuple() test cases. Neaten the code and comments.
Raymond Hettinger <python@rcn.com>
parents:
44303
diff
changeset
|
2 # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py. |
|
4a6c06a77deb
Add more namedtuple() test cases. Neaten the code and comments.
Raymond Hettinger <python@rcn.com>
parents:
44303
diff
changeset
|
3 # They should however be considered an integral part of collections.py. |
|
4a6c06a77deb
Add more namedtuple() test cases. Neaten the code and comments.
Raymond Hettinger <python@rcn.com>
parents:
44303
diff
changeset
|
4 from _abcoll import * |
|
4a6c06a77deb
Add more namedtuple() test cases. Neaten the code and comments.
Raymond Hettinger <python@rcn.com>
parents:
44303
diff
changeset
|
5 import _abcoll |
|
4a6c06a77deb
Add more namedtuple() test cases. Neaten the code and comments.
Raymond Hettinger <python@rcn.com>
parents:
44303
diff
changeset
|
6 __all__ += _abcoll.__all__ |
|
40989
4087c0ec733b
Prepare collections module for pure python code entries.
Raymond Hettinger <python@rcn.com>
parents:
diff
changeset
|
7 |
|
4087c0ec733b
Prepare collections module for pure python code entries.
Raymond Hettinger <python@rcn.com>
parents:
diff
changeset
|
8 from _collections import deque, defaultdict |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
9 from operator import itemgetter as _itemgetter, eq as _eq |
|
43579
046edaa1566a
More docs, error messages, and tests
Raymond Hettinger <python@rcn.com>
parents:
43578
diff
changeset
|
10 from keyword import iskeyword as _iskeyword |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
11 import sys as _sys |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
12 import heapq as _heapq |
|
52286
a1ddb4de85a5
Make imported name private and wrap long-line.
Raymond Hettinger <python@rcn.com>
parents:
52282
diff
changeset
|
13 from weakref import proxy as _proxy |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
14 from itertools import repeat as _repeat, chain as _chain, starmap as _starmap, \ |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
15 ifilter as _ifilter, imap as _imap, izip as _izip |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
16 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
17 ################################################################################ |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
18 ### OrderedDict |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
19 ################################################################################ |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
20 |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
21 class _Link(object): |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
22 __slots__ = 'prev', 'next', 'key', '__weakref__' |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
23 |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
24 class OrderedDict(dict, MutableMapping): |
|
52229
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
25 'Dictionary that remembers insertion order' |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
26 # An inherited dict maps keys to values. |
|
52229
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
27 # The inherited dict provides __getitem__, __len__, __contains__, and get. |
|
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
28 # The remaining methods are order-aware. |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
29 # Big-O running times for all methods are the same as for regular dictionaries. |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
30 |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
31 # The internal self.__map dictionary maps keys to links in a doubly linked list. |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
32 # The circular doubly linked list starts and ends with a sentinel element. |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
33 # The sentinel element never gets deleted (this simplifies the algorithm). |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
34 # The prev/next links are weakref proxies (to prevent circular references). |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
35 # Individual links are kept alive by the hard reference in self.__map. |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
36 # Those hard references disappear when a key is deleted from an OrderedDict. |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
37 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
38 def __init__(self, *args, **kwds): |
| 52982 | 39 '''Initialize an ordered dictionary. Signature is the same as for |
| 40 regular dictionaries, but keyword arguments are not recommended | |
| 41 because their insertion order is arbitrary. | |
| 42 | |
| 43 ''' | |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
44 if len(args) > 1: |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
45 raise TypeError('expected at most 1 arguments, got %d' % len(args)) |
|
51973
982502826f78
Make the underlying data structure more private.
Raymond Hettinger <python@rcn.com>
parents:
51963
diff
changeset
|
46 try: |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
47 self.__root |
|
51973
982502826f78
Make the underlying data structure more private.
Raymond Hettinger <python@rcn.com>
parents:
51963
diff
changeset
|
48 except AttributeError: |
|
52336
f5d670fcdbe9
Separate initialization from clearing.
Raymond Hettinger <python@rcn.com>
parents:
52286
diff
changeset
|
49 self.__root = root = _Link() # sentinel node for the doubly linked list |
|
f5d670fcdbe9
Separate initialization from clearing.
Raymond Hettinger <python@rcn.com>
parents:
52286
diff
changeset
|
50 root.prev = root.next = root |
|
f5d670fcdbe9
Separate initialization from clearing.
Raymond Hettinger <python@rcn.com>
parents:
52286
diff
changeset
|
51 self.__map = {} |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
52 self.update(*args, **kwds) |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
53 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
54 def clear(self): |
| 52982 | 55 'od.clear() -> None. Remove all items from od.' |
|
52282
687e751c288e
Move initialization of root link to __init__.
Raymond Hettinger <python@rcn.com>
parents:
52277
diff
changeset
|
56 root = self.__root |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
57 root.prev = root.next = root |
|
52336
f5d670fcdbe9
Separate initialization from clearing.
Raymond Hettinger <python@rcn.com>
parents:
52286
diff
changeset
|
58 self.__map.clear() |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
59 dict.clear(self) |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
60 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
61 def __setitem__(self, key, value): |
| 52982 | 62 'od.__setitem__(i, y) <==> od[i]=y' |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
63 # Setting a new item creates a new link which goes at the end of the linked |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
64 # list, and the inherited dictionary is updated with the new key/value pair. |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
65 if key not in self: |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
66 self.__map[key] = link = _Link() |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
67 root = self.__root |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
68 last = root.prev |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
69 link.prev, link.next, link.key = last, root, key |
|
52286
a1ddb4de85a5
Make imported name private and wrap long-line.
Raymond Hettinger <python@rcn.com>
parents:
52282
diff
changeset
|
70 last.next = root.prev = _proxy(link) |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
71 dict.__setitem__(self, key, value) |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
72 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
73 def __delitem__(self, key): |
| 52982 | 74 'od.__delitem__(y) <==> del od[y]' |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
75 # Deleting an existing item uses self.__map to find the link which is |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
76 # then removed by updating the links in the predecessor and successor nodes. |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
77 dict.__delitem__(self, key) |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
78 link = self.__map.pop(key) |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
79 link.prev.next = link.next |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
80 link.next.prev = link.prev |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
81 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
82 def __iter__(self): |
| 52982 | 83 'od.__iter__() <==> iter(od)' |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
84 # Traverse the linked list in order. |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
85 root = self.__root |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
86 curr = root.next |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
87 while curr is not root: |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
88 yield curr.key |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
89 curr = curr.next |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
90 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
91 def __reversed__(self): |
| 52982 | 92 'od.__reversed__() <==> reversed(od)' |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
93 # Traverse the linked list in reverse order. |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
94 root = self.__root |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
95 curr = root.prev |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
96 while curr is not root: |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
97 yield curr.key |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
98 curr = curr.prev |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
99 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
100 def __reduce__(self): |
| 52982 | 101 'Return state information for pickling' |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
102 items = [[k, self[k]] for k in self] |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
103 tmp = self.__map, self.__root |
|
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
104 del self.__map, self.__root |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
105 inst_dict = vars(self).copy() |
|
52277
119e3fc6cdf3
Add more comments. Improve variable names.
Raymond Hettinger <python@rcn.com>
parents:
52231
diff
changeset
|
106 self.__map, self.__root = tmp |
|
51988
778599ce81a1
Backport 70140, 70141, 70143, and 70144.
Raymond Hettinger <python@rcn.com>
parents:
51974
diff
changeset
|
107 if inst_dict: |
|
778599ce81a1
Backport 70140, 70141, 70143, and 70144.
Raymond Hettinger <python@rcn.com>
parents:
51974
diff
changeset
|
108 return (self.__class__, (items,), inst_dict) |
|
778599ce81a1
Backport 70140, 70141, 70143, and 70144.
Raymond Hettinger <python@rcn.com>
parents:
51974
diff
changeset
|
109 return self.__class__, (items,) |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
110 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
111 setdefault = MutableMapping.setdefault |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
112 update = MutableMapping.update |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
113 pop = MutableMapping.pop |
|
52222
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
114 keys = MutableMapping.keys |
|
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
115 values = MutableMapping.values |
|
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
116 items = MutableMapping.items |
|
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
117 iterkeys = MutableMapping.iterkeys |
|
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
118 itervalues = MutableMapping.itervalues |
|
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
119 iteritems = MutableMapping.iteritems |
|
7cfbbf2d294e
Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0)
Raymond Hettinger <python@rcn.com>
parents:
51988
diff
changeset
|
120 __ne__ = MutableMapping.__ne__ |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
121 |
|
52229
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
122 def popitem(self, last=True): |
| 52982 | 123 '''od.popitem() -> (k, v), return and remove a (key, value) pair. |
| 124 Pairs are returned in LIFO order if last is true or FIFO order if false. | |
| 125 | |
| 126 ''' | |
|
52229
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
127 if not self: |
|
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
128 raise KeyError('dictionary is empty') |
| 52985 | 129 key = next(reversed(self) if last else iter(self)) |
|
52229
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
130 value = self.pop(key) |
|
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
131 return key, value |
|
290c7513e125
* Add implementation notes.
Raymond Hettinger <python@rcn.com>
parents:
52227
diff
changeset
|
132 |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
133 def __repr__(self): |
| 52982 | 134 'od.__repr__() <==> repr(od)' |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
135 if not self: |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
136 return '%s()' % (self.__class__.__name__,) |
| 51974 | 137 return '%s(%r)' % (self.__class__.__name__, self.items()) |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
138 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
139 def copy(self): |
| 52982 | 140 'od.copy() -> a shallow copy of od' |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
141 return self.__class__(self) |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
142 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
143 @classmethod |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
144 def fromkeys(cls, iterable, value=None): |
| 52982 | 145 '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S |
| 146 and values equal to v (which defaults to None). | |
| 147 | |
| 148 ''' | |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
149 d = cls() |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
150 for key in iterable: |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
151 d[key] = value |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
152 return d |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
153 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
154 def __eq__(self, other): |
| 52982 | 155 '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive |
| 156 while comparison to a regular mapping is order-insensitive. | |
| 157 | |
| 158 ''' | |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
159 if isinstance(other, OrderedDict): |
|
52286
a1ddb4de85a5
Make imported name private and wrap long-line.
Raymond Hettinger <python@rcn.com>
parents:
52282
diff
changeset
|
160 return len(self)==len(other) and \ |
|
a1ddb4de85a5
Make imported name private and wrap long-line.
Raymond Hettinger <python@rcn.com>
parents:
52282
diff
changeset
|
161 all(_imap(_eq, self.iteritems(), other.iteritems())) |
|
51962
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
162 return dict.__eq__(self, other) |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
163 |
|
4a4da968de2a
Backport PEP 372: OrderedDict()
Raymond Hettinger <python@rcn.com>
parents:
51499
diff
changeset
|
164 |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
165 |
|
50924
8d66b82a10a3
Make merging easier by formattng comment blocks the same in Py3.1
Raymond Hettinger <python@rcn.com>
parents:
50923
diff
changeset
|
166 ################################################################################ |
|
8d66b82a10a3
Make merging easier by formattng comment blocks the same in Py3.1
Raymond Hettinger <python@rcn.com>
parents:
50923
diff
changeset
|
167 ### namedtuple |
|
8d66b82a10a3
Make merging easier by formattng comment blocks the same in Py3.1
Raymond Hettinger <python@rcn.com>
parents:
50923
diff
changeset
|
168 ################################################################################ |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
169 |
|
51499
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
170 def namedtuple(typename, field_names, verbose=False, rename=False): |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
171 """Returns a new subclass of tuple with named fields. |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
172 |
|
43654
a0983f55c957
Shorter name for namedtuple()
Raymond Hettinger <python@rcn.com>
parents:
43579
diff
changeset
|
173 >>> Point = namedtuple('Point', 'x y') |
|
43377
2e7dd201ea1d
Sync-up named tuples with the latest version of the ASPN recipe.
Raymond Hettinger <python@rcn.com>
parents:
41801
diff
changeset
|
174 >>> Point.__doc__ # docstring for the new class |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
175 'Point(x, y)' |
|
43377
2e7dd201ea1d
Sync-up named tuples with the latest version of the ASPN recipe.
Raymond Hettinger <python@rcn.com>
parents:
41801
diff
changeset
|
176 >>> p = Point(11, y=22) # instantiate with positional args or keywords |
|
44343
f8d0faffce88
Simplify and speedup _asdict() for named tuples.
Raymond Hettinger <python@rcn.com>
parents:
44330
diff
changeset
|
177 >>> p[0] + p[1] # indexable like a plain tuple |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
178 33 |
|
44330
4a6c06a77deb
Add more namedtuple() test cases. Neaten the code and comments.
Raymond Hettinger <python@rcn.com>
parents:
44303
diff
changeset
|
179 >>> x, y = p # unpack like a regular tuple |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
180 >>> x, y |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
181 (11, 22) |
|
43377
2e7dd201ea1d
Sync-up named tuples with the latest version of the ASPN recipe.
Raymond Hettinger <python@rcn.com>
parents:
41801
diff
changeset
|
182 >>> p.x + p.y # fields also accessable by name |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
183 33 |
|
44294
294b1a79f201
Cleaner method naming convention
Raymond Hettinger <python@rcn.com>
parents:
44290
diff
changeset
|
184 >>> d = p._asdict() # convert to a dictionary |
|
43466
73f49656420b
Add __asdict__() to NamedTuple and refine the docs.
Raymond Hettinger <python@rcn.com>
parents:
43388
diff
changeset
|
185 >>> d['x'] |
|
73f49656420b
Add __asdict__() to NamedTuple and refine the docs.
Raymond Hettinger <python@rcn.com>
parents:
43388
diff
changeset
|
186 11 |
|
73f49656420b
Add __asdict__() to NamedTuple and refine the docs.
Raymond Hettinger <python@rcn.com>
parents:
43388
diff
changeset
|
187 >>> Point(**d) # convert from a dictionary |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
188 Point(x=11, y=22) |
|
44294
294b1a79f201
Cleaner method naming convention
Raymond Hettinger <python@rcn.com>
parents:
44290
diff
changeset
|
189 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
|
43377
2e7dd201ea1d
Sync-up named tuples with the latest version of the ASPN recipe.
Raymond Hettinger <python@rcn.com>
parents:
41801
diff
changeset
|
190 Point(x=100, y=22) |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
191 |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
192 """ |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
193 |
| 44590 | 194 # Parse and validate the field names. Validation serves two purposes, |
| 195 # generating informative error messages and preventing template injection attacks. | |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
196 if isinstance(field_names, basestring): |
| 43496 | 197 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas |
|
49301
f323fa4e48d7
Fix namedtuple bug reported by Glenn Linderman. Template did not form correctly if the field names were input in Unicode.
Raymond Hettinger <python@rcn.com>
parents:
47526
diff
changeset
|
198 field_names = tuple(map(str, field_names)) |
|
51499
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
199 if rename: |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
200 names = list(field_names) |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
201 seen = set() |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
202 for i, name in enumerate(names): |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
203 if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name) |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
204 or not name or name[0].isdigit() or name.startswith('_') |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
205 or name in seen): |
|
52751
20e7aa42d6fe
Have namedtuple's field renamer assign names that
Raymond Hettinger <python@rcn.com>
parents:
52336
diff
changeset
|
206 names[i] = '_%d' % i |
|
51499
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
207 seen.add(name) |
|
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
208 field_names = tuple(names) |
|
43578
4060047b3f1d
Improve error messages
Raymond Hettinger <python@rcn.com>
parents:
43502
diff
changeset
|
209 for name in (typename,) + field_names: |
|
44178
9340698ae421
Error checking was too aggressive (reported by Chris Tismer)
Raymond Hettinger <python@rcn.com>
parents:
43958
diff
changeset
|
210 if not all(c.isalnum() or c=='_' for c in name): |
|
43578
4060047b3f1d
Improve error messages
Raymond Hettinger <python@rcn.com>
parents:
43502
diff
changeset
|
211 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) |
|
43579
046edaa1566a
More docs, error messages, and tests
Raymond Hettinger <python@rcn.com>
parents:
43578
diff
changeset
|
212 if _iskeyword(name): |
|
046edaa1566a
More docs, error messages, and tests
Raymond Hettinger <python@rcn.com>
parents:
43578
diff
changeset
|
213 raise ValueError('Type names and field names cannot be a keyword: %r' % name) |
|
43578
4060047b3f1d
Improve error messages
Raymond Hettinger <python@rcn.com>
parents:
43502
diff
changeset
|
214 if name[0].isdigit(): |
|
4060047b3f1d
Improve error messages
Raymond Hettinger <python@rcn.com>
parents:
43502
diff
changeset
|
215 raise ValueError('Type names and field names cannot start with a number: %r' % name) |
|
43502
ebf2a5cf13fb
Make the error messages more specific
Raymond Hettinger <python@rcn.com>
parents:
43500
diff
changeset
|
216 seen_names = set() |
|
ebf2a5cf13fb
Make the error messages more specific
Raymond Hettinger <python@rcn.com>
parents:
43500
diff
changeset
|
217 for name in field_names: |
|
51499
beef8818a66c
Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames.
Raymond Hettinger <python@rcn.com>
parents:
51110
diff
changeset
|
218 if name.startswith('_') and not rename: |
|
44294
294b1a79f201
Cleaner method naming convention
Raymond Hettinger <python@rcn.com>
parents:
44290
diff
changeset
|
219 raise ValueError('Field names cannot start with an underscore: %r' % name) |
|
43502
ebf2a5cf13fb
Make the error messages more specific
Raymond Hettinger <python@rcn.com>
parents:
43500
diff
changeset
|
220 if name in seen_names: |
|
43578
4060047b3f1d
Improve error messages
Raymond Hettinger <python@rcn.com>
parents:
43502
diff
changeset
|
221 raise ValueError('Encountered duplicate field name: %r' % name) |
|
43502
ebf2a5cf13fb
Make the error messages more specific
Raymond Hettinger <python@rcn.com>
parents:
43500
diff
changeset
|
222 seen_names.add(name) |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
223 |
|
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
224 # Create and fill-in the class template |
|
44484
dcc7c865c77b
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Raymond Hettinger <python@rcn.com>
parents:
44464
diff
changeset
|
225 numfields = len(field_names) |
|
43388
2fdff0b5beb6
Handle corner cased on 0-tuples and 1-tuples. Add verbose option so people can see how it works.
Raymond Hettinger <python@rcn.com>
parents:
43377
diff
changeset
|
226 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes |
|
41774
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
227 reprtxt = ', '.join('%s=%%r' % name for name in field_names) |
|
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
228 template = '''class %(typename)s(tuple): |
|
44299
905a96997b7c
Add line spacing for readability
Raymond Hettinger <python@rcn.com>
parents:
44294
diff
changeset
|
229 '%(typename)s(%(argtxt)s)' \n |
|
905a96997b7c
Add line spacing for readability
Raymond Hettinger <python@rcn.com>
parents:
44294
diff
changeset
|
230 __slots__ = () \n |
|
44464
398b6246759f
Minor fix-ups to named tuples:
Raymond Hettinger <python@rcn.com>
parents:
44345
diff
changeset
|
231 _fields = %(field_names)r \n |
|
41774
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
232 def __new__(cls, %(argtxt)s): |
|
44299
905a96997b7c
Add line spacing for readability
Raymond Hettinger <python@rcn.com>
parents:
44294
diff
changeset
|
233 return tuple.__new__(cls, (%(argtxt)s)) \n |
|
44484
dcc7c865c77b
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Raymond Hettinger <python@rcn.com>
parents:
44464
diff
changeset
|
234 @classmethod |
|
44546
974f0320d6b3
Speed-up named tuple's _make() constructor.
Raymond Hettinger <python@rcn.com>
parents:
44517
diff
changeset
|
235 def _make(cls, iterable, new=tuple.__new__, len=len): |
|
44484
dcc7c865c77b
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Raymond Hettinger <python@rcn.com>
parents:
44464
diff
changeset
|
236 'Make a new %(typename)s object from a sequence or iterable' |
|
44546
974f0320d6b3
Speed-up named tuple's _make() constructor.
Raymond Hettinger <python@rcn.com>
parents:
44517
diff
changeset
|
237 result = new(cls, iterable) |
|
44484
dcc7c865c77b
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Raymond Hettinger <python@rcn.com>
parents:
44464
diff
changeset
|
238 if len(result) != %(numfields)d: |
|
dcc7c865c77b
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Raymond Hettinger <python@rcn.com>
parents:
44464
diff
changeset
|
239 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) |
|
dcc7c865c77b
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Raymond Hettinger <python@rcn.com>
parents:
44464
diff
changeset
|
240 return result \n |
|
41774
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
241 def __repr__(self): |
|
44299
905a96997b7c
Add line spacing for readability
Raymond Hettinger <python@rcn.com>
parents:
44294
diff
changeset
|
242 return '%(typename)s(%(reprtxt)s)' %% self \n |
|
51963
0c635574b139
Backport 70106: Add OrderedDict support to collections.namedtuple().
Raymond Hettinger <python@rcn.com>
parents:
51962
diff
changeset
|
243 def _asdict(self): |
|
0c635574b139
Backport 70106: Add OrderedDict support to collections.namedtuple().
Raymond Hettinger <python@rcn.com>
parents:
51962
diff
changeset
|
244 'Return a new OrderedDict which maps field names to their values' |
|
0c635574b139
Backport 70106: Add OrderedDict support to collections.namedtuple().
Raymond Hettinger <python@rcn.com>
parents:
51962
diff
changeset
|
245 return OrderedDict(zip(self._fields, self)) \n |
|
44294
294b1a79f201
Cleaner method naming convention
Raymond Hettinger <python@rcn.com>
parents:
44290
diff
changeset
|
246 def _replace(self, **kwds): |
|
43856
98795738b4c2
Accept Issac Morland's suggestion for __replace__ to allow multiple replacements
Raymond Hettinger <python@rcn.com>
parents:
43852
diff
changeset
|
247 'Return a new %(typename)s object replacing specified fields with new values' |
|
44517
7a2065b5be75
Small code simplification. Forgot that classmethods can be called from intances.
Raymond Hettinger <python@rcn.com>
parents:
44485
diff
changeset
|
248 result = self._make(map(kwds.pop, %(field_names)r, self)) |
|
44485
7bb91b3ba0ec
Add error-checking to namedtuple's _replace() method.
Raymond Hettinger <python@rcn.com>
parents:
44484
diff
changeset
|
249 if kwds: |
|
7bb91b3ba0ec
Add error-checking to namedtuple's _replace() method.
Raymond Hettinger <python@rcn.com>
parents:
44484
diff
changeset
|
250 raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) |
|
47526
246a802637ad
Issue3065: Fixed pickling of named tuples. Added tests.
Raymond Hettinger <python@rcn.com>
parents:
47387
diff
changeset
|
251 return result \n |
|
246a802637ad
Issue3065: Fixed pickling of named tuples. Added tests.
Raymond Hettinger <python@rcn.com>
parents:
47387
diff
changeset
|
252 def __getnewargs__(self): |
|
246a802637ad
Issue3065: Fixed pickling of named tuples. Added tests.
Raymond Hettinger <python@rcn.com>
parents:
47387
diff
changeset
|
253 return tuple(self) \n\n''' % locals() |
|
41774
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
254 for i, name in enumerate(field_names): |
|
43388
2fdff0b5beb6
Handle corner cased on 0-tuples and 1-tuples. Add verbose option so people can see how it works.
Raymond Hettinger <python@rcn.com>
parents:
43377
diff
changeset
|
255 template += ' %s = property(itemgetter(%d))\n' % (name, i) |
|
2fdff0b5beb6
Handle corner cased on 0-tuples and 1-tuples. Add verbose option so people can see how it works.
Raymond Hettinger <python@rcn.com>
parents:
43377
diff
changeset
|
256 if verbose: |
|
2fdff0b5beb6
Handle corner cased on 0-tuples and 1-tuples. Add verbose option so people can see how it works.
Raymond Hettinger <python@rcn.com>
parents:
43377
diff
changeset
|
257 print template |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
258 |
|
47387
33865bb58396
Issue 2903: Add __name__ in globals for namedtuple namespace.
Raymond Hettinger <python@rcn.com>
parents:
44625
diff
changeset
|
259 # Execute the template string in a temporary namespace and |
|
33865bb58396
Issue 2903: Add __name__ in globals for namedtuple namespace.
Raymond Hettinger <python@rcn.com>
parents:
44625
diff
changeset
|
260 # support tracing utilities by setting a value for frame.f_globals['__name__'] |
|
51963
0c635574b139
Backport 70106: Add OrderedDict support to collections.namedtuple().
Raymond Hettinger <python@rcn.com>
parents:
51962
diff
changeset
|
261 namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename, |
|
0c635574b139
Backport 70106: Add OrderedDict support to collections.namedtuple().
Raymond Hettinger <python@rcn.com>
parents:
51962
diff
changeset
|
262 OrderedDict=OrderedDict) |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
263 try: |
| 43496 | 264 exec template in namespace |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
265 except SyntaxError, e: |
|
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
266 raise SyntaxError(e.message + ':\n' + template) |
| 43496 | 267 result = namespace[typename] |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
268 |
|
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
269 # For pickling to work, the __module__ variable needs to be set to the frame |
|
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
270 # where the named tuple is created. Bypass this step in enviroments where |
|
53760
639a79fa6a23
using sys._getframe(x), where x > 0 doesnt' work on IronPython
Benjamin Peterson <benjamin@python.org>
parents:
52985
diff
changeset
|
271 # sys._getframe is not defined (Jython for example) or sys._getframe is not |
|
639a79fa6a23
using sys._getframe(x), where x > 0 doesnt' work on IronPython
Benjamin Peterson <benjamin@python.org>
parents:
52985
diff
changeset
|
272 # defined for arguments greater than 0 (IronPython). |
|
639a79fa6a23
using sys._getframe(x), where x > 0 doesnt' work on IronPython
Benjamin Peterson <benjamin@python.org>
parents:
52985
diff
changeset
|
273 try: |
|
51110
a28765fd32f0
Issue 5021: doctest.testfile should set __name__
Raymond Hettinger <python@rcn.com>
parents:
50972
diff
changeset
|
274 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') |
|
53760
639a79fa6a23
using sys._getframe(x), where x > 0 doesnt' work on IronPython
Benjamin Peterson <benjamin@python.org>
parents:
52985
diff
changeset
|
275 except (AttributeError, ValueError): |
|
639a79fa6a23
using sys._getframe(x), where x > 0 doesnt' work on IronPython
Benjamin Peterson <benjamin@python.org>
parents:
52985
diff
changeset
|
276 pass |
|
43494
4db5dab7f235
Add comments to NamedTuple code.
Raymond Hettinger <python@rcn.com>
parents:
43466
diff
changeset
|
277 |
|
41774
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
278 return result |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
279 |
|
41774
4a3a63769d34
Improvements to NamedTuple's implementation, tests, and documentation
Raymond Hettinger <python@rcn.com>
parents:
40992
diff
changeset
|
280 |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
281 ######################################################################## |
|
50924
8d66b82a10a3
Make merging easier by formattng comment blocks the same in Py3.1
Raymond Hettinger <python@rcn.com>
parents:
50923
diff
changeset
|
282 ### Counter |
|
8d66b82a10a3
Make merging easier by formattng comment blocks the same in Py3.1
Raymond Hettinger <python@rcn.com>
parents:
50923
diff
changeset
|
283 ######################################################################## |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
284 |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
285 class Counter(dict): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
286 '''Dict subclass for counting hashable items. Sometimes called a bag |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
287 or multiset. Elements are stored as dictionary keys and their counts |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
288 are stored as dictionary values. |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
289 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
290 >>> c = Counter('abracadabra') # count elements from a string |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
291 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
292 >>> c.most_common(3) # three most common elements |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
293 [('a', 5), ('r', 2), ('b', 2)] |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
294 >>> sorted(c) # list all unique elements |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
295 ['a', 'b', 'c', 'd', 'r'] |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
296 >>> ''.join(sorted(c.elements())) # list elements with repetitions |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
297 'aaaaabbcdrr' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
298 >>> sum(c.values()) # total of all counts |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
299 11 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
300 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
301 >>> c['a'] # count of letter 'a' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
302 5 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
303 >>> for elem in 'shazam': # update counts from an iterable |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
304 ... c[elem] += 1 # by adding 1 to each element's count |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
305 >>> c['a'] # now there are seven 'a' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
306 7 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
307 >>> del c['r'] # remove all 'r' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
308 >>> c['r'] # now there are zero 'r' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
309 0 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
310 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
311 >>> d = Counter('simsalabim') # make another counter |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
312 >>> c.update(d) # add in the second counter |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
313 >>> c['a'] # now there are nine 'a' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
314 9 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
315 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
316 >>> c.clear() # empty the counter |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
317 >>> c |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
318 Counter() |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
319 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
320 Note: If a count is set to zero or reduced to zero, it will remain |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
321 in the counter until the entry is deleted or the counter is cleared: |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
322 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
323 >>> c = Counter('aaabbc') |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
324 >>> c['b'] -= 2 # reduce the count of 'b' by two |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
325 >>> c.most_common() # 'b' is still in, but its count is zero |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
326 [('a', 3), ('c', 1), ('b', 0)] |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
327 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
328 ''' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
329 # References: |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
330 # http://en.wikipedia.org/wiki/Multiset |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
331 # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
332 # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
333 # http://code.activestate.com/recipes/259174/ |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
334 # Knuth, TAOCP Vol. II section 4.6.3 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
335 |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
336 def __init__(self, iterable=None, **kwds): |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
337 '''Create a new, empty Counter object. And if given, count elements |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
338 from an input iterable. Or, initialize the count from another mapping |
|
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
339 of elements to their counts. |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
340 |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
341 >>> c = Counter() # a new, empty counter |
|
50760
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
342 >>> c = Counter('gallahad') # a new counter from an iterable |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
343 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
344 >>> c = Counter(a=4, b=2) # a new counter from keyword args |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
345 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
346 ''' |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
347 self.update(iterable, **kwds) |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
348 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
349 def __missing__(self, key): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
350 'The count of elements not in the Counter is zero.' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
351 # Needed so that self[missing_item] does not raise KeyError |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
352 return 0 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
353 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
354 def most_common(self, n=None): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
355 '''List the n most common elements and their counts from the most |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
356 common to the least. If n is None, then list all element counts. |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
357 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
358 >>> Counter('abracadabra').most_common(3) |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
359 [('a', 5), ('r', 2), ('b', 2)] |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
360 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
361 ''' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
362 # Emulate Bag.sortedByCount from Smalltalk |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
363 if n is None: |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
364 return sorted(self.iteritems(), key=_itemgetter(1), reverse=True) |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
365 return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1)) |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
366 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
367 def elements(self): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
368 '''Iterator over elements repeating each as many times as its count. |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
369 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
370 >>> c = Counter('ABCABC') |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
371 >>> sorted(c.elements()) |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
372 ['A', 'A', 'B', 'B', 'C', 'C'] |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
373 |
|
50760
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
374 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
375 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
376 >>> product = 1 |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
377 >>> for factor in prime_factors.elements(): # loop over factors |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
378 ... product *= factor # and multiply them |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
379 >>> product |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
380 1836 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
381 |
|
50760
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
382 Note, if an element's count has been set to zero or is a negative |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
383 number, elements() will ignore it. |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
384 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
385 ''' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
386 # Emulate Bag.do from Smalltalk and Multiset.begin from C++. |
|
50761
e5f996cda321
Speed-up __repr__. Eliminate duplicate tests. Use a from-irmport.
Raymond Hettinger <python@rcn.com>
parents:
50760
diff
changeset
|
387 return _chain.from_iterable(_starmap(_repeat, self.iteritems())) |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
388 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
389 # Override dict methods where necessary |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
390 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
391 @classmethod |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
392 def fromkeys(cls, iterable, v=None): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
393 # There is no equivalent method for counters because setting v=1 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
394 # means that no element can have a count greater than one. |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
395 raise NotImplementedError( |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
396 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
397 |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
398 def update(self, iterable=None, **kwds): |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
399 '''Like dict.update() but add counts instead of replacing them. |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
400 |
|
50760
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
401 Source can be an iterable, a dictionary, or another Counter instance. |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
402 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
403 >>> c = Counter('which') |
|
50760
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
404 >>> c.update('witch') # add elements from another iterable |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
405 >>> d = Counter('watch') |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
406 >>> c.update(d) # add elements from another counter |
|
e301141e91b1
Fixup and simplify docstrings and doctests.
Raymond Hettinger <python@rcn.com>
parents:
50756
diff
changeset
|
407 >>> c['h'] # four 'h' in which, witch, and watch |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
408 4 |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
409 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
410 ''' |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
411 # The regular dict.update() operation makes no sense here because the |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
412 # replace behavior results in the some of original untouched counts |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
413 # being mixed-in with all of the other counts for a mismash that |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
414 # doesn't have a straight-forward interpretation in most counting |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
415 # contexts. Instead, we implement straight-addition. Both the inputs |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
416 # and outputs are allowed to contain zero and negative counts. |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
417 |
|
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
418 if iterable is not None: |
|
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
419 if isinstance(iterable, Mapping): |
|
50972
3f13c65aec05
Update comments and add an optimized path for Counter.update().
Raymond Hettinger <python@rcn.com>
parents:
50964
diff
changeset
|
420 if self: |
|
3f13c65aec05
Update comments and add an optimized path for Counter.update().
Raymond Hettinger <python@rcn.com>
parents:
50964
diff
changeset
|
421 for elem, count in iterable.iteritems(): |
|
3f13c65aec05
Update comments and add an optimized path for Counter.update().
Raymond Hettinger <python@rcn.com>
parents:
50964
diff
changeset
|
422 self[elem] += count |
|
3f13c65aec05
Update comments and add an optimized path for Counter.update().
Raymond Hettinger <python@rcn.com>
parents:
50964
diff
changeset
|
423 else: |
|
3f13c65aec05
Update comments and add an optimized path for Counter.update().
Raymond Hettinger <python@rcn.com>
parents:
50964
diff
changeset
|
424 dict.update(self, iterable) # fast path when counter is empty |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
425 else: |
|
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
426 for elem in iterable: |
|
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
427 self[elem] += 1 |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
428 if kwds: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
429 self.update(kwds) |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
430 |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
431 def copy(self): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
432 'Like dict.copy() but returns a Counter instance instead of a dict.' |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
433 return Counter(self) |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
434 |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
435 def __delitem__(self, elem): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
436 'Like dict.__delitem__() but does not raise KeyError for missing values.' |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
437 if elem in self: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
438 dict.__delitem__(self, elem) |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
439 |
|
50753
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
440 def __repr__(self): |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
441 if not self: |
|
5934612d5070
Issue 1696199: Add collections.Counter().
Raymond Hettinger <python@rcn.com>
parents:
49301
diff
changeset
|
442 return '%s()' % self.__class__.__name__ |
|
50761
e5f996cda321
Speed-up __repr__. Eliminate duplicate tests. Use a from-irmport.
Raymond Hettinger <python@rcn.com>
parents:
50760
diff
changeset
|
443 items = ', '.join(map('%r: %r'.__mod__, self.most_common())) |
|
50756
f45997d9ac55
Simplify Counter() API. Replace items keyword argument
Raymond Hettinger <python@rcn.com>
parents:
50753
diff
changeset
|
444 return '%s({%s})' % (self.__class__.__name__, items) |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
445 |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
446 # Multiset-style mathematical operations discussed in: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
447 # Knuth TAOCP Volume II section 4.6.3 exercise 19 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
448 # and at http://en.wikipedia.org/wiki/Multiset |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
449 # |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
450 # Outputs guaranteed to only include positive counts. |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
451 # |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
452 # To strip negative and zero counts, add-in an empty counter: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
453 # c += Counter() |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
454 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
455 def __add__(self, other): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
456 '''Add counts from two counters. |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
457 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
458 >>> Counter('abbb') + Counter('bcc') |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
459 Counter({'b': 4, 'c': 2, 'a': 1}) |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
460 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
461 ''' |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
462 if not isinstance(other, Counter): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
463 return NotImplemented |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
464 result = Counter() |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
465 for elem in set(self) | set(other): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
466 newcount = self[elem] + other[elem] |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
467 if newcount > 0: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
468 result[elem] = newcount |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
469 return result |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
470 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
471 def __sub__(self, other): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
472 ''' Subtract count, but keep only results with positive counts. |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
473 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
474 >>> Counter('abbbc') - Counter('bccd') |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
475 Counter({'b': 2, 'a': 1}) |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
476 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
477 ''' |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
478 if not isinstance(other, Counter): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
479 return NotImplemented |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
480 result = Counter() |
|
50964
8bf204af9691
Simplify explanation of multiset operations by removing restrictions on negative inputs.
Raymond Hettinger <python@rcn.com>
parents:
50924
diff
changeset
|
481 for elem in set(self) | set(other): |
|
8bf204af9691
Simplify explanation of multiset operations by removing restrictions on negative inputs.
Raymond Hettinger <python@rcn.com>
parents:
50924
diff
changeset
|
482 newcount = self[elem] - other[elem] |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
483 if newcount > 0: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
484 result[elem] = newcount |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
485 return result |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
486 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
487 def __or__(self, other): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
488 '''Union is the maximum of value in either of the input counters. |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
489 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
490 >>> Counter('abbb') | Counter('bcc') |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
491 Counter({'b': 3, 'c': 2, 'a': 1}) |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
492 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
493 ''' |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
494 if not isinstance(other, Counter): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
495 return NotImplemented |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
496 result = Counter() |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
497 for elem in set(self) | set(other): |
|
52800
5f66dead1175
Replace the localized min/max calls with normal if/else
Raymond Hettinger <python@rcn.com>
parents:
52751
diff
changeset
|
498 p, q = self[elem], other[elem] |
|
5f66dead1175
Replace the localized min/max calls with normal if/else
Raymond Hettinger <python@rcn.com>
parents:
52751
diff
changeset
|
499 newcount = q if p < q else p |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
500 if newcount > 0: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
501 result[elem] = newcount |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
502 return result |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
503 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
504 def __and__(self, other): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
505 ''' Intersection is the minimum of corresponding counts. |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
506 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
507 >>> Counter('abbb') & Counter('bcc') |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
508 Counter({'b': 1}) |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
509 |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
510 ''' |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
511 if not isinstance(other, Counter): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
512 return NotImplemented |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
513 result = Counter() |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
514 if len(self) < len(other): |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
515 self, other = other, self |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
516 for elem in _ifilter(self.__contains__, other): |
|
52800
5f66dead1175
Replace the localized min/max calls with normal if/else
Raymond Hettinger <python@rcn.com>
parents:
52751
diff
changeset
|
517 p, q = self[elem], other[elem] |
|
5f66dead1175
Replace the localized min/max calls with normal if/else
Raymond Hettinger <python@rcn.com>
parents:
52751
diff
changeset
|
518 newcount = p if p < q else q |
|
50920
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
519 if newcount > 0: |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
520 result[elem] = newcount |
|
191b7b3ddf4f
Build-outs for Counter() class:
Raymond Hettinger <python@rcn.com>
parents:
50761
diff
changeset
|
521 return result |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
522 |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
523 |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
524 if __name__ == '__main__': |
|
43377
2e7dd201ea1d
Sync-up named tuples with the latest version of the ASPN recipe.
Raymond Hettinger <python@rcn.com>
parents:
41801
diff
changeset
|
525 # verify that instances can be pickled |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
526 from cPickle import loads, dumps |
|
43654
a0983f55c957
Shorter name for namedtuple()
Raymond Hettinger <python@rcn.com>
parents:
43579
diff
changeset
|
527 Point = namedtuple('Point', 'x, y', True) |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
528 p = Point(x=10, y=20) |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
529 assert p == loads(dumps(p)) |
|
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
530 |
|
43856
98795738b4c2
Accept Issac Morland's suggestion for __replace__ to allow multiple replacements
Raymond Hettinger <python@rcn.com>
parents:
43852
diff
changeset
|
531 # test and demonstrate ability to override methods |
|
44549
a8697afbf17e
Add subclassing example to docs for named tuples.
Raymond Hettinger <python@rcn.com>
parents:
44546
diff
changeset
|
532 class Point(namedtuple('Point', 'x y')): |
|
44622
c3113914e66e
Examples for named tuple subclassing should include __slots__
Raymond Hettinger <python@rcn.com>
parents:
44590
diff
changeset
|
533 __slots__ = () |
|
44549
a8697afbf17e
Add subclassing example to docs for named tuples.
Raymond Hettinger <python@rcn.com>
parents:
44546
diff
changeset
|
534 @property |
|
a8697afbf17e
Add subclassing example to docs for named tuples.
Raymond Hettinger <python@rcn.com>
parents:
44546
diff
changeset
|
535 def hypot(self): |
|
a8697afbf17e
Add subclassing example to docs for named tuples.
Raymond Hettinger <python@rcn.com>
parents:
44546
diff
changeset
|
536 return (self.x ** 2 + self.y ** 2) ** 0.5 |
|
44582
c75d360ab87b
Cleanup named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44552
diff
changeset
|
537 def __str__(self): |
|
44625
69f495082412
Neaten-up the named tuple docs
Raymond Hettinger <python@rcn.com>
parents:
44623
diff
changeset
|
538 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
|
44549
a8697afbf17e
Add subclassing example to docs for named tuples.
Raymond Hettinger <python@rcn.com>
parents:
44546
diff
changeset
|
539 |
|
44622
c3113914e66e
Examples for named tuple subclassing should include __slots__
Raymond Hettinger <python@rcn.com>
parents:
44590
diff
changeset
|
540 for p in Point(3, 4), Point(14, 5/7.): |
|
44582
c75d360ab87b
Cleanup named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44552
diff
changeset
|
541 print p |
|
43856
98795738b4c2
Accept Issac Morland's suggestion for __replace__ to allow multiple replacements
Raymond Hettinger <python@rcn.com>
parents:
43852
diff
changeset
|
542 |
|
44552
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
543 class Point(namedtuple('Point', 'x y')): |
|
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
544 'Point class with optimized _make() and _replace() without error-checking' |
|
44622
c3113914e66e
Examples for named tuple subclassing should include __slots__
Raymond Hettinger <python@rcn.com>
parents:
44590
diff
changeset
|
545 __slots__ = () |
|
44552
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
546 _make = classmethod(tuple.__new__) |
|
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
547 def _replace(self, _map=map, **kwds): |
|
44585
42cf59ccce66
Use get() instead of pop() for the optimized version of _replace().
Raymond Hettinger <python@rcn.com>
parents:
44582
diff
changeset
|
548 return self._make(_map(kwds.get, ('x', 'y'), self)) |
|
44552
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
549 |
|
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
550 print Point(11, 22)._replace(x=100) |
|
b6ea52993cae
Add another named tuple subclassing example.
Raymond Hettinger <python@rcn.com>
parents:
44550
diff
changeset
|
551 |
|
44623
dbafcd827979
Clarify how to add a field to a named tuple.
Raymond Hettinger <python@rcn.com>
parents:
44622
diff
changeset
|
552 Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
|
dbafcd827979
Clarify how to add a field to a named tuple.
Raymond Hettinger <python@rcn.com>
parents:
44622
diff
changeset
|
553 print Point3D.__doc__ |
|
dbafcd827979
Clarify how to add a field to a named tuple.
Raymond Hettinger <python@rcn.com>
parents:
44622
diff
changeset
|
554 |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
555 import doctest |
|
43654
a0983f55c957
Shorter name for namedtuple()
Raymond Hettinger <python@rcn.com>
parents:
43579
diff
changeset
|
556 TestResults = namedtuple('TestResults', 'failed attempted') |
|
40992
b46c6d27625e
Add collections.NamedTuple
Raymond Hettinger <python@rcn.com>
parents:
40989
diff
changeset
|
557 print TestResults(*doctest.testmod()) |
