Brett Cannon | 23a4a7b | 2008-05-12 00:56:28 +0000 | [diff] [blame] | 1 | __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', |
Benjamin Peterson | c92f622 | 2011-09-11 12:55:34 -0400 | [diff] [blame] | 2 | 'UserString', 'Counter', 'OrderedDict', 'ChainMap'] |
Raymond Hettinger | 158c9c2 | 2011-02-22 00:41:50 +0000 | [diff] [blame] | 3 | |
Ezio Melotti | 3730892 | 2011-03-15 06:03:08 +0200 | [diff] [blame] | 4 | # For backwards compatibility, continue to make the collections ABCs |
Raymond Hettinger | 158c9c2 | 2011-02-22 00:41:50 +0000 | [diff] [blame] | 5 | # available through the collections module. |
| 6 | from collections.abc import * |
| 7 | import collections.abc |
| 8 | __all__ += collections.abc.__all__ |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 9 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 10 | from _collections import deque, defaultdict |
Raymond Hettinger | 1c2018c | 2012-06-09 22:51:39 -0700 | [diff] [blame] | 11 | from operator import itemgetter as _itemgetter, eq as _eq |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 12 | from keyword import iskeyword as _iskeyword |
| 13 | import sys as _sys |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 14 | import heapq as _heapq |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 15 | from weakref import proxy as _proxy |
Raymond Hettinger | ea9f8db | 2009-03-02 21:28:41 +0000 | [diff] [blame] | 16 | from itertools import repeat as _repeat, chain as _chain, starmap as _starmap |
Raymond Hettinger | 98a5f3f | 2010-09-13 21:36:00 +0000 | [diff] [blame] | 17 | from reprlib import recursive_repr as _recursive_repr |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 18 | |
| 19 | ################################################################################ |
| 20 | ### OrderedDict |
| 21 | ################################################################################ |
| 22 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 23 | class _Link(object): |
| 24 | __slots__ = 'prev', 'next', 'key', '__weakref__' |
| 25 | |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 26 | class OrderedDict(dict): |
Raymond Hettinger | 18ed2cb | 2009-03-19 23:14:39 +0000 | [diff] [blame] | 27 | 'Dictionary that remembers insertion order' |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 28 | # An inherited dict maps keys to values. |
Raymond Hettinger | 18ed2cb | 2009-03-19 23:14:39 +0000 | [diff] [blame] | 29 | # The inherited dict provides __getitem__, __len__, __contains__, and get. |
| 30 | # The remaining methods are order-aware. |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 31 | # Big-O running times for all methods are the same as regular dictionaries. |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 32 | |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 33 | # The internal self.__map dict maps keys to links in a doubly linked list. |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 34 | # The circular doubly linked list starts and ends with a sentinel element. |
| 35 | # The sentinel element never gets deleted (this simplifies the algorithm). |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 36 | # The sentinel is in self.__hardroot with a weakref proxy in self.__root. |
Raymond Hettinger | eaac4f0 | 2012-01-26 00:14:16 -0800 | [diff] [blame] | 37 | # The prev links are weakref proxies (to prevent circular references). |
Raymond Hettinger | c5c29c0 | 2010-09-12 18:13:46 +0000 | [diff] [blame] | 38 | # Individual links are kept alive by the hard reference in self.__map. |
| 39 | # Those hard references disappear when a key is deleted from an OrderedDict. |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 40 | |
| 41 | def __init__(self, *args, **kwds): |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 42 | '''Initialize an ordered dictionary. The signature is the same as |
| 43 | regular dictionaries, but keyword arguments are not recommended because |
| 44 | their insertion order is arbitrary. |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 45 | |
| 46 | ''' |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 47 | if len(args) > 1: |
| 48 | raise TypeError('expected at most 1 arguments, got %d' % len(args)) |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame] | 49 | try: |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 50 | self.__root |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame] | 51 | except AttributeError: |
Raymond Hettinger | f7328d0 | 2010-09-14 19:40:15 +0000 | [diff] [blame] | 52 | self.__hardroot = _Link() |
| 53 | self.__root = root = _proxy(self.__hardroot) |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 54 | root.prev = root.next = root |
Raymond Hettinger | 52dc06b | 2009-03-25 22:45:22 +0000 | [diff] [blame] | 55 | self.__map = {} |
Raymond Hettinger | 32062e9 | 2011-01-01 22:38:00 +0000 | [diff] [blame] | 56 | self.__update(*args, **kwds) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 57 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 58 | def __setitem__(self, key, value, |
| 59 | dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 60 | 'od.__setitem__(i, y) <==> od[i]=y' |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 61 | # Setting a new item creates a new link at the end of the linked list, |
| 62 | # and the inherited dictionary is updated with the new key/value pair. |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 63 | if key not in self: |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 64 | self.__map[key] = link = Link() |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 65 | root = self.__root |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 66 | last = root.prev |
| 67 | link.prev, link.next, link.key = last, root, key |
Raymond Hettinger | f7328d0 | 2010-09-14 19:40:15 +0000 | [diff] [blame] | 68 | last.next = link |
| 69 | root.prev = proxy(link) |
| 70 | dict_setitem(self, key, value) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 71 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 72 | def __delitem__(self, key, dict_delitem=dict.__delitem__): |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 73 | 'od.__delitem__(y) <==> del od[y]' |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 74 | # Deleting an existing item uses self.__map to find the link which gets |
| 75 | # removed by updating the links in the predecessor and successor nodes. |
Raymond Hettinger | 5be21b7 | 2010-08-01 22:10:57 +0000 | [diff] [blame] | 76 | dict_delitem(self, key) |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 77 | link = self.__map.pop(key) |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 78 | link_prev = link.prev |
| 79 | link_next = link.next |
| 80 | link_prev.next = link_next |
| 81 | link_next.prev = link_prev |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 82 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 83 | def __iter__(self): |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 84 | 'od.__iter__() <==> iter(od)' |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 85 | # Traverse the linked list in order. |
| 86 | root = self.__root |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 87 | curr = root.next |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 88 | while curr is not root: |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 89 | yield curr.key |
| 90 | curr = curr.next |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 91 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 92 | def __reversed__(self): |
Raymond Hettinger | 2352cf3 | 2009-04-08 01:16:27 +0000 | [diff] [blame] | 93 | 'od.__reversed__() <==> reversed(od)' |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 94 | # Traverse the linked list in reverse order. |
| 95 | root = self.__root |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 96 | curr = root.prev |
Raymond Hettinger | f173654 | 2009-03-23 05:19:21 +0000 | [diff] [blame] | 97 | while curr is not root: |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 98 | yield curr.key |
| 99 | curr = curr.prev |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 100 | |
Raymond Hettinger | 5be21b7 | 2010-08-01 22:10:57 +0000 | [diff] [blame] | 101 | def clear(self): |
| 102 | 'od.clear() -> None. Remove all items from od.' |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 103 | root = self.__root |
| 104 | root.prev = root.next = root |
| 105 | self.__map.clear() |
Raymond Hettinger | 5be21b7 | 2010-08-01 22:10:57 +0000 | [diff] [blame] | 106 | dict.clear(self) |
| 107 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 108 | def popitem(self, last=True): |
Raymond Hettinger | 331722d | 2010-09-02 18:44:16 +0000 | [diff] [blame] | 109 | '''od.popitem() -> (k, v), return and remove a (key, value) pair. |
| 110 | Pairs are returned in LIFO order if last is true or FIFO order if false. |
| 111 | |
| 112 | ''' |
| 113 | if not self: |
| 114 | raise KeyError('dictionary is empty') |
| 115 | root = self.__root |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 116 | if last: |
| 117 | link = root.prev |
| 118 | link_prev = link.prev |
| 119 | link_prev.next = root |
| 120 | root.prev = link_prev |
| 121 | else: |
| 122 | link = root.next |
| 123 | link_next = link.next |
| 124 | root.next = link_next |
| 125 | link_next.prev = root |
| 126 | key = link.key |
Raymond Hettinger | 331722d | 2010-09-02 18:44:16 +0000 | [diff] [blame] | 127 | del self.__map[key] |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 128 | value = dict.pop(self, key) |
Raymond Hettinger | 331722d | 2010-09-02 18:44:16 +0000 | [diff] [blame] | 129 | return key, value |
| 130 | |
Raymond Hettinger | fa11db0 | 2010-09-12 04:12:42 +0000 | [diff] [blame] | 131 | def move_to_end(self, key, last=True): |
| 132 | '''Move an existing element to the end (or beginning if last==False). |
| 133 | |
| 134 | Raises KeyError if the element does not exist. |
| 135 | When last=True, acts like a fast version of self[key]=self.pop(key). |
| 136 | |
| 137 | ''' |
| 138 | link = self.__map[key] |
| 139 | link_prev = link.prev |
| 140 | link_next = link.next |
| 141 | link_prev.next = link_next |
| 142 | link_next.prev = link_prev |
| 143 | root = self.__root |
| 144 | if last: |
| 145 | last = root.prev |
| 146 | link.prev = last |
| 147 | link.next = root |
| 148 | last.next = root.prev = link |
| 149 | else: |
| 150 | first = root.next |
| 151 | link.prev = root |
| 152 | link.next = first |
| 153 | root.next = first.prev = link |
| 154 | |
Raymond Hettinger | 35c87f2 | 2010-09-16 19:10:17 +0000 | [diff] [blame] | 155 | def __sizeof__(self): |
| 156 | sizeof = _sys.getsizeof |
| 157 | n = len(self) + 1 # number of links including root |
| 158 | size = sizeof(self.__dict__) # instance dictionary |
| 159 | size += sizeof(self.__map) * 2 # internal dict and inherited dict |
| 160 | size += sizeof(self.__hardroot) * n # link objects |
| 161 | size += sizeof(self.__root) * n # proxy objects |
| 162 | return size |
| 163 | |
Raymond Hettinger | 32062e9 | 2011-01-01 22:38:00 +0000 | [diff] [blame] | 164 | update = __update = MutableMapping.update |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 165 | keys = MutableMapping.keys |
| 166 | values = MutableMapping.values |
| 167 | items = MutableMapping.items |
Raymond Hettinger | 5be21b7 | 2010-08-01 22:10:57 +0000 | [diff] [blame] | 168 | __ne__ = MutableMapping.__ne__ |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 169 | |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 170 | __marker = object() |
| 171 | |
| 172 | def pop(self, key, default=__marker): |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 173 | '''od.pop(k[,d]) -> v, remove specified key and return the corresponding |
| 174 | value. If key is not found, d is returned if given, otherwise KeyError |
| 175 | is raised. |
| 176 | |
| 177 | ''' |
Raymond Hettinger | 345c49b | 2011-01-01 23:51:55 +0000 | [diff] [blame] | 178 | if key in self: |
| 179 | result = self[key] |
| 180 | del self[key] |
| 181 | return result |
| 182 | if default is self.__marker: |
| 183 | raise KeyError(key) |
| 184 | return default |
| 185 | |
Raymond Hettinger | a673b1f | 2010-12-31 23:16:17 +0000 | [diff] [blame] | 186 | def setdefault(self, key, default=None): |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 187 | 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' |
Raymond Hettinger | a673b1f | 2010-12-31 23:16:17 +0000 | [diff] [blame] | 188 | if key in self: |
| 189 | return self[key] |
| 190 | self[key] = default |
| 191 | return default |
| 192 | |
Raymond Hettinger | 98a5f3f | 2010-09-13 21:36:00 +0000 | [diff] [blame] | 193 | @_recursive_repr() |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 194 | def __repr__(self): |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 195 | 'od.__repr__() <==> repr(od)' |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 196 | if not self: |
| 197 | return '%s()' % (self.__class__.__name__,) |
Raymond Hettinger | 98a5f3f | 2010-09-13 21:36:00 +0000 | [diff] [blame] | 198 | return '%s(%r)' % (self.__class__.__name__, list(self.items())) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 199 | |
Raymond Hettinger | fc330ae | 2011-04-20 13:03:49 -0700 | [diff] [blame] | 200 | def __reduce__(self): |
| 201 | 'Return state information for pickling' |
| 202 | items = [[k, self[k]] for k in self] |
| 203 | inst_dict = vars(self).copy() |
| 204 | for k in vars(OrderedDict()): |
| 205 | inst_dict.pop(k, None) |
| 206 | if inst_dict: |
| 207 | return (self.__class__, (items,), inst_dict) |
| 208 | return self.__class__, (items,) |
| 209 | |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 210 | def copy(self): |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 211 | 'od.copy() -> a shallow copy of od' |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 212 | return self.__class__(self) |
| 213 | |
| 214 | @classmethod |
| 215 | def fromkeys(cls, iterable, value=None): |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 216 | '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. |
| 217 | If not specified, the value defaults to None. |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 218 | |
| 219 | ''' |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 220 | self = cls() |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 221 | for key in iterable: |
Raymond Hettinger | a82aa55 | 2011-04-24 14:34:26 -0700 | [diff] [blame] | 222 | self[key] = value |
| 223 | return self |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 224 | |
| 225 | def __eq__(self, other): |
Raymond Hettinger | f04fa1b | 2009-04-08 01:15:02 +0000 | [diff] [blame] | 226 | '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive |
| 227 | while comparison to a regular mapping is order-insensitive. |
| 228 | |
| 229 | ''' |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 230 | if isinstance(other, OrderedDict): |
Raymond Hettinger | 325dc88 | 2013-03-23 06:34:19 -0700 | [diff] [blame] | 231 | return dict.__eq__(self, other) and all(map(_eq, self, other)) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 232 | return dict.__eq__(self, other) |
| 233 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 234 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 235 | ################################################################################ |
| 236 | ### namedtuple |
| 237 | ################################################################################ |
| 238 | |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 239 | _class_template = '''\ |
Raymond Hettinger | 843a751 | 2011-03-23 11:49:56 -0700 | [diff] [blame] | 240 | from builtins import property as _property, tuple as _tuple |
| 241 | from operator import itemgetter as _itemgetter |
| 242 | from collections import OrderedDict |
| 243 | |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 244 | class {typename}(tuple): |
| 245 | '{typename}({arg_list})' |
| 246 | |
| 247 | __slots__ = () |
| 248 | |
| 249 | _fields = {field_names!r} |
| 250 | |
| 251 | def __new__(_cls, {arg_list}): |
| 252 | 'Create new instance of {typename}({arg_list})' |
| 253 | return _tuple.__new__(_cls, ({arg_list})) |
| 254 | |
| 255 | @classmethod |
| 256 | def _make(cls, iterable, new=tuple.__new__, len=len): |
| 257 | 'Make a new {typename} object from a sequence or iterable' |
| 258 | result = new(cls, iterable) |
| 259 | if len(result) != {num_fields:d}: |
| 260 | raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result)) |
| 261 | return result |
| 262 | |
| 263 | def __repr__(self): |
| 264 | 'Return a nicely formatted representation string' |
| 265 | return self.__class__.__name__ + '({repr_fmt})' % self |
| 266 | |
| 267 | def _asdict(self): |
| 268 | 'Return a new OrderedDict which maps field names to their values' |
| 269 | return OrderedDict(zip(self._fields, self)) |
| 270 | |
Raymond Hettinger | 3d89057 | 2011-06-02 23:40:24 -0700 | [diff] [blame] | 271 | __dict__ = property(_asdict) |
| 272 | |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 273 | def _replace(_self, **kwds): |
| 274 | 'Return a new {typename} object replacing specified fields with new values' |
| 275 | result = _self._make(map(kwds.pop, {field_names!r}, _self)) |
| 276 | if kwds: |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 277 | raise ValueError('Got unexpected field names: %r' % list(kwds)) |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 278 | return result |
| 279 | |
| 280 | def __getnewargs__(self): |
| 281 | 'Return self as a plain tuple. Used by copy and pickle.' |
| 282 | return tuple(self) |
| 283 | |
| 284 | {field_defs} |
| 285 | ''' |
| 286 | |
| 287 | _repr_template = '{name}=%r' |
| 288 | |
| 289 | _field_template = '''\ |
| 290 | {name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}') |
| 291 | ''' |
| 292 | |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 293 | def namedtuple(typename, field_names, verbose=False, rename=False): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 294 | """Returns a new subclass of tuple with named fields. |
| 295 | |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 296 | >>> Point = namedtuple('Point', ['x', 'y']) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 297 | >>> Point.__doc__ # docstring for the new class |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 298 | 'Point(x, y)' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 299 | >>> p = Point(11, y=22) # instantiate with positional args or keywords |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 300 | >>> p[0] + p[1] # indexable like a plain tuple |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 301 | 33 |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 302 | >>> x, y = p # unpack like a regular tuple |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 303 | >>> x, y |
| 304 | (11, 22) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 305 | >>> p.x + p.y # fields also accessable by name |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 306 | 33 |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 307 | >>> d = p._asdict() # convert to a dictionary |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 308 | >>> d['x'] |
| 309 | 11 |
| 310 | >>> Point(**d) # convert from a dictionary |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 311 | Point(x=11, y=22) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 312 | >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 313 | Point(x=100, y=22) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 314 | |
| 315 | """ |
| 316 | |
Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 317 | # Validate the field names. At the user's option, either generate an error |
| 318 | # message or automatically replace the field name with a valid name. |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 319 | if isinstance(field_names, str): |
Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 320 | field_names = field_names.replace(',', ' ').split() |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 321 | field_names = list(map(str, field_names)) |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 322 | if rename: |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 323 | seen = set() |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 324 | for index, name in enumerate(field_names): |
Raymond Hettinger | 4f4ba16 | 2013-03-01 23:43:48 -0800 | [diff] [blame] | 325 | if (not name.isidentifier() |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 326 | or _iskeyword(name) |
Raymond Hettinger | 15d0c1d | 2011-03-23 14:38:39 -0700 | [diff] [blame] | 327 | or name.startswith('_') |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 328 | or name in seen): |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 329 | field_names[index] = '_%d' % index |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 330 | seen.add(name) |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 331 | for name in [typename] + field_names: |
Raymond Hettinger | 4f4ba16 | 2013-03-01 23:43:48 -0800 | [diff] [blame] | 332 | if not name.isidentifier(): |
| 333 | raise ValueError('Type names and field names must be valid ' |
| 334 | 'identifiers: %r' % name) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 335 | if _iskeyword(name): |
Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 336 | raise ValueError('Type names and field names cannot be a ' |
| 337 | 'keyword: %r' % name) |
Raymond Hettinger | 2ebea41 | 2011-03-23 12:52:23 -0700 | [diff] [blame] | 338 | seen = set() |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 339 | for name in field_names: |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 340 | if name.startswith('_') and not rename: |
Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 341 | raise ValueError('Field names cannot start with an underscore: ' |
| 342 | '%r' % name) |
Raymond Hettinger | 2ebea41 | 2011-03-23 12:52:23 -0700 | [diff] [blame] | 343 | if name in seen: |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 344 | raise ValueError('Encountered duplicate field name: %r' % name) |
Raymond Hettinger | 2ebea41 | 2011-03-23 12:52:23 -0700 | [diff] [blame] | 345 | seen.add(name) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 346 | |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 347 | # Fill-in the class template |
| 348 | class_definition = _class_template.format( |
Raymond Hettinger | 3e82ae0 | 2011-03-22 14:21:38 -0700 | [diff] [blame] | 349 | typename = typename, |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 350 | field_names = tuple(field_names), |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 351 | num_fields = len(field_names), |
Raymond Hettinger | b2d0945 | 2011-03-22 22:36:21 -0700 | [diff] [blame] | 352 | arg_list = repr(tuple(field_names)).replace("'", "")[1:-1], |
Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 353 | repr_fmt = ', '.join(_repr_template.format(name=name) |
| 354 | for name in field_names), |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 355 | field_defs = '\n'.join(_field_template.format(index=index, name=name) |
| 356 | for index, name in enumerate(field_names)) |
Raymond Hettinger | 3e82ae0 | 2011-03-22 14:21:38 -0700 | [diff] [blame] | 357 | ) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 358 | |
Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 359 | # Execute the template string in a temporary namespace and support |
| 360 | # tracing utilities by setting a value for frame.f_globals['__name__'] |
Raymond Hettinger | f6d3e8e | 2011-03-23 20:33:30 -0700 | [diff] [blame] | 361 | namespace = dict(__name__='namedtuple_%s' % typename) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 362 | try: |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 363 | exec(class_definition, namespace) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 364 | except SyntaxError as e: |
Raymond Hettinger | fef8546 | 2011-03-22 21:14:41 -0700 | [diff] [blame] | 365 | raise SyntaxError(e.msg + ':\n\n' + class_definition) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 366 | result = namespace[typename] |
Raymond Hettinger | 2ebea41 | 2011-03-23 12:52:23 -0700 | [diff] [blame] | 367 | result._source = class_definition |
| 368 | if verbose: |
| 369 | print(result._source) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 370 | |
| 371 | # For pickling to work, the __module__ variable needs to be set to the frame |
| 372 | # where the named tuple is created. Bypass this step in enviroments where |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 373 | # sys._getframe is not defined (Jython for example) or sys._getframe is not |
| 374 | # defined for arguments greater than 0 (IronPython). |
| 375 | try: |
Raymond Hettinger | 0f05517 | 2009-01-27 10:06:09 +0000 | [diff] [blame] | 376 | result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 377 | except (AttributeError, ValueError): |
| 378 | pass |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 379 | |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 380 | return result |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 381 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 382 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 383 | ######################################################################## |
| 384 | ### Counter |
| 385 | ######################################################################## |
| 386 | |
Raymond Hettinger | 96f3410 | 2010-12-15 16:30:37 +0000 | [diff] [blame] | 387 | def _count_elements(mapping, iterable): |
| 388 | 'Tally elements from the iterable.' |
| 389 | mapping_get = mapping.get |
| 390 | for elem in iterable: |
| 391 | mapping[elem] = mapping_get(elem, 0) + 1 |
| 392 | |
| 393 | try: # Load C helper function if available |
| 394 | from _collections import _count_elements |
| 395 | except ImportError: |
| 396 | pass |
| 397 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 398 | class Counter(dict): |
| 399 | '''Dict subclass for counting hashable items. Sometimes called a bag |
| 400 | or multiset. Elements are stored as dictionary keys and their counts |
| 401 | are stored as dictionary values. |
| 402 | |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 403 | >>> c = Counter('abcdeabcdabcaba') # count elements from a string |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 404 | |
| 405 | >>> c.most_common(3) # three most common elements |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 406 | [('a', 5), ('b', 4), ('c', 3)] |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 407 | >>> sorted(c) # list all unique elements |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 408 | ['a', 'b', 'c', 'd', 'e'] |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 409 | >>> ''.join(sorted(c.elements())) # list elements with repetitions |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 410 | 'aaaaabbbbcccdde' |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 411 | >>> sum(c.values()) # total of all counts |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 412 | 15 |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 413 | |
| 414 | >>> c['a'] # count of letter 'a' |
| 415 | 5 |
| 416 | >>> for elem in 'shazam': # update counts from an iterable |
| 417 | ... c[elem] += 1 # by adding 1 to each element's count |
| 418 | >>> c['a'] # now there are seven 'a' |
| 419 | 7 |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 420 | >>> del c['b'] # remove all 'b' |
| 421 | >>> c['b'] # now there are zero 'b' |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 422 | 0 |
| 423 | |
| 424 | >>> d = Counter('simsalabim') # make another counter |
| 425 | >>> c.update(d) # add in the second counter |
| 426 | >>> c['a'] # now there are nine 'a' |
| 427 | 9 |
| 428 | |
| 429 | >>> c.clear() # empty the counter |
| 430 | >>> c |
| 431 | Counter() |
| 432 | |
| 433 | Note: If a count is set to zero or reduced to zero, it will remain |
| 434 | in the counter until the entry is deleted or the counter is cleared: |
| 435 | |
| 436 | >>> c = Counter('aaabbc') |
| 437 | >>> c['b'] -= 2 # reduce the count of 'b' by two |
| 438 | >>> c.most_common() # 'b' is still in, but its count is zero |
| 439 | [('a', 3), ('c', 1), ('b', 0)] |
| 440 | |
| 441 | ''' |
| 442 | # References: |
| 443 | # http://en.wikipedia.org/wiki/Multiset |
| 444 | # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html |
| 445 | # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm |
| 446 | # http://code.activestate.com/recipes/259174/ |
| 447 | # Knuth, TAOCP Vol. II section 4.6.3 |
| 448 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 449 | def __init__(self, iterable=None, **kwds): |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 450 | '''Create a new, empty Counter object. And if given, count elements |
| 451 | from an input iterable. Or, initialize the count from another mapping |
| 452 | of elements to their counts. |
| 453 | |
| 454 | >>> c = Counter() # a new, empty counter |
| 455 | >>> c = Counter('gallahad') # a new counter from an iterable |
| 456 | >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 457 | >>> c = Counter(a=4, b=2) # a new counter from keyword args |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 458 | |
| 459 | ''' |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 460 | super().__init__() |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 461 | self.update(iterable, **kwds) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 462 | |
| 463 | def __missing__(self, key): |
| 464 | 'The count of elements not in the Counter is zero.' |
| 465 | # Needed so that self[missing_item] does not raise KeyError |
| 466 | return 0 |
| 467 | |
| 468 | def most_common(self, n=None): |
| 469 | '''List the n most common elements and their counts from the most |
| 470 | common to the least. If n is None, then list all element counts. |
| 471 | |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 472 | >>> Counter('abcdeabcdabcaba').most_common(3) |
| 473 | [('a', 5), ('b', 4), ('c', 3)] |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 474 | |
| 475 | ''' |
| 476 | # Emulate Bag.sortedByCount from Smalltalk |
| 477 | if n is None: |
| 478 | return sorted(self.items(), key=_itemgetter(1), reverse=True) |
| 479 | return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) |
| 480 | |
| 481 | def elements(self): |
| 482 | '''Iterator over elements repeating each as many times as its count. |
| 483 | |
| 484 | >>> c = Counter('ABCABC') |
| 485 | >>> sorted(c.elements()) |
| 486 | ['A', 'A', 'B', 'B', 'C', 'C'] |
| 487 | |
| 488 | # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 |
| 489 | >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) |
| 490 | >>> product = 1 |
| 491 | >>> for factor in prime_factors.elements(): # loop over factors |
| 492 | ... product *= factor # and multiply them |
| 493 | >>> product |
| 494 | 1836 |
| 495 | |
| 496 | Note, if an element's count has been set to zero or is a negative |
| 497 | number, elements() will ignore it. |
| 498 | |
| 499 | ''' |
| 500 | # Emulate Bag.do from Smalltalk and Multiset.begin from C++. |
| 501 | return _chain.from_iterable(_starmap(_repeat, self.items())) |
| 502 | |
| 503 | # Override dict methods where necessary |
| 504 | |
| 505 | @classmethod |
| 506 | def fromkeys(cls, iterable, v=None): |
| 507 | # There is no equivalent method for counters because setting v=1 |
| 508 | # means that no element can have a count greater than one. |
| 509 | raise NotImplementedError( |
| 510 | 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
| 511 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 512 | def update(self, iterable=None, **kwds): |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 513 | '''Like dict.update() but add counts instead of replacing them. |
| 514 | |
| 515 | Source can be an iterable, a dictionary, or another Counter instance. |
| 516 | |
| 517 | >>> c = Counter('which') |
| 518 | >>> c.update('witch') # add elements from another iterable |
| 519 | >>> d = Counter('watch') |
| 520 | >>> c.update(d) # add elements from another counter |
| 521 | >>> c['h'] # four 'h' in which, witch, and watch |
| 522 | 4 |
| 523 | |
| 524 | ''' |
| 525 | # The regular dict.update() operation makes no sense here because the |
| 526 | # replace behavior results in the some of original untouched counts |
| 527 | # being mixed-in with all of the other counts for a mismash that |
| 528 | # doesn't have a straight-forward interpretation in most counting |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 529 | # contexts. Instead, we implement straight-addition. Both the inputs |
| 530 | # and outputs are allowed to contain zero and negative counts. |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 531 | |
| 532 | if iterable is not None: |
| 533 | if isinstance(iterable, Mapping): |
Raymond Hettinger | dd01f8f | 2009-01-22 09:09:55 +0000 | [diff] [blame] | 534 | if self: |
Raymond Hettinger | f909202 | 2009-06-29 18:30:43 +0000 | [diff] [blame] | 535 | self_get = self.get |
Raymond Hettinger | dd01f8f | 2009-01-22 09:09:55 +0000 | [diff] [blame] | 536 | for elem, count in iterable.items(): |
Raymond Hettinger | f909202 | 2009-06-29 18:30:43 +0000 | [diff] [blame] | 537 | self[elem] = count + self_get(elem, 0) |
Raymond Hettinger | dd01f8f | 2009-01-22 09:09:55 +0000 | [diff] [blame] | 538 | else: |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 539 | super().update(iterable) # fast path when counter is empty |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 540 | else: |
Raymond Hettinger | 96f3410 | 2010-12-15 16:30:37 +0000 | [diff] [blame] | 541 | _count_elements(self, iterable) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 542 | if kwds: |
| 543 | self.update(kwds) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 544 | |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 545 | def subtract(self, iterable=None, **kwds): |
| 546 | '''Like dict.update() but subtracts counts instead of replacing them. |
| 547 | Counts can be reduced below zero. Both the inputs and outputs are |
| 548 | allowed to contain zero and negative counts. |
| 549 | |
| 550 | Source can be an iterable, a dictionary, or another Counter instance. |
| 551 | |
| 552 | >>> c = Counter('which') |
| 553 | >>> c.subtract('witch') # subtract elements from another iterable |
| 554 | >>> c.subtract(Counter('watch')) # subtract elements from another counter |
| 555 | >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch |
| 556 | 0 |
| 557 | >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch |
| 558 | -1 |
| 559 | |
| 560 | ''' |
| 561 | if iterable is not None: |
Raymond Hettinger | fc3c9cd | 2010-04-11 20:41:56 +0000 | [diff] [blame] | 562 | self_get = self.get |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 563 | if isinstance(iterable, Mapping): |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 564 | for elem, count in iterable.items(): |
| 565 | self[elem] = self_get(elem, 0) - count |
| 566 | else: |
Raymond Hettinger | 9c01e44 | 2010-04-03 10:32:58 +0000 | [diff] [blame] | 567 | for elem in iterable: |
| 568 | self[elem] = self_get(elem, 0) - 1 |
| 569 | if kwds: |
| 570 | self.subtract(kwds) |
| 571 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 572 | def copy(self): |
Raymond Hettinger | 1c746c2 | 2011-04-15 13:16:46 -0700 | [diff] [blame] | 573 | 'Return a shallow copy.' |
| 574 | return self.__class__(self) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 575 | |
Raymond Hettinger | ff72816 | 2011-01-03 02:44:14 +0000 | [diff] [blame] | 576 | def __reduce__(self): |
| 577 | return self.__class__, (dict(self),) |
| 578 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 579 | def __delitem__(self, elem): |
| 580 | 'Like dict.__delitem__() but does not raise KeyError for missing values.' |
| 581 | if elem in self: |
Raymond Hettinger | 00d43fd | 2011-01-02 08:03:33 +0000 | [diff] [blame] | 582 | super().__delitem__(elem) |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 583 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 584 | def __repr__(self): |
| 585 | if not self: |
| 586 | return '%s()' % self.__class__.__name__ |
Raymond Hettinger | 4e6bf41 | 2011-11-05 13:35:26 -0700 | [diff] [blame] | 587 | try: |
| 588 | items = ', '.join(map('%r: %r'.__mod__, self.most_common())) |
| 589 | return '%s({%s})' % (self.__class__.__name__, items) |
| 590 | except TypeError: |
| 591 | # handle case where values are not orderable |
| 592 | return '{0}({1!r})'.format(self.__class__.__name__, dict(self)) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 593 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 594 | # Multiset-style mathematical operations discussed in: |
| 595 | # Knuth TAOCP Volume II section 4.6.3 exercise 19 |
| 596 | # and at http://en.wikipedia.org/wiki/Multiset |
| 597 | # |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 598 | # Outputs guaranteed to only include positive counts. |
| 599 | # |
| 600 | # To strip negative and zero counts, add-in an empty counter: |
| 601 | # c += Counter() |
| 602 | |
| 603 | def __add__(self, other): |
| 604 | '''Add counts from two counters. |
| 605 | |
| 606 | >>> Counter('abbb') + Counter('bcc') |
| 607 | Counter({'b': 4, 'c': 2, 'a': 1}) |
| 608 | |
| 609 | ''' |
| 610 | if not isinstance(other, Counter): |
| 611 | return NotImplemented |
| 612 | result = Counter() |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 613 | for elem, count in self.items(): |
| 614 | newcount = count + other[elem] |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 615 | if newcount > 0: |
| 616 | result[elem] = newcount |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 617 | for elem, count in other.items(): |
| 618 | if elem not in self and count > 0: |
| 619 | result[elem] = count |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 620 | return result |
| 621 | |
| 622 | def __sub__(self, other): |
| 623 | ''' Subtract count, but keep only results with positive counts. |
| 624 | |
| 625 | >>> Counter('abbbc') - Counter('bccd') |
| 626 | Counter({'b': 2, 'a': 1}) |
| 627 | |
| 628 | ''' |
| 629 | if not isinstance(other, Counter): |
| 630 | return NotImplemented |
| 631 | result = Counter() |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 632 | for elem, count in self.items(): |
| 633 | newcount = count - other[elem] |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 634 | if newcount > 0: |
| 635 | result[elem] = newcount |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 636 | for elem, count in other.items(): |
| 637 | if elem not in self and count < 0: |
| 638 | result[elem] = 0 - count |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 639 | return result |
| 640 | |
| 641 | def __or__(self, other): |
| 642 | '''Union is the maximum of value in either of the input counters. |
| 643 | |
| 644 | >>> Counter('abbb') | Counter('bcc') |
| 645 | Counter({'b': 3, 'c': 2, 'a': 1}) |
| 646 | |
| 647 | ''' |
| 648 | if not isinstance(other, Counter): |
| 649 | return NotImplemented |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 650 | result = Counter() |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 651 | for elem, count in self.items(): |
| 652 | other_count = other[elem] |
| 653 | newcount = other_count if count < other_count else count |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 654 | if newcount > 0: |
| 655 | result[elem] = newcount |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 656 | for elem, count in other.items(): |
| 657 | if elem not in self and count > 0: |
| 658 | result[elem] = count |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 659 | return result |
| 660 | |
| 661 | def __and__(self, other): |
| 662 | ''' Intersection is the minimum of corresponding counts. |
| 663 | |
| 664 | >>> Counter('abbb') & Counter('bcc') |
| 665 | Counter({'b': 1}) |
| 666 | |
| 667 | ''' |
| 668 | if not isinstance(other, Counter): |
| 669 | return NotImplemented |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 670 | result = Counter() |
Raymond Hettinger | 90375bc | 2011-04-17 19:49:29 -0700 | [diff] [blame] | 671 | for elem, count in self.items(): |
| 672 | other_count = other[elem] |
| 673 | newcount = count if count < other_count else other_count |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 674 | if newcount > 0: |
| 675 | result[elem] = newcount |
| 676 | return result |
| 677 | |
Raymond Hettinger | fcb393c | 2011-08-09 13:00:40 -0700 | [diff] [blame] | 678 | def __pos__(self): |
| 679 | 'Adds an empty counter, effectively stripping negative and zero counts' |
| 680 | return self + Counter() |
| 681 | |
| 682 | def __neg__(self): |
| 683 | '''Subtracts from an empty counter. Strips positive and zero counts, |
| 684 | and flips the sign on negative counts. |
| 685 | |
| 686 | ''' |
| 687 | return Counter() - self |
| 688 | |
Raymond Hettinger | becd568 | 2011-10-19 13:40:37 -0700 | [diff] [blame] | 689 | def _keep_positive(self): |
| 690 | '''Internal method to strip elements with a negative or zero count''' |
| 691 | nonpositive = [elem for elem, count in self.items() if not count > 0] |
| 692 | for elem in nonpositive: |
| 693 | del self[elem] |
| 694 | return self |
| 695 | |
| 696 | def __iadd__(self, other): |
| 697 | '''Inplace add from another counter, keeping only positive counts. |
| 698 | |
| 699 | >>> c = Counter('abbb') |
| 700 | >>> c += Counter('bcc') |
| 701 | >>> c |
| 702 | Counter({'b': 4, 'c': 2, 'a': 1}) |
| 703 | |
| 704 | ''' |
| 705 | for elem, count in other.items(): |
| 706 | self[elem] += count |
| 707 | return self._keep_positive() |
| 708 | |
| 709 | def __isub__(self, other): |
| 710 | '''Inplace subtract counter, but keep only results with positive counts. |
| 711 | |
| 712 | >>> c = Counter('abbbc') |
| 713 | >>> c -= Counter('bccd') |
| 714 | >>> c |
| 715 | Counter({'b': 2, 'a': 1}) |
| 716 | |
| 717 | ''' |
| 718 | for elem, count in other.items(): |
| 719 | self[elem] -= count |
| 720 | return self._keep_positive() |
| 721 | |
| 722 | def __ior__(self, other): |
| 723 | '''Inplace union is the maximum of value from either counter. |
| 724 | |
| 725 | >>> c = Counter('abbb') |
| 726 | >>> c |= Counter('bcc') |
| 727 | >>> c |
| 728 | Counter({'b': 3, 'c': 2, 'a': 1}) |
| 729 | |
| 730 | ''' |
| 731 | for elem, other_count in other.items(): |
| 732 | count = self[elem] |
| 733 | if other_count > count: |
| 734 | self[elem] = other_count |
| 735 | return self._keep_positive() |
| 736 | |
| 737 | def __iand__(self, other): |
| 738 | '''Inplace intersection is the minimum of corresponding counts. |
| 739 | |
| 740 | >>> c = Counter('abbb') |
| 741 | >>> c &= Counter('bcc') |
| 742 | >>> c |
| 743 | Counter({'b': 1}) |
| 744 | |
| 745 | ''' |
| 746 | for elem, count in self.items(): |
| 747 | other_count = other[elem] |
| 748 | if other_count < count: |
| 749 | self[elem] = other_count |
| 750 | return self._keep_positive() |
| 751 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 752 | |
Raymond Hettinger | ddb5240 | 2011-02-21 19:42:11 +0000 | [diff] [blame] | 753 | ######################################################################## |
Raymond Hettinger | c942310 | 2011-02-22 01:55:36 +0000 | [diff] [blame] | 754 | ### ChainMap (helper for configparser and string.Template) |
Raymond Hettinger | ddb5240 | 2011-02-21 19:42:11 +0000 | [diff] [blame] | 755 | ######################################################################## |
| 756 | |
Raymond Hettinger | 9fe1ccf | 2011-02-26 01:02:51 +0000 | [diff] [blame] | 757 | class ChainMap(MutableMapping): |
Raymond Hettinger | ddb5240 | 2011-02-21 19:42:11 +0000 | [diff] [blame] | 758 | ''' A ChainMap groups multiple dicts (or other mappings) together |
| 759 | to create a single, updateable view. |
| 760 | |
| 761 | The underlying mappings are stored in a list. That list is public and can |
| 762 | accessed or updated using the *maps* attribute. There is no other state. |
| 763 | |
| 764 | Lookups search the underlying mappings successively until a key is found. |
| 765 | In contrast, writes, updates, and deletions only operate on the first |
| 766 | mapping. |
| 767 | |
| 768 | ''' |
| 769 | |
| 770 | def __init__(self, *maps): |
| 771 | '''Initialize a ChainMap by setting *maps* to the given mappings. |
| 772 | If no mappings are provided, a single empty dictionary is used. |
| 773 | |
| 774 | ''' |
| 775 | self.maps = list(maps) or [{}] # always at least one map |
| 776 | |
| 777 | def __missing__(self, key): |
| 778 | raise KeyError(key) |
| 779 | |
| 780 | def __getitem__(self, key): |
| 781 | for mapping in self.maps: |
| 782 | try: |
| 783 | return mapping[key] # can't use 'key in mapping' with defaultdict |
| 784 | except KeyError: |
| 785 | pass |
| 786 | return self.__missing__(key) # support subclasses that define __missing__ |
| 787 | |
| 788 | def get(self, key, default=None): |
| 789 | return self[key] if key in self else default |
| 790 | |
| 791 | def __len__(self): |
| 792 | return len(set().union(*self.maps)) # reuses stored hash values if possible |
| 793 | |
| 794 | def __iter__(self): |
| 795 | return iter(set().union(*self.maps)) |
| 796 | |
| 797 | def __contains__(self, key): |
| 798 | return any(key in m for m in self.maps) |
| 799 | |
Raymond Hettinger | d032131 | 2011-02-26 06:53:58 +0000 | [diff] [blame] | 800 | def __bool__(self): |
| 801 | return any(self.maps) |
| 802 | |
Raymond Hettinger | ddb5240 | 2011-02-21 19:42:11 +0000 | [diff] [blame] | 803 | @_recursive_repr() |
| 804 | def __repr__(self): |
| 805 | return '{0.__class__.__name__}({1})'.format( |
| 806 | self, ', '.join(map(repr, self.maps))) |
| 807 | |
| 808 | @classmethod |
| 809 | def fromkeys(cls, iterable, *args): |
| 810 | 'Create a ChainMap with a single dict created from the iterable.' |
| 811 | return cls(dict.fromkeys(iterable, *args)) |
| 812 | |
| 813 | def copy(self): |
| 814 | 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' |
| 815 | return self.__class__(self.maps[0].copy(), *self.maps[1:]) |
| 816 | |
| 817 | __copy__ = copy |
| 818 | |
Raymond Hettinger | 499e193 | 2011-02-23 07:56:53 +0000 | [diff] [blame] | 819 | def new_child(self): # like Django's Context.push() |
| 820 | 'New ChainMap with a new dict followed by all previous maps.' |
| 821 | return self.__class__({}, *self.maps) |
| 822 | |
| 823 | @property |
| 824 | def parents(self): # like Django's Context.pop() |
| 825 | 'New ChainMap from maps[1:].' |
| 826 | return self.__class__(*self.maps[1:]) |
| 827 | |
Raymond Hettinger | ddb5240 | 2011-02-21 19:42:11 +0000 | [diff] [blame] | 828 | def __setitem__(self, key, value): |
| 829 | self.maps[0][key] = value |
| 830 | |
| 831 | def __delitem__(self, key): |
| 832 | try: |
| 833 | del self.maps[0][key] |
| 834 | except KeyError: |
| 835 | raise KeyError('Key not found in the first mapping: {!r}'.format(key)) |
| 836 | |
| 837 | def popitem(self): |
| 838 | 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' |
| 839 | try: |
| 840 | return self.maps[0].popitem() |
| 841 | except KeyError: |
| 842 | raise KeyError('No keys found in the first mapping.') |
| 843 | |
| 844 | def pop(self, key, *args): |
| 845 | 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' |
| 846 | try: |
| 847 | return self.maps[0].pop(key, *args) |
| 848 | except KeyError: |
| 849 | raise KeyError('Key not found in the first mapping: {!r}'.format(key)) |
| 850 | |
| 851 | def clear(self): |
| 852 | 'Clear maps[0], leaving maps[1:] intact.' |
| 853 | self.maps[0].clear() |
| 854 | |
| 855 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 856 | ################################################################################ |
| 857 | ### UserDict |
| 858 | ################################################################################ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 859 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 860 | class UserDict(MutableMapping): |
| 861 | |
| 862 | # Start by filling-out the abstract methods |
| 863 | def __init__(self, dict=None, **kwargs): |
| 864 | self.data = {} |
| 865 | if dict is not None: |
| 866 | self.update(dict) |
| 867 | if len(kwargs): |
| 868 | self.update(kwargs) |
| 869 | def __len__(self): return len(self.data) |
| 870 | def __getitem__(self, key): |
| 871 | if key in self.data: |
| 872 | return self.data[key] |
| 873 | if hasattr(self.__class__, "__missing__"): |
| 874 | return self.__class__.__missing__(self, key) |
| 875 | raise KeyError(key) |
| 876 | def __setitem__(self, key, item): self.data[key] = item |
| 877 | def __delitem__(self, key): del self.data[key] |
| 878 | def __iter__(self): |
| 879 | return iter(self.data) |
| 880 | |
Raymond Hettinger | 554c8b8 | 2008-02-05 22:54:43 +0000 | [diff] [blame] | 881 | # Modify __contains__ to work correctly when __missing__ is present |
| 882 | def __contains__(self, key): |
| 883 | return key in self.data |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 884 | |
| 885 | # Now, add the methods in dicts but not in MutableMapping |
| 886 | def __repr__(self): return repr(self.data) |
| 887 | def copy(self): |
| 888 | if self.__class__ is UserDict: |
| 889 | return UserDict(self.data.copy()) |
| 890 | import copy |
| 891 | data = self.data |
| 892 | try: |
| 893 | self.data = {} |
| 894 | c = copy.copy(self) |
| 895 | finally: |
| 896 | self.data = data |
| 897 | c.update(self) |
| 898 | return c |
| 899 | @classmethod |
| 900 | def fromkeys(cls, iterable, value=None): |
| 901 | d = cls() |
| 902 | for key in iterable: |
| 903 | d[key] = value |
| 904 | return d |
| 905 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 906 | |
| 907 | |
| 908 | ################################################################################ |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 909 | ### UserList |
| 910 | ################################################################################ |
| 911 | |
| 912 | class UserList(MutableSequence): |
| 913 | """A more or less complete user-defined wrapper around list objects.""" |
| 914 | def __init__(self, initlist=None): |
| 915 | self.data = [] |
| 916 | if initlist is not None: |
| 917 | # XXX should this accept an arbitrary sequence? |
| 918 | if type(initlist) == type(self.data): |
| 919 | self.data[:] = initlist |
| 920 | elif isinstance(initlist, UserList): |
| 921 | self.data[:] = initlist.data[:] |
| 922 | else: |
| 923 | self.data = list(initlist) |
| 924 | def __repr__(self): return repr(self.data) |
| 925 | def __lt__(self, other): return self.data < self.__cast(other) |
| 926 | def __le__(self, other): return self.data <= self.__cast(other) |
| 927 | def __eq__(self, other): return self.data == self.__cast(other) |
| 928 | def __ne__(self, other): return self.data != self.__cast(other) |
| 929 | def __gt__(self, other): return self.data > self.__cast(other) |
| 930 | def __ge__(self, other): return self.data >= self.__cast(other) |
| 931 | def __cast(self, other): |
| 932 | return other.data if isinstance(other, UserList) else other |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 933 | def __contains__(self, item): return item in self.data |
| 934 | def __len__(self): return len(self.data) |
| 935 | def __getitem__(self, i): return self.data[i] |
| 936 | def __setitem__(self, i, item): self.data[i] = item |
| 937 | def __delitem__(self, i): del self.data[i] |
| 938 | def __add__(self, other): |
| 939 | if isinstance(other, UserList): |
| 940 | return self.__class__(self.data + other.data) |
| 941 | elif isinstance(other, type(self.data)): |
| 942 | return self.__class__(self.data + other) |
| 943 | return self.__class__(self.data + list(other)) |
| 944 | def __radd__(self, other): |
| 945 | if isinstance(other, UserList): |
| 946 | return self.__class__(other.data + self.data) |
| 947 | elif isinstance(other, type(self.data)): |
| 948 | return self.__class__(other + self.data) |
| 949 | return self.__class__(list(other) + self.data) |
| 950 | def __iadd__(self, other): |
| 951 | if isinstance(other, UserList): |
| 952 | self.data += other.data |
| 953 | elif isinstance(other, type(self.data)): |
| 954 | self.data += other |
| 955 | else: |
| 956 | self.data += list(other) |
| 957 | return self |
| 958 | def __mul__(self, n): |
| 959 | return self.__class__(self.data*n) |
| 960 | __rmul__ = __mul__ |
| 961 | def __imul__(self, n): |
| 962 | self.data *= n |
| 963 | return self |
| 964 | def append(self, item): self.data.append(item) |
| 965 | def insert(self, i, item): self.data.insert(i, item) |
| 966 | def pop(self, i=-1): return self.data.pop(i) |
| 967 | def remove(self, item): self.data.remove(item) |
Eli Bendersky | cbbaa96 | 2011-02-25 05:47:53 +0000 | [diff] [blame] | 968 | def clear(self): self.data.clear() |
Raymond Hettinger | 1c7b7f7 | 2011-05-05 14:34:35 -0700 | [diff] [blame] | 969 | def copy(self): return self.__class__(self) |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 970 | def count(self, item): return self.data.count(item) |
| 971 | def index(self, item, *args): return self.data.index(item, *args) |
| 972 | def reverse(self): self.data.reverse() |
| 973 | def sort(self, *args, **kwds): self.data.sort(*args, **kwds) |
| 974 | def extend(self, other): |
| 975 | if isinstance(other, UserList): |
| 976 | self.data.extend(other.data) |
| 977 | else: |
| 978 | self.data.extend(other) |
| 979 | |
| 980 | |
| 981 | |
| 982 | ################################################################################ |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 983 | ### UserString |
| 984 | ################################################################################ |
| 985 | |
| 986 | class UserString(Sequence): |
| 987 | def __init__(self, seq): |
| 988 | if isinstance(seq, str): |
| 989 | self.data = seq |
| 990 | elif isinstance(seq, UserString): |
| 991 | self.data = seq.data[:] |
| 992 | else: |
| 993 | self.data = str(seq) |
| 994 | def __str__(self): return str(self.data) |
| 995 | def __repr__(self): return repr(self.data) |
| 996 | def __int__(self): return int(self.data) |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 997 | def __float__(self): return float(self.data) |
| 998 | def __complex__(self): return complex(self.data) |
| 999 | def __hash__(self): return hash(self.data) |
| 1000 | |
| 1001 | def __eq__(self, string): |
| 1002 | if isinstance(string, UserString): |
| 1003 | return self.data == string.data |
| 1004 | return self.data == string |
| 1005 | def __ne__(self, string): |
| 1006 | if isinstance(string, UserString): |
| 1007 | return self.data != string.data |
| 1008 | return self.data != string |
| 1009 | def __lt__(self, string): |
| 1010 | if isinstance(string, UserString): |
| 1011 | return self.data < string.data |
| 1012 | return self.data < string |
| 1013 | def __le__(self, string): |
| 1014 | if isinstance(string, UserString): |
| 1015 | return self.data <= string.data |
| 1016 | return self.data <= string |
| 1017 | def __gt__(self, string): |
| 1018 | if isinstance(string, UserString): |
| 1019 | return self.data > string.data |
| 1020 | return self.data > string |
| 1021 | def __ge__(self, string): |
| 1022 | if isinstance(string, UserString): |
| 1023 | return self.data >= string.data |
| 1024 | return self.data >= string |
| 1025 | |
| 1026 | def __contains__(self, char): |
| 1027 | if isinstance(char, UserString): |
| 1028 | char = char.data |
| 1029 | return char in self.data |
| 1030 | |
| 1031 | def __len__(self): return len(self.data) |
| 1032 | def __getitem__(self, index): return self.__class__(self.data[index]) |
| 1033 | def __add__(self, other): |
| 1034 | if isinstance(other, UserString): |
| 1035 | return self.__class__(self.data + other.data) |
| 1036 | elif isinstance(other, str): |
| 1037 | return self.__class__(self.data + other) |
| 1038 | return self.__class__(self.data + str(other)) |
| 1039 | def __radd__(self, other): |
| 1040 | if isinstance(other, str): |
| 1041 | return self.__class__(other + self.data) |
| 1042 | return self.__class__(str(other) + self.data) |
| 1043 | def __mul__(self, n): |
| 1044 | return self.__class__(self.data*n) |
| 1045 | __rmul__ = __mul__ |
| 1046 | def __mod__(self, args): |
| 1047 | return self.__class__(self.data % args) |
| 1048 | |
| 1049 | # the following methods are defined in alphabetical order: |
| 1050 | def capitalize(self): return self.__class__(self.data.capitalize()) |
| 1051 | def center(self, width, *args): |
| 1052 | return self.__class__(self.data.center(width, *args)) |
| 1053 | def count(self, sub, start=0, end=_sys.maxsize): |
| 1054 | if isinstance(sub, UserString): |
| 1055 | sub = sub.data |
| 1056 | return self.data.count(sub, start, end) |
| 1057 | def encode(self, encoding=None, errors=None): # XXX improve this? |
| 1058 | if encoding: |
| 1059 | if errors: |
| 1060 | return self.__class__(self.data.encode(encoding, errors)) |
| 1061 | return self.__class__(self.data.encode(encoding)) |
| 1062 | return self.__class__(self.data.encode()) |
| 1063 | def endswith(self, suffix, start=0, end=_sys.maxsize): |
| 1064 | return self.data.endswith(suffix, start, end) |
| 1065 | def expandtabs(self, tabsize=8): |
| 1066 | return self.__class__(self.data.expandtabs(tabsize)) |
| 1067 | def find(self, sub, start=0, end=_sys.maxsize): |
| 1068 | if isinstance(sub, UserString): |
| 1069 | sub = sub.data |
| 1070 | return self.data.find(sub, start, end) |
| 1071 | def format(self, *args, **kwds): |
| 1072 | return self.data.format(*args, **kwds) |
| 1073 | def index(self, sub, start=0, end=_sys.maxsize): |
| 1074 | return self.data.index(sub, start, end) |
| 1075 | def isalpha(self): return self.data.isalpha() |
| 1076 | def isalnum(self): return self.data.isalnum() |
| 1077 | def isdecimal(self): return self.data.isdecimal() |
| 1078 | def isdigit(self): return self.data.isdigit() |
| 1079 | def isidentifier(self): return self.data.isidentifier() |
| 1080 | def islower(self): return self.data.islower() |
| 1081 | def isnumeric(self): return self.data.isnumeric() |
| 1082 | def isspace(self): return self.data.isspace() |
| 1083 | def istitle(self): return self.data.istitle() |
| 1084 | def isupper(self): return self.data.isupper() |
| 1085 | def join(self, seq): return self.data.join(seq) |
| 1086 | def ljust(self, width, *args): |
| 1087 | return self.__class__(self.data.ljust(width, *args)) |
| 1088 | def lower(self): return self.__class__(self.data.lower()) |
| 1089 | def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) |
| 1090 | def partition(self, sep): |
| 1091 | return self.data.partition(sep) |
| 1092 | def replace(self, old, new, maxsplit=-1): |
| 1093 | if isinstance(old, UserString): |
| 1094 | old = old.data |
| 1095 | if isinstance(new, UserString): |
| 1096 | new = new.data |
| 1097 | return self.__class__(self.data.replace(old, new, maxsplit)) |
| 1098 | def rfind(self, sub, start=0, end=_sys.maxsize): |
Antoine Pitrou | da2ecaf | 2010-01-02 21:40:36 +0000 | [diff] [blame] | 1099 | if isinstance(sub, UserString): |
| 1100 | sub = sub.data |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 1101 | return self.data.rfind(sub, start, end) |
| 1102 | def rindex(self, sub, start=0, end=_sys.maxsize): |
| 1103 | return self.data.rindex(sub, start, end) |
| 1104 | def rjust(self, width, *args): |
| 1105 | return self.__class__(self.data.rjust(width, *args)) |
| 1106 | def rpartition(self, sep): |
| 1107 | return self.data.rpartition(sep) |
| 1108 | def rstrip(self, chars=None): |
| 1109 | return self.__class__(self.data.rstrip(chars)) |
| 1110 | def split(self, sep=None, maxsplit=-1): |
| 1111 | return self.data.split(sep, maxsplit) |
| 1112 | def rsplit(self, sep=None, maxsplit=-1): |
| 1113 | return self.data.rsplit(sep, maxsplit) |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 1114 | def splitlines(self, keepends=False): return self.data.splitlines(keepends) |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 1115 | def startswith(self, prefix, start=0, end=_sys.maxsize): |
| 1116 | return self.data.startswith(prefix, start, end) |
| 1117 | def strip(self, chars=None): return self.__class__(self.data.strip(chars)) |
| 1118 | def swapcase(self): return self.__class__(self.data.swapcase()) |
| 1119 | def title(self): return self.__class__(self.data.title()) |
| 1120 | def translate(self, *args): |
| 1121 | return self.__class__(self.data.translate(*args)) |
| 1122 | def upper(self): return self.__class__(self.data.upper()) |
| 1123 | def zfill(self, width): return self.__class__(self.data.zfill(width)) |