| 1 | n/a | __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', |
|---|
| 2 | n/a | 'UserString', 'Counter', 'OrderedDict'] |
|---|
| 3 | n/a | # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py. |
|---|
| 4 | n/a | # They should however be considered an integral part of collections.py. |
|---|
| 5 | n/a | from _abcoll import * |
|---|
| 6 | n/a | import _abcoll |
|---|
| 7 | n/a | __all__ += _abcoll.__all__ |
|---|
| 8 | n/a | |
|---|
| 9 | n/a | from _collections import deque, defaultdict |
|---|
| 10 | n/a | from operator import itemgetter as _itemgetter |
|---|
| 11 | n/a | from keyword import iskeyword as _iskeyword |
|---|
| 12 | n/a | import sys as _sys |
|---|
| 13 | n/a | import heapq as _heapq |
|---|
| 14 | n/a | from weakref import proxy as _proxy |
|---|
| 15 | n/a | from itertools import repeat as _repeat, chain as _chain, starmap as _starmap |
|---|
| 16 | n/a | from reprlib import recursive_repr as _recursive_repr |
|---|
| 17 | n/a | |
|---|
| 18 | n/a | ################################################################################ |
|---|
| 19 | n/a | ### OrderedDict |
|---|
| 20 | n/a | ################################################################################ |
|---|
| 21 | n/a | |
|---|
| 22 | n/a | class _Link(object): |
|---|
| 23 | n/a | __slots__ = 'prev', 'next', 'key', '__weakref__' |
|---|
| 24 | n/a | |
|---|
| 25 | n/a | class OrderedDict(dict): |
|---|
| 26 | n/a | 'Dictionary that remembers insertion order' |
|---|
| 27 | n/a | # An inherited dict maps keys to values. |
|---|
| 28 | n/a | # The inherited dict provides __getitem__, __len__, __contains__, and get. |
|---|
| 29 | n/a | # The remaining methods are order-aware. |
|---|
| 30 | n/a | # Big-O running times for all methods are the same as for regular dictionaries. |
|---|
| 31 | n/a | |
|---|
| 32 | n/a | # The internal self.__map dictionary maps keys to links in a doubly linked list. |
|---|
| 33 | n/a | # The circular doubly linked list starts and ends with a sentinel element. |
|---|
| 34 | n/a | # The sentinel element never gets deleted (this simplifies the algorithm). |
|---|
| 35 | n/a | # The sentinel is stored in self.__hardroot with a weakref proxy in self.__root. |
|---|
| 36 | n/a | # The prev/next links are weakref proxies (to prevent circular references). |
|---|
| 37 | n/a | # Individual links are kept alive by the hard reference in self.__map. |
|---|
| 38 | n/a | # Those hard references disappear when a key is deleted from an OrderedDict. |
|---|
| 39 | n/a | |
|---|
| 40 | n/a | def __init__(self, *args, **kwds): |
|---|
| 41 | n/a | '''Initialize an ordered dictionary. Signature is the same as for |
|---|
| 42 | n/a | regular dictionaries, but keyword arguments are not recommended |
|---|
| 43 | n/a | because their insertion order is arbitrary. |
|---|
| 44 | n/a | |
|---|
| 45 | n/a | ''' |
|---|
| 46 | n/a | if len(args) > 1: |
|---|
| 47 | n/a | raise TypeError('expected at most 1 arguments, got %d' % len(args)) |
|---|
| 48 | n/a | try: |
|---|
| 49 | n/a | self.__root |
|---|
| 50 | n/a | except AttributeError: |
|---|
| 51 | n/a | self.__hardroot = _Link() |
|---|
| 52 | n/a | self.__root = root = _proxy(self.__hardroot) |
|---|
| 53 | n/a | root.prev = root.next = root |
|---|
| 54 | n/a | self.__map = {} |
|---|
| 55 | n/a | self.__update(*args, **kwds) |
|---|
| 56 | n/a | |
|---|
| 57 | n/a | def __setitem__(self, key, value, |
|---|
| 58 | n/a | dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): |
|---|
| 59 | n/a | 'od.__setitem__(i, y) <==> od[i]=y' |
|---|
| 60 | n/a | # Setting a new item creates a new link which goes at the end of the linked |
|---|
| 61 | n/a | # list, and the inherited dictionary is updated with the new key/value pair. |
|---|
| 62 | n/a | if key not in self: |
|---|
| 63 | n/a | self.__map[key] = link = Link() |
|---|
| 64 | n/a | root = self.__root |
|---|
| 65 | n/a | last = root.prev |
|---|
| 66 | n/a | link.prev, link.next, link.key = last, root, key |
|---|
| 67 | n/a | last.next = link |
|---|
| 68 | n/a | root.prev = proxy(link) |
|---|
| 69 | n/a | dict_setitem(self, key, value) |
|---|
| 70 | n/a | |
|---|
| 71 | n/a | def __delitem__(self, key, dict_delitem=dict.__delitem__): |
|---|
| 72 | n/a | 'od.__delitem__(y) <==> del od[y]' |
|---|
| 73 | n/a | # Deleting an existing item uses self.__map to find the link which is |
|---|
| 74 | n/a | # then removed by updating the links in the predecessor and successor nodes. |
|---|
| 75 | n/a | dict_delitem(self, key) |
|---|
| 76 | n/a | link = self.__map.pop(key) |
|---|
| 77 | n/a | link_prev = link.prev |
|---|
| 78 | n/a | link_next = link.next |
|---|
| 79 | n/a | link_prev.next = link_next |
|---|
| 80 | n/a | link_next.prev = link_prev |
|---|
| 81 | n/a | |
|---|
| 82 | n/a | def __iter__(self): |
|---|
| 83 | n/a | 'od.__iter__() <==> iter(od)' |
|---|
| 84 | n/a | # Traverse the linked list in order. |
|---|
| 85 | n/a | root = self.__root |
|---|
| 86 | n/a | curr = root.next |
|---|
| 87 | n/a | while curr is not root: |
|---|
| 88 | n/a | yield curr.key |
|---|
| 89 | n/a | curr = curr.next |
|---|
| 90 | n/a | |
|---|
| 91 | n/a | def __reversed__(self): |
|---|
| 92 | n/a | 'od.__reversed__() <==> reversed(od)' |
|---|
| 93 | n/a | # Traverse the linked list in reverse order. |
|---|
| 94 | n/a | root = self.__root |
|---|
| 95 | n/a | curr = root.prev |
|---|
| 96 | n/a | while curr is not root: |
|---|
| 97 | n/a | yield curr.key |
|---|
| 98 | n/a | curr = curr.prev |
|---|
| 99 | n/a | |
|---|
| 100 | n/a | def clear(self): |
|---|
| 101 | n/a | 'od.clear() -> None. Remove all items from od.' |
|---|
| 102 | n/a | root = self.__root |
|---|
| 103 | n/a | root.prev = root.next = root |
|---|
| 104 | n/a | self.__map.clear() |
|---|
| 105 | n/a | dict.clear(self) |
|---|
| 106 | n/a | |
|---|
| 107 | n/a | def popitem(self, last=True): |
|---|
| 108 | n/a | '''od.popitem() -> (k, v), return and remove a (key, value) pair. |
|---|
| 109 | n/a | Pairs are returned in LIFO order if last is true or FIFO order if false. |
|---|
| 110 | n/a | |
|---|
| 111 | n/a | ''' |
|---|
| 112 | n/a | if not self: |
|---|
| 113 | n/a | raise KeyError('dictionary is empty') |
|---|
| 114 | n/a | root = self.__root |
|---|
| 115 | n/a | if last: |
|---|
| 116 | n/a | link = root.prev |
|---|
| 117 | n/a | link_prev = link.prev |
|---|
| 118 | n/a | link_prev.next = root |
|---|
| 119 | n/a | root.prev = link_prev |
|---|
| 120 | n/a | else: |
|---|
| 121 | n/a | link = root.next |
|---|
| 122 | n/a | link_next = link.next |
|---|
| 123 | n/a | root.next = link_next |
|---|
| 124 | n/a | link_next.prev = root |
|---|
| 125 | n/a | key = link.key |
|---|
| 126 | n/a | del self.__map[key] |
|---|
| 127 | n/a | value = dict.pop(self, key) |
|---|
| 128 | n/a | return key, value |
|---|
| 129 | n/a | |
|---|
| 130 | n/a | def move_to_end(self, key, last=True): |
|---|
| 131 | n/a | '''Move an existing element to the end (or beginning if last==False). |
|---|
| 132 | n/a | |
|---|
| 133 | n/a | Raises KeyError if the element does not exist. |
|---|
| 134 | n/a | When last=True, acts like a fast version of self[key]=self.pop(key). |
|---|
| 135 | n/a | |
|---|
| 136 | n/a | ''' |
|---|
| 137 | n/a | link = self.__map[key] |
|---|
| 138 | n/a | link_prev = link.prev |
|---|
| 139 | n/a | link_next = link.next |
|---|
| 140 | n/a | link_prev.next = link_next |
|---|
| 141 | n/a | link_next.prev = link_prev |
|---|
| 142 | n/a | root = self.__root |
|---|
| 143 | n/a | if last: |
|---|
| 144 | n/a | last = root.prev |
|---|
| 145 | n/a | link.prev = last |
|---|
| 146 | n/a | link.next = root |
|---|
| 147 | n/a | last.next = root.prev = link |
|---|
| 148 | n/a | else: |
|---|
| 149 | n/a | first = root.next |
|---|
| 150 | n/a | link.prev = root |
|---|
| 151 | n/a | link.next = first |
|---|
| 152 | n/a | root.next = first.prev = link |
|---|
| 153 | n/a | |
|---|
| 154 | n/a | def __reduce__(self): |
|---|
| 155 | n/a | 'Return state information for pickling' |
|---|
| 156 | n/a | items = [[k, self[k]] for k in self] |
|---|
| 157 | n/a | tmp = self.__map, self.__root, self.__hardroot |
|---|
| 158 | n/a | del self.__map, self.__root, self.__hardroot |
|---|
| 159 | n/a | inst_dict = vars(self).copy() |
|---|
| 160 | n/a | self.__map, self.__root, self.__hardroot = tmp |
|---|
| 161 | n/a | if inst_dict: |
|---|
| 162 | n/a | return (self.__class__, (items,), inst_dict) |
|---|
| 163 | n/a | return self.__class__, (items,) |
|---|
| 164 | n/a | |
|---|
| 165 | n/a | def __sizeof__(self): |
|---|
| 166 | n/a | sizeof = _sys.getsizeof |
|---|
| 167 | n/a | n = len(self) + 1 # number of links including root |
|---|
| 168 | n/a | size = sizeof(self.__dict__) # instance dictionary |
|---|
| 169 | n/a | size += sizeof(self.__map) * 2 # internal dict and inherited dict |
|---|
| 170 | n/a | size += sizeof(self.__hardroot) * n # link objects |
|---|
| 171 | n/a | size += sizeof(self.__root) * n # proxy objects |
|---|
| 172 | n/a | return size |
|---|
| 173 | n/a | |
|---|
| 174 | n/a | update = __update = MutableMapping.update |
|---|
| 175 | n/a | keys = MutableMapping.keys |
|---|
| 176 | n/a | values = MutableMapping.values |
|---|
| 177 | n/a | items = MutableMapping.items |
|---|
| 178 | n/a | __ne__ = MutableMapping.__ne__ |
|---|
| 179 | n/a | |
|---|
| 180 | n/a | __marker = object() |
|---|
| 181 | n/a | |
|---|
| 182 | n/a | def pop(self, key, default=__marker): |
|---|
| 183 | n/a | if key in self: |
|---|
| 184 | n/a | result = self[key] |
|---|
| 185 | n/a | del self[key] |
|---|
| 186 | n/a | return result |
|---|
| 187 | n/a | if default is self.__marker: |
|---|
| 188 | n/a | raise KeyError(key) |
|---|
| 189 | n/a | return default |
|---|
| 190 | n/a | |
|---|
| 191 | n/a | def setdefault(self, key, default=None): |
|---|
| 192 | n/a | 'OD.setdefault(k[,d]) -> OD.get(k,d), also set OD[k]=d if k not in OD' |
|---|
| 193 | n/a | if key in self: |
|---|
| 194 | n/a | return self[key] |
|---|
| 195 | n/a | self[key] = default |
|---|
| 196 | n/a | return default |
|---|
| 197 | n/a | |
|---|
| 198 | n/a | @_recursive_repr() |
|---|
| 199 | n/a | def __repr__(self): |
|---|
| 200 | n/a | 'od.__repr__() <==> repr(od)' |
|---|
| 201 | n/a | if not self: |
|---|
| 202 | n/a | return '%s()' % (self.__class__.__name__,) |
|---|
| 203 | n/a | return '%s(%r)' % (self.__class__.__name__, list(self.items())) |
|---|
| 204 | n/a | |
|---|
| 205 | n/a | def copy(self): |
|---|
| 206 | n/a | 'od.copy() -> a shallow copy of od' |
|---|
| 207 | n/a | return self.__class__(self) |
|---|
| 208 | n/a | |
|---|
| 209 | n/a | @classmethod |
|---|
| 210 | n/a | def fromkeys(cls, iterable, value=None): |
|---|
| 211 | n/a | '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S |
|---|
| 212 | n/a | and values equal to v (which defaults to None). |
|---|
| 213 | n/a | |
|---|
| 214 | n/a | ''' |
|---|
| 215 | n/a | d = cls() |
|---|
| 216 | n/a | for key in iterable: |
|---|
| 217 | n/a | d[key] = value |
|---|
| 218 | n/a | return d |
|---|
| 219 | n/a | |
|---|
| 220 | n/a | def __eq__(self, other): |
|---|
| 221 | n/a | '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive |
|---|
| 222 | n/a | while comparison to a regular mapping is order-insensitive. |
|---|
| 223 | n/a | |
|---|
| 224 | n/a | ''' |
|---|
| 225 | n/a | if isinstance(other, OrderedDict): |
|---|
| 226 | n/a | return len(self)==len(other) and \ |
|---|
| 227 | n/a | all(p==q for p, q in zip(self.items(), other.items())) |
|---|
| 228 | n/a | return dict.__eq__(self, other) |
|---|
| 229 | n/a | |
|---|
| 230 | n/a | |
|---|
| 231 | n/a | ################################################################################ |
|---|
| 232 | n/a | ### namedtuple |
|---|
| 233 | n/a | ################################################################################ |
|---|
| 234 | n/a | |
|---|
| 235 | n/a | def namedtuple(typename, field_names, verbose=False, rename=False): |
|---|
| 236 | n/a | """Returns a new subclass of tuple with named fields. |
|---|
| 237 | n/a | |
|---|
| 238 | n/a | >>> Point = namedtuple('Point', 'x y') |
|---|
| 239 | n/a | >>> Point.__doc__ # docstring for the new class |
|---|
| 240 | n/a | 'Point(x, y)' |
|---|
| 241 | n/a | >>> p = Point(11, y=22) # instantiate with positional args or keywords |
|---|
| 242 | n/a | >>> p[0] + p[1] # indexable like a plain tuple |
|---|
| 243 | n/a | 33 |
|---|
| 244 | n/a | >>> x, y = p # unpack like a regular tuple |
|---|
| 245 | n/a | >>> x, y |
|---|
| 246 | n/a | (11, 22) |
|---|
| 247 | n/a | >>> p.x + p.y # fields also accessable by name |
|---|
| 248 | n/a | 33 |
|---|
| 249 | n/a | >>> d = p._asdict() # convert to a dictionary |
|---|
| 250 | n/a | >>> d['x'] |
|---|
| 251 | n/a | 11 |
|---|
| 252 | n/a | >>> Point(**d) # convert from a dictionary |
|---|
| 253 | n/a | Point(x=11, y=22) |
|---|
| 254 | n/a | >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
|---|
| 255 | n/a | Point(x=100, y=22) |
|---|
| 256 | n/a | |
|---|
| 257 | n/a | """ |
|---|
| 258 | n/a | |
|---|
| 259 | n/a | # Parse and validate the field names. Validation serves two purposes, |
|---|
| 260 | n/a | # generating informative error messages and preventing template injection attacks. |
|---|
| 261 | n/a | if isinstance(field_names, str): |
|---|
| 262 | n/a | field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas |
|---|
| 263 | n/a | field_names = tuple(map(str, field_names)) |
|---|
| 264 | n/a | if rename: |
|---|
| 265 | n/a | names = list(field_names) |
|---|
| 266 | n/a | seen = set() |
|---|
| 267 | n/a | for i, name in enumerate(names): |
|---|
| 268 | n/a | if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name) |
|---|
| 269 | n/a | or not name or name[0].isdigit() or name.startswith('_') |
|---|
| 270 | n/a | or name in seen): |
|---|
| 271 | n/a | names[i] = '_%d' % i |
|---|
| 272 | n/a | seen.add(name) |
|---|
| 273 | n/a | field_names = tuple(names) |
|---|
| 274 | n/a | for name in (typename,) + field_names: |
|---|
| 275 | n/a | if not all(c.isalnum() or c=='_' for c in name): |
|---|
| 276 | n/a | raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) |
|---|
| 277 | n/a | if _iskeyword(name): |
|---|
| 278 | n/a | raise ValueError('Type names and field names cannot be a keyword: %r' % name) |
|---|
| 279 | n/a | if name[0].isdigit(): |
|---|
| 280 | n/a | raise ValueError('Type names and field names cannot start with a number: %r' % name) |
|---|
| 281 | n/a | seen_names = set() |
|---|
| 282 | n/a | for name in field_names: |
|---|
| 283 | n/a | if name.startswith('_') and not rename: |
|---|
| 284 | n/a | raise ValueError('Field names cannot start with an underscore: %r' % name) |
|---|
| 285 | n/a | if name in seen_names: |
|---|
| 286 | n/a | raise ValueError('Encountered duplicate field name: %r' % name) |
|---|
| 287 | n/a | seen_names.add(name) |
|---|
| 288 | n/a | |
|---|
| 289 | n/a | # Create and fill-in the class template |
|---|
| 290 | n/a | numfields = len(field_names) |
|---|
| 291 | n/a | argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes |
|---|
| 292 | n/a | reprtxt = ', '.join('%s=%%r' % name for name in field_names) |
|---|
| 293 | n/a | template = '''class %(typename)s(tuple): |
|---|
| 294 | n/a | '%(typename)s(%(argtxt)s)' \n |
|---|
| 295 | n/a | __slots__ = () \n |
|---|
| 296 | n/a | _fields = %(field_names)r \n |
|---|
| 297 | n/a | def __new__(_cls, %(argtxt)s): |
|---|
| 298 | n/a | 'Create new instance of %(typename)s(%(argtxt)s)' |
|---|
| 299 | n/a | return _tuple.__new__(_cls, (%(argtxt)s)) \n |
|---|
| 300 | n/a | @classmethod |
|---|
| 301 | n/a | def _make(cls, iterable, new=tuple.__new__, len=len): |
|---|
| 302 | n/a | 'Make a new %(typename)s object from a sequence or iterable' |
|---|
| 303 | n/a | result = new(cls, iterable) |
|---|
| 304 | n/a | if len(result) != %(numfields)d: |
|---|
| 305 | n/a | raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) |
|---|
| 306 | n/a | return result \n |
|---|
| 307 | n/a | def __repr__(self): |
|---|
| 308 | n/a | 'Return a nicely formatted representation string' |
|---|
| 309 | n/a | return self.__class__.__name__ + '(%(reprtxt)s)' %% self \n |
|---|
| 310 | n/a | def _asdict(self): |
|---|
| 311 | n/a | 'Return a new OrderedDict which maps field names to their values' |
|---|
| 312 | n/a | return OrderedDict(zip(self._fields, self)) \n |
|---|
| 313 | n/a | def _replace(_self, **kwds): |
|---|
| 314 | n/a | 'Return a new %(typename)s object replacing specified fields with new values' |
|---|
| 315 | n/a | result = _self._make(map(kwds.pop, %(field_names)r, _self)) |
|---|
| 316 | n/a | if kwds: |
|---|
| 317 | n/a | raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) |
|---|
| 318 | n/a | return result \n |
|---|
| 319 | n/a | def __getnewargs__(self): |
|---|
| 320 | n/a | 'Return self as a plain tuple. Used by copy and pickle.' |
|---|
| 321 | n/a | return tuple(self) \n\n''' % locals() |
|---|
| 322 | n/a | for i, name in enumerate(field_names): |
|---|
| 323 | n/a | template += " %s = _property(_itemgetter(%d), doc='Alias for field number %d')\n" % (name, i, i) |
|---|
| 324 | n/a | if verbose: |
|---|
| 325 | n/a | print(template) |
|---|
| 326 | n/a | |
|---|
| 327 | n/a | # Execute the template string in a temporary namespace and |
|---|
| 328 | n/a | # support tracing utilities by setting a value for frame.f_globals['__name__'] |
|---|
| 329 | n/a | namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename, |
|---|
| 330 | n/a | OrderedDict=OrderedDict, _property=property, _tuple=tuple) |
|---|
| 331 | n/a | try: |
|---|
| 332 | n/a | exec(template, namespace) |
|---|
| 333 | n/a | except SyntaxError as e: |
|---|
| 334 | n/a | raise SyntaxError(e.msg + ':\n\n' + template) |
|---|
| 335 | n/a | result = namespace[typename] |
|---|
| 336 | n/a | |
|---|
| 337 | n/a | # For pickling to work, the __module__ variable needs to be set to the frame |
|---|
| 338 | n/a | # where the named tuple is created. Bypass this step in enviroments where |
|---|
| 339 | n/a | # sys._getframe is not defined (Jython for example) or sys._getframe is not |
|---|
| 340 | n/a | # defined for arguments greater than 0 (IronPython). |
|---|
| 341 | n/a | try: |
|---|
| 342 | n/a | result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') |
|---|
| 343 | n/a | except (AttributeError, ValueError): |
|---|
| 344 | n/a | pass |
|---|
| 345 | n/a | |
|---|
| 346 | n/a | return result |
|---|
| 347 | n/a | |
|---|
| 348 | n/a | |
|---|
| 349 | n/a | ######################################################################## |
|---|
| 350 | n/a | ### Counter |
|---|
| 351 | n/a | ######################################################################## |
|---|
| 352 | n/a | |
|---|
| 353 | n/a | def _count_elements(mapping, iterable): |
|---|
| 354 | n/a | 'Tally elements from the iterable.' |
|---|
| 355 | n/a | mapping_get = mapping.get |
|---|
| 356 | n/a | for elem in iterable: |
|---|
| 357 | n/a | mapping[elem] = mapping_get(elem, 0) + 1 |
|---|
| 358 | n/a | |
|---|
| 359 | n/a | try: # Load C helper function if available |
|---|
| 360 | n/a | from _collections import _count_elements |
|---|
| 361 | n/a | except ImportError: |
|---|
| 362 | n/a | pass |
|---|
| 363 | n/a | |
|---|
| 364 | n/a | class Counter(dict): |
|---|
| 365 | n/a | '''Dict subclass for counting hashable items. Sometimes called a bag |
|---|
| 366 | n/a | or multiset. Elements are stored as dictionary keys and their counts |
|---|
| 367 | n/a | are stored as dictionary values. |
|---|
| 368 | n/a | |
|---|
| 369 | n/a | >>> c = Counter('abcdeabcdabcaba') # count elements from a string |
|---|
| 370 | n/a | |
|---|
| 371 | n/a | >>> c.most_common(3) # three most common elements |
|---|
| 372 | n/a | [('a', 5), ('b', 4), ('c', 3)] |
|---|
| 373 | n/a | >>> sorted(c) # list all unique elements |
|---|
| 374 | n/a | ['a', 'b', 'c', 'd', 'e'] |
|---|
| 375 | n/a | >>> ''.join(sorted(c.elements())) # list elements with repetitions |
|---|
| 376 | n/a | 'aaaaabbbbcccdde' |
|---|
| 377 | n/a | >>> sum(c.values()) # total of all counts |
|---|
| 378 | n/a | 15 |
|---|
| 379 | n/a | |
|---|
| 380 | n/a | >>> c['a'] # count of letter 'a' |
|---|
| 381 | n/a | 5 |
|---|
| 382 | n/a | >>> for elem in 'shazam': # update counts from an iterable |
|---|
| 383 | n/a | ... c[elem] += 1 # by adding 1 to each element's count |
|---|
| 384 | n/a | >>> c['a'] # now there are seven 'a' |
|---|
| 385 | n/a | 7 |
|---|
| 386 | n/a | >>> del c['b'] # remove all 'b' |
|---|
| 387 | n/a | >>> c['b'] # now there are zero 'b' |
|---|
| 388 | n/a | 0 |
|---|
| 389 | n/a | |
|---|
| 390 | n/a | >>> d = Counter('simsalabim') # make another counter |
|---|
| 391 | n/a | >>> c.update(d) # add in the second counter |
|---|
| 392 | n/a | >>> c['a'] # now there are nine 'a' |
|---|
| 393 | n/a | 9 |
|---|
| 394 | n/a | |
|---|
| 395 | n/a | >>> c.clear() # empty the counter |
|---|
| 396 | n/a | >>> c |
|---|
| 397 | n/a | Counter() |
|---|
| 398 | n/a | |
|---|
| 399 | n/a | Note: If a count is set to zero or reduced to zero, it will remain |
|---|
| 400 | n/a | in the counter until the entry is deleted or the counter is cleared: |
|---|
| 401 | n/a | |
|---|
| 402 | n/a | >>> c = Counter('aaabbc') |
|---|
| 403 | n/a | >>> c['b'] -= 2 # reduce the count of 'b' by two |
|---|
| 404 | n/a | >>> c.most_common() # 'b' is still in, but its count is zero |
|---|
| 405 | n/a | [('a', 3), ('c', 1), ('b', 0)] |
|---|
| 406 | n/a | |
|---|
| 407 | n/a | ''' |
|---|
| 408 | n/a | # References: |
|---|
| 409 | n/a | # http://en.wikipedia.org/wiki/Multiset |
|---|
| 410 | n/a | # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html |
|---|
| 411 | n/a | # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm |
|---|
| 412 | n/a | # http://code.activestate.com/recipes/259174/ |
|---|
| 413 | n/a | # Knuth, TAOCP Vol. II section 4.6.3 |
|---|
| 414 | n/a | |
|---|
| 415 | n/a | def __init__(self, iterable=None, **kwds): |
|---|
| 416 | n/a | '''Create a new, empty Counter object. And if given, count elements |
|---|
| 417 | n/a | from an input iterable. Or, initialize the count from another mapping |
|---|
| 418 | n/a | of elements to their counts. |
|---|
| 419 | n/a | |
|---|
| 420 | n/a | >>> c = Counter() # a new, empty counter |
|---|
| 421 | n/a | >>> c = Counter('gallahad') # a new counter from an iterable |
|---|
| 422 | n/a | >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping |
|---|
| 423 | n/a | >>> c = Counter(a=4, b=2) # a new counter from keyword args |
|---|
| 424 | n/a | |
|---|
| 425 | n/a | ''' |
|---|
| 426 | n/a | super().__init__() |
|---|
| 427 | n/a | self.update(iterable, **kwds) |
|---|
| 428 | n/a | |
|---|
| 429 | n/a | def __missing__(self, key): |
|---|
| 430 | n/a | 'The count of elements not in the Counter is zero.' |
|---|
| 431 | n/a | # Needed so that self[missing_item] does not raise KeyError |
|---|
| 432 | n/a | return 0 |
|---|
| 433 | n/a | |
|---|
| 434 | n/a | def most_common(self, n=None): |
|---|
| 435 | n/a | '''List the n most common elements and their counts from the most |
|---|
| 436 | n/a | common to the least. If n is None, then list all element counts. |
|---|
| 437 | n/a | |
|---|
| 438 | n/a | >>> Counter('abcdeabcdabcaba').most_common(3) |
|---|
| 439 | n/a | [('a', 5), ('b', 4), ('c', 3)] |
|---|
| 440 | n/a | |
|---|
| 441 | n/a | ''' |
|---|
| 442 | n/a | # Emulate Bag.sortedByCount from Smalltalk |
|---|
| 443 | n/a | if n is None: |
|---|
| 444 | n/a | return sorted(self.items(), key=_itemgetter(1), reverse=True) |
|---|
| 445 | n/a | return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) |
|---|
| 446 | n/a | |
|---|
| 447 | n/a | def elements(self): |
|---|
| 448 | n/a | '''Iterator over elements repeating each as many times as its count. |
|---|
| 449 | n/a | |
|---|
| 450 | n/a | >>> c = Counter('ABCABC') |
|---|
| 451 | n/a | >>> sorted(c.elements()) |
|---|
| 452 | n/a | ['A', 'A', 'B', 'B', 'C', 'C'] |
|---|
| 453 | n/a | |
|---|
| 454 | n/a | # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 |
|---|
| 455 | n/a | >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) |
|---|
| 456 | n/a | >>> product = 1 |
|---|
| 457 | n/a | >>> for factor in prime_factors.elements(): # loop over factors |
|---|
| 458 | n/a | ... product *= factor # and multiply them |
|---|
| 459 | n/a | >>> product |
|---|
| 460 | n/a | 1836 |
|---|
| 461 | n/a | |
|---|
| 462 | n/a | Note, if an element's count has been set to zero or is a negative |
|---|
| 463 | n/a | number, elements() will ignore it. |
|---|
| 464 | n/a | |
|---|
| 465 | n/a | ''' |
|---|
| 466 | n/a | # Emulate Bag.do from Smalltalk and Multiset.begin from C++. |
|---|
| 467 | n/a | return _chain.from_iterable(_starmap(_repeat, self.items())) |
|---|
| 468 | n/a | |
|---|
| 469 | n/a | # Override dict methods where necessary |
|---|
| 470 | n/a | |
|---|
| 471 | n/a | @classmethod |
|---|
| 472 | n/a | def fromkeys(cls, iterable, v=None): |
|---|
| 473 | n/a | # There is no equivalent method for counters because setting v=1 |
|---|
| 474 | n/a | # means that no element can have a count greater than one. |
|---|
| 475 | n/a | raise NotImplementedError( |
|---|
| 476 | n/a | 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
|---|
| 477 | n/a | |
|---|
| 478 | n/a | def update(self, iterable=None, **kwds): |
|---|
| 479 | n/a | '''Like dict.update() but add counts instead of replacing them. |
|---|
| 480 | n/a | |
|---|
| 481 | n/a | Source can be an iterable, a dictionary, or another Counter instance. |
|---|
| 482 | n/a | |
|---|
| 483 | n/a | >>> c = Counter('which') |
|---|
| 484 | n/a | >>> c.update('witch') # add elements from another iterable |
|---|
| 485 | n/a | >>> d = Counter('watch') |
|---|
| 486 | n/a | >>> c.update(d) # add elements from another counter |
|---|
| 487 | n/a | >>> c['h'] # four 'h' in which, witch, and watch |
|---|
| 488 | n/a | 4 |
|---|
| 489 | n/a | |
|---|
| 490 | n/a | ''' |
|---|
| 491 | n/a | # The regular dict.update() operation makes no sense here because the |
|---|
| 492 | n/a | # replace behavior results in the some of original untouched counts |
|---|
| 493 | n/a | # being mixed-in with all of the other counts for a mismash that |
|---|
| 494 | n/a | # doesn't have a straight-forward interpretation in most counting |
|---|
| 495 | n/a | # contexts. Instead, we implement straight-addition. Both the inputs |
|---|
| 496 | n/a | # and outputs are allowed to contain zero and negative counts. |
|---|
| 497 | n/a | |
|---|
| 498 | n/a | if iterable is not None: |
|---|
| 499 | n/a | if isinstance(iterable, Mapping): |
|---|
| 500 | n/a | if self: |
|---|
| 501 | n/a | self_get = self.get |
|---|
| 502 | n/a | for elem, count in iterable.items(): |
|---|
| 503 | n/a | self[elem] = count + self_get(elem, 0) |
|---|
| 504 | n/a | else: |
|---|
| 505 | n/a | super().update(iterable) # fast path when counter is empty |
|---|
| 506 | n/a | else: |
|---|
| 507 | n/a | _count_elements(self, iterable) |
|---|
| 508 | n/a | if kwds: |
|---|
| 509 | n/a | self.update(kwds) |
|---|
| 510 | n/a | |
|---|
| 511 | n/a | def subtract(self, iterable=None, **kwds): |
|---|
| 512 | n/a | '''Like dict.update() but subtracts counts instead of replacing them. |
|---|
| 513 | n/a | Counts can be reduced below zero. Both the inputs and outputs are |
|---|
| 514 | n/a | allowed to contain zero and negative counts. |
|---|
| 515 | n/a | |
|---|
| 516 | n/a | Source can be an iterable, a dictionary, or another Counter instance. |
|---|
| 517 | n/a | |
|---|
| 518 | n/a | >>> c = Counter('which') |
|---|
| 519 | n/a | >>> c.subtract('witch') # subtract elements from another iterable |
|---|
| 520 | n/a | >>> c.subtract(Counter('watch')) # subtract elements from another counter |
|---|
| 521 | n/a | >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch |
|---|
| 522 | n/a | 0 |
|---|
| 523 | n/a | >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch |
|---|
| 524 | n/a | -1 |
|---|
| 525 | n/a | |
|---|
| 526 | n/a | ''' |
|---|
| 527 | n/a | if iterable is not None: |
|---|
| 528 | n/a | self_get = self.get |
|---|
| 529 | n/a | if isinstance(iterable, Mapping): |
|---|
| 530 | n/a | for elem, count in iterable.items(): |
|---|
| 531 | n/a | self[elem] = self_get(elem, 0) - count |
|---|
| 532 | n/a | else: |
|---|
| 533 | n/a | for elem in iterable: |
|---|
| 534 | n/a | self[elem] = self_get(elem, 0) - 1 |
|---|
| 535 | n/a | if kwds: |
|---|
| 536 | n/a | self.subtract(kwds) |
|---|
| 537 | n/a | |
|---|
| 538 | n/a | def copy(self): |
|---|
| 539 | n/a | 'Like dict.copy() but returns a Counter instance instead of a dict.' |
|---|
| 540 | n/a | return Counter(self) |
|---|
| 541 | n/a | |
|---|
| 542 | n/a | def __reduce__(self): |
|---|
| 543 | n/a | return self.__class__, (dict(self),) |
|---|
| 544 | n/a | |
|---|
| 545 | n/a | def __delitem__(self, elem): |
|---|
| 546 | n/a | 'Like dict.__delitem__() but does not raise KeyError for missing values.' |
|---|
| 547 | n/a | if elem in self: |
|---|
| 548 | n/a | super().__delitem__(elem) |
|---|
| 549 | n/a | |
|---|
| 550 | n/a | def __repr__(self): |
|---|
| 551 | n/a | if not self: |
|---|
| 552 | n/a | return '%s()' % self.__class__.__name__ |
|---|
| 553 | n/a | items = ', '.join(map('%r: %r'.__mod__, self.most_common())) |
|---|
| 554 | n/a | return '%s({%s})' % (self.__class__.__name__, items) |
|---|
| 555 | n/a | |
|---|
| 556 | n/a | # Multiset-style mathematical operations discussed in: |
|---|
| 557 | n/a | # Knuth TAOCP Volume II section 4.6.3 exercise 19 |
|---|
| 558 | n/a | # and at http://en.wikipedia.org/wiki/Multiset |
|---|
| 559 | n/a | # |
|---|
| 560 | n/a | # Outputs guaranteed to only include positive counts. |
|---|
| 561 | n/a | # |
|---|
| 562 | n/a | # To strip negative and zero counts, add-in an empty counter: |
|---|
| 563 | n/a | # c += Counter() |
|---|
| 564 | n/a | |
|---|
| 565 | n/a | def __add__(self, other): |
|---|
| 566 | n/a | '''Add counts from two counters. |
|---|
| 567 | n/a | |
|---|
| 568 | n/a | >>> Counter('abbb') + Counter('bcc') |
|---|
| 569 | n/a | Counter({'b': 4, 'c': 2, 'a': 1}) |
|---|
| 570 | n/a | |
|---|
| 571 | n/a | ''' |
|---|
| 572 | n/a | if not isinstance(other, Counter): |
|---|
| 573 | n/a | return NotImplemented |
|---|
| 574 | n/a | result = Counter() |
|---|
| 575 | n/a | for elem in set(self) | set(other): |
|---|
| 576 | n/a | newcount = self[elem] + other[elem] |
|---|
| 577 | n/a | if newcount > 0: |
|---|
| 578 | n/a | result[elem] = newcount |
|---|
| 579 | n/a | return result |
|---|
| 580 | n/a | |
|---|
| 581 | n/a | def __sub__(self, other): |
|---|
| 582 | n/a | ''' Subtract count, but keep only results with positive counts. |
|---|
| 583 | n/a | |
|---|
| 584 | n/a | >>> Counter('abbbc') - Counter('bccd') |
|---|
| 585 | n/a | Counter({'b': 2, 'a': 1}) |
|---|
| 586 | n/a | |
|---|
| 587 | n/a | ''' |
|---|
| 588 | n/a | if not isinstance(other, Counter): |
|---|
| 589 | n/a | return NotImplemented |
|---|
| 590 | n/a | result = Counter() |
|---|
| 591 | n/a | for elem in set(self) | set(other): |
|---|
| 592 | n/a | newcount = self[elem] - other[elem] |
|---|
| 593 | n/a | if newcount > 0: |
|---|
| 594 | n/a | result[elem] = newcount |
|---|
| 595 | n/a | return result |
|---|
| 596 | n/a | |
|---|
| 597 | n/a | def __or__(self, other): |
|---|
| 598 | n/a | '''Union is the maximum of value in either of the input counters. |
|---|
| 599 | n/a | |
|---|
| 600 | n/a | >>> Counter('abbb') | Counter('bcc') |
|---|
| 601 | n/a | Counter({'b': 3, 'c': 2, 'a': 1}) |
|---|
| 602 | n/a | |
|---|
| 603 | n/a | ''' |
|---|
| 604 | n/a | if not isinstance(other, Counter): |
|---|
| 605 | n/a | return NotImplemented |
|---|
| 606 | n/a | result = Counter() |
|---|
| 607 | n/a | for elem in set(self) | set(other): |
|---|
| 608 | n/a | p, q = self[elem], other[elem] |
|---|
| 609 | n/a | newcount = q if p < q else p |
|---|
| 610 | n/a | if newcount > 0: |
|---|
| 611 | n/a | result[elem] = newcount |
|---|
| 612 | n/a | return result |
|---|
| 613 | n/a | |
|---|
| 614 | n/a | def __and__(self, other): |
|---|
| 615 | n/a | ''' Intersection is the minimum of corresponding counts. |
|---|
| 616 | n/a | |
|---|
| 617 | n/a | >>> Counter('abbb') & Counter('bcc') |
|---|
| 618 | n/a | Counter({'b': 1}) |
|---|
| 619 | n/a | |
|---|
| 620 | n/a | ''' |
|---|
| 621 | n/a | if not isinstance(other, Counter): |
|---|
| 622 | n/a | return NotImplemented |
|---|
| 623 | n/a | result = Counter() |
|---|
| 624 | n/a | if len(self) < len(other): |
|---|
| 625 | n/a | self, other = other, self |
|---|
| 626 | n/a | for elem in filter(self.__contains__, other): |
|---|
| 627 | n/a | p, q = self[elem], other[elem] |
|---|
| 628 | n/a | newcount = p if p < q else q |
|---|
| 629 | n/a | if newcount > 0: |
|---|
| 630 | n/a | result[elem] = newcount |
|---|
| 631 | n/a | return result |
|---|
| 632 | n/a | |
|---|
| 633 | n/a | |
|---|
| 634 | n/a | ################################################################################ |
|---|
| 635 | n/a | ### UserDict |
|---|
| 636 | n/a | ################################################################################ |
|---|
| 637 | n/a | |
|---|
| 638 | n/a | class UserDict(MutableMapping): |
|---|
| 639 | n/a | |
|---|
| 640 | n/a | # Start by filling-out the abstract methods |
|---|
| 641 | n/a | def __init__(self, dict=None, **kwargs): |
|---|
| 642 | n/a | self.data = {} |
|---|
| 643 | n/a | if dict is not None: |
|---|
| 644 | n/a | self.update(dict) |
|---|
| 645 | n/a | if len(kwargs): |
|---|
| 646 | n/a | self.update(kwargs) |
|---|
| 647 | n/a | def __len__(self): return len(self.data) |
|---|
| 648 | n/a | def __getitem__(self, key): |
|---|
| 649 | n/a | if key in self.data: |
|---|
| 650 | n/a | return self.data[key] |
|---|
| 651 | n/a | if hasattr(self.__class__, "__missing__"): |
|---|
| 652 | n/a | return self.__class__.__missing__(self, key) |
|---|
| 653 | n/a | raise KeyError(key) |
|---|
| 654 | n/a | def __setitem__(self, key, item): self.data[key] = item |
|---|
| 655 | n/a | def __delitem__(self, key): del self.data[key] |
|---|
| 656 | n/a | def __iter__(self): |
|---|
| 657 | n/a | return iter(self.data) |
|---|
| 658 | n/a | |
|---|
| 659 | n/a | # Modify __contains__ to work correctly when __missing__ is present |
|---|
| 660 | n/a | def __contains__(self, key): |
|---|
| 661 | n/a | return key in self.data |
|---|
| 662 | n/a | |
|---|
| 663 | n/a | # Now, add the methods in dicts but not in MutableMapping |
|---|
| 664 | n/a | def __repr__(self): return repr(self.data) |
|---|
| 665 | n/a | def copy(self): |
|---|
| 666 | n/a | if self.__class__ is UserDict: |
|---|
| 667 | n/a | return UserDict(self.data.copy()) |
|---|
| 668 | n/a | import copy |
|---|
| 669 | n/a | data = self.data |
|---|
| 670 | n/a | try: |
|---|
| 671 | n/a | self.data = {} |
|---|
| 672 | n/a | c = copy.copy(self) |
|---|
| 673 | n/a | finally: |
|---|
| 674 | n/a | self.data = data |
|---|
| 675 | n/a | c.update(self) |
|---|
| 676 | n/a | return c |
|---|
| 677 | n/a | @classmethod |
|---|
| 678 | n/a | def fromkeys(cls, iterable, value=None): |
|---|
| 679 | n/a | d = cls() |
|---|
| 680 | n/a | for key in iterable: |
|---|
| 681 | n/a | d[key] = value |
|---|
| 682 | n/a | return d |
|---|
| 683 | n/a | |
|---|
| 684 | n/a | |
|---|
| 685 | n/a | |
|---|
| 686 | n/a | ################################################################################ |
|---|
| 687 | n/a | ### UserList |
|---|
| 688 | n/a | ################################################################################ |
|---|
| 689 | n/a | |
|---|
| 690 | n/a | class UserList(MutableSequence): |
|---|
| 691 | n/a | """A more or less complete user-defined wrapper around list objects.""" |
|---|
| 692 | n/a | def __init__(self, initlist=None): |
|---|
| 693 | n/a | self.data = [] |
|---|
| 694 | n/a | if initlist is not None: |
|---|
| 695 | n/a | # XXX should this accept an arbitrary sequence? |
|---|
| 696 | n/a | if type(initlist) == type(self.data): |
|---|
| 697 | n/a | self.data[:] = initlist |
|---|
| 698 | n/a | elif isinstance(initlist, UserList): |
|---|
| 699 | n/a | self.data[:] = initlist.data[:] |
|---|
| 700 | n/a | else: |
|---|
| 701 | n/a | self.data = list(initlist) |
|---|
| 702 | n/a | def __repr__(self): return repr(self.data) |
|---|
| 703 | n/a | def __lt__(self, other): return self.data < self.__cast(other) |
|---|
| 704 | n/a | def __le__(self, other): return self.data <= self.__cast(other) |
|---|
| 705 | n/a | def __eq__(self, other): return self.data == self.__cast(other) |
|---|
| 706 | n/a | def __ne__(self, other): return self.data != self.__cast(other) |
|---|
| 707 | n/a | def __gt__(self, other): return self.data > self.__cast(other) |
|---|
| 708 | n/a | def __ge__(self, other): return self.data >= self.__cast(other) |
|---|
| 709 | n/a | def __cast(self, other): |
|---|
| 710 | n/a | return other.data if isinstance(other, UserList) else other |
|---|
| 711 | n/a | def __contains__(self, item): return item in self.data |
|---|
| 712 | n/a | def __len__(self): return len(self.data) |
|---|
| 713 | n/a | def __getitem__(self, i): return self.data[i] |
|---|
| 714 | n/a | def __setitem__(self, i, item): self.data[i] = item |
|---|
| 715 | n/a | def __delitem__(self, i): del self.data[i] |
|---|
| 716 | n/a | def __add__(self, other): |
|---|
| 717 | n/a | if isinstance(other, UserList): |
|---|
| 718 | n/a | return self.__class__(self.data + other.data) |
|---|
| 719 | n/a | elif isinstance(other, type(self.data)): |
|---|
| 720 | n/a | return self.__class__(self.data + other) |
|---|
| 721 | n/a | return self.__class__(self.data + list(other)) |
|---|
| 722 | n/a | def __radd__(self, other): |
|---|
| 723 | n/a | if isinstance(other, UserList): |
|---|
| 724 | n/a | return self.__class__(other.data + self.data) |
|---|
| 725 | n/a | elif isinstance(other, type(self.data)): |
|---|
| 726 | n/a | return self.__class__(other + self.data) |
|---|
| 727 | n/a | return self.__class__(list(other) + self.data) |
|---|
| 728 | n/a | def __iadd__(self, other): |
|---|
| 729 | n/a | if isinstance(other, UserList): |
|---|
| 730 | n/a | self.data += other.data |
|---|
| 731 | n/a | elif isinstance(other, type(self.data)): |
|---|
| 732 | n/a | self.data += other |
|---|
| 733 | n/a | else: |
|---|
| 734 | n/a | self.data += list(other) |
|---|
| 735 | n/a | return self |
|---|
| 736 | n/a | def __mul__(self, n): |
|---|
| 737 | n/a | return self.__class__(self.data*n) |
|---|
| 738 | n/a | __rmul__ = __mul__ |
|---|
| 739 | n/a | def __imul__(self, n): |
|---|
| 740 | n/a | self.data *= n |
|---|
| 741 | n/a | return self |
|---|
| 742 | n/a | def append(self, item): self.data.append(item) |
|---|
| 743 | n/a | def insert(self, i, item): self.data.insert(i, item) |
|---|
| 744 | n/a | def pop(self, i=-1): return self.data.pop(i) |
|---|
| 745 | n/a | def remove(self, item): self.data.remove(item) |
|---|
| 746 | n/a | def count(self, item): return self.data.count(item) |
|---|
| 747 | n/a | def index(self, item, *args): return self.data.index(item, *args) |
|---|
| 748 | n/a | def reverse(self): self.data.reverse() |
|---|
| 749 | n/a | def sort(self, *args, **kwds): self.data.sort(*args, **kwds) |
|---|
| 750 | n/a | def extend(self, other): |
|---|
| 751 | n/a | if isinstance(other, UserList): |
|---|
| 752 | n/a | self.data.extend(other.data) |
|---|
| 753 | n/a | else: |
|---|
| 754 | n/a | self.data.extend(other) |
|---|
| 755 | n/a | |
|---|
| 756 | n/a | |
|---|
| 757 | n/a | |
|---|
| 758 | n/a | ################################################################################ |
|---|
| 759 | n/a | ### UserString |
|---|
| 760 | n/a | ################################################################################ |
|---|
| 761 | n/a | |
|---|
| 762 | n/a | class UserString(Sequence): |
|---|
| 763 | n/a | def __init__(self, seq): |
|---|
| 764 | n/a | if isinstance(seq, str): |
|---|
| 765 | n/a | self.data = seq |
|---|
| 766 | n/a | elif isinstance(seq, UserString): |
|---|
| 767 | n/a | self.data = seq.data[:] |
|---|
| 768 | n/a | else: |
|---|
| 769 | n/a | self.data = str(seq) |
|---|
| 770 | n/a | def __str__(self): return str(self.data) |
|---|
| 771 | n/a | def __repr__(self): return repr(self.data) |
|---|
| 772 | n/a | def __int__(self): return int(self.data) |
|---|
| 773 | n/a | def __float__(self): return float(self.data) |
|---|
| 774 | n/a | def __complex__(self): return complex(self.data) |
|---|
| 775 | n/a | def __hash__(self): return hash(self.data) |
|---|
| 776 | n/a | |
|---|
| 777 | n/a | def __eq__(self, string): |
|---|
| 778 | n/a | if isinstance(string, UserString): |
|---|
| 779 | n/a | return self.data == string.data |
|---|
| 780 | n/a | return self.data == string |
|---|
| 781 | n/a | def __ne__(self, string): |
|---|
| 782 | n/a | if isinstance(string, UserString): |
|---|
| 783 | n/a | return self.data != string.data |
|---|
| 784 | n/a | return self.data != string |
|---|
| 785 | n/a | def __lt__(self, string): |
|---|
| 786 | n/a | if isinstance(string, UserString): |
|---|
| 787 | n/a | return self.data < string.data |
|---|
| 788 | n/a | return self.data < string |
|---|
| 789 | n/a | def __le__(self, string): |
|---|
| 790 | n/a | if isinstance(string, UserString): |
|---|
| 791 | n/a | return self.data <= string.data |
|---|
| 792 | n/a | return self.data <= string |
|---|
| 793 | n/a | def __gt__(self, string): |
|---|
| 794 | n/a | if isinstance(string, UserString): |
|---|
| 795 | n/a | return self.data > string.data |
|---|
| 796 | n/a | return self.data > string |
|---|
| 797 | n/a | def __ge__(self, string): |
|---|
| 798 | n/a | if isinstance(string, UserString): |
|---|
| 799 | n/a | return self.data >= string.data |
|---|
| 800 | n/a | return self.data >= string |
|---|
| 801 | n/a | |
|---|
| 802 | n/a | def __contains__(self, char): |
|---|
| 803 | n/a | if isinstance(char, UserString): |
|---|
| 804 | n/a | char = char.data |
|---|
| 805 | n/a | return char in self.data |
|---|
| 806 | n/a | |
|---|
| 807 | n/a | def __len__(self): return len(self.data) |
|---|
| 808 | n/a | def __getitem__(self, index): return self.__class__(self.data[index]) |
|---|
| 809 | n/a | def __add__(self, other): |
|---|
| 810 | n/a | if isinstance(other, UserString): |
|---|
| 811 | n/a | return self.__class__(self.data + other.data) |
|---|
| 812 | n/a | elif isinstance(other, str): |
|---|
| 813 | n/a | return self.__class__(self.data + other) |
|---|
| 814 | n/a | return self.__class__(self.data + str(other)) |
|---|
| 815 | n/a | def __radd__(self, other): |
|---|
| 816 | n/a | if isinstance(other, str): |
|---|
| 817 | n/a | return self.__class__(other + self.data) |
|---|
| 818 | n/a | return self.__class__(str(other) + self.data) |
|---|
| 819 | n/a | def __mul__(self, n): |
|---|
| 820 | n/a | return self.__class__(self.data*n) |
|---|
| 821 | n/a | __rmul__ = __mul__ |
|---|
| 822 | n/a | def __mod__(self, args): |
|---|
| 823 | n/a | return self.__class__(self.data % args) |
|---|
| 824 | n/a | |
|---|
| 825 | n/a | # the following methods are defined in alphabetical order: |
|---|
| 826 | n/a | def capitalize(self): return self.__class__(self.data.capitalize()) |
|---|
| 827 | n/a | def center(self, width, *args): |
|---|
| 828 | n/a | return self.__class__(self.data.center(width, *args)) |
|---|
| 829 | n/a | def count(self, sub, start=0, end=_sys.maxsize): |
|---|
| 830 | n/a | if isinstance(sub, UserString): |
|---|
| 831 | n/a | sub = sub.data |
|---|
| 832 | n/a | return self.data.count(sub, start, end) |
|---|
| 833 | n/a | def encode(self, encoding=None, errors=None): # XXX improve this? |
|---|
| 834 | n/a | if encoding: |
|---|
| 835 | n/a | if errors: |
|---|
| 836 | n/a | return self.__class__(self.data.encode(encoding, errors)) |
|---|
| 837 | n/a | return self.__class__(self.data.encode(encoding)) |
|---|
| 838 | n/a | return self.__class__(self.data.encode()) |
|---|
| 839 | n/a | def endswith(self, suffix, start=0, end=_sys.maxsize): |
|---|
| 840 | n/a | return self.data.endswith(suffix, start, end) |
|---|
| 841 | n/a | def expandtabs(self, tabsize=8): |
|---|
| 842 | n/a | return self.__class__(self.data.expandtabs(tabsize)) |
|---|
| 843 | n/a | def find(self, sub, start=0, end=_sys.maxsize): |
|---|
| 844 | n/a | if isinstance(sub, UserString): |
|---|
| 845 | n/a | sub = sub.data |
|---|
| 846 | n/a | return self.data.find(sub, start, end) |
|---|
| 847 | n/a | def format(self, *args, **kwds): |
|---|
| 848 | n/a | return self.data.format(*args, **kwds) |
|---|
| 849 | n/a | def index(self, sub, start=0, end=_sys.maxsize): |
|---|
| 850 | n/a | return self.data.index(sub, start, end) |
|---|
| 851 | n/a | def isalpha(self): return self.data.isalpha() |
|---|
| 852 | n/a | def isalnum(self): return self.data.isalnum() |
|---|
| 853 | n/a | def isdecimal(self): return self.data.isdecimal() |
|---|
| 854 | n/a | def isdigit(self): return self.data.isdigit() |
|---|
| 855 | n/a | def isidentifier(self): return self.data.isidentifier() |
|---|
| 856 | n/a | def islower(self): return self.data.islower() |
|---|
| 857 | n/a | def isnumeric(self): return self.data.isnumeric() |
|---|
| 858 | n/a | def isspace(self): return self.data.isspace() |
|---|
| 859 | n/a | def istitle(self): return self.data.istitle() |
|---|
| 860 | n/a | def isupper(self): return self.data.isupper() |
|---|
| 861 | n/a | def join(self, seq): return self.data.join(seq) |
|---|
| 862 | n/a | def ljust(self, width, *args): |
|---|
| 863 | n/a | return self.__class__(self.data.ljust(width, *args)) |
|---|
| 864 | n/a | def lower(self): return self.__class__(self.data.lower()) |
|---|
| 865 | n/a | def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) |
|---|
| 866 | n/a | def partition(self, sep): |
|---|
| 867 | n/a | return self.data.partition(sep) |
|---|
| 868 | n/a | def replace(self, old, new, maxsplit=-1): |
|---|
| 869 | n/a | if isinstance(old, UserString): |
|---|
| 870 | n/a | old = old.data |
|---|
| 871 | n/a | if isinstance(new, UserString): |
|---|
| 872 | n/a | new = new.data |
|---|
| 873 | n/a | return self.__class__(self.data.replace(old, new, maxsplit)) |
|---|
| 874 | n/a | def rfind(self, sub, start=0, end=_sys.maxsize): |
|---|
| 875 | n/a | if isinstance(sub, UserString): |
|---|
| 876 | n/a | sub = sub.data |
|---|
| 877 | n/a | return self.data.rfind(sub, start, end) |
|---|
| 878 | n/a | def rindex(self, sub, start=0, end=_sys.maxsize): |
|---|
| 879 | n/a | return self.data.rindex(sub, start, end) |
|---|
| 880 | n/a | def rjust(self, width, *args): |
|---|
| 881 | n/a | return self.__class__(self.data.rjust(width, *args)) |
|---|
| 882 | n/a | def rpartition(self, sep): |
|---|
| 883 | n/a | return self.data.rpartition(sep) |
|---|
| 884 | n/a | def rstrip(self, chars=None): |
|---|
| 885 | n/a | return self.__class__(self.data.rstrip(chars)) |
|---|
| 886 | n/a | def split(self, sep=None, maxsplit=-1): |
|---|
| 887 | n/a | return self.data.split(sep, maxsplit) |
|---|
| 888 | n/a | def rsplit(self, sep=None, maxsplit=-1): |
|---|
| 889 | n/a | return self.data.rsplit(sep, maxsplit) |
|---|
| 890 | n/a | def splitlines(self, keepends=0): return self.data.splitlines(keepends) |
|---|
| 891 | n/a | def startswith(self, prefix, start=0, end=_sys.maxsize): |
|---|
| 892 | n/a | return self.data.startswith(prefix, start, end) |
|---|
| 893 | n/a | def strip(self, chars=None): return self.__class__(self.data.strip(chars)) |
|---|
| 894 | n/a | def swapcase(self): return self.__class__(self.data.swapcase()) |
|---|
| 895 | n/a | def title(self): return self.__class__(self.data.title()) |
|---|
| 896 | n/a | def translate(self, *args): |
|---|
| 897 | n/a | return self.__class__(self.data.translate(*args)) |
|---|
| 898 | n/a | def upper(self): return self.__class__(self.data.upper()) |
|---|
| 899 | n/a | def zfill(self, width): return self.__class__(self.data.zfill(width)) |
|---|
| 900 | n/a | |
|---|
| 901 | n/a | |
|---|
| 902 | n/a | |
|---|
| 903 | n/a | ################################################################################ |
|---|
| 904 | n/a | ### Simple tests |
|---|
| 905 | n/a | ################################################################################ |
|---|
| 906 | n/a | |
|---|
| 907 | n/a | if __name__ == '__main__': |
|---|
| 908 | n/a | # verify that instances can be pickled |
|---|
| 909 | n/a | from pickle import loads, dumps |
|---|
| 910 | n/a | Point = namedtuple('Point', 'x, y', True) |
|---|
| 911 | n/a | p = Point(x=10, y=20) |
|---|
| 912 | n/a | assert p == loads(dumps(p)) |
|---|
| 913 | n/a | |
|---|
| 914 | n/a | # test and demonstrate ability to override methods |
|---|
| 915 | n/a | class Point(namedtuple('Point', 'x y')): |
|---|
| 916 | n/a | __slots__ = () |
|---|
| 917 | n/a | @property |
|---|
| 918 | n/a | def hypot(self): |
|---|
| 919 | n/a | return (self.x ** 2 + self.y ** 2) ** 0.5 |
|---|
| 920 | n/a | def __str__(self): |
|---|
| 921 | n/a | return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
|---|
| 922 | n/a | |
|---|
| 923 | n/a | for p in Point(3, 4), Point(14, 5/7.): |
|---|
| 924 | n/a | print (p) |
|---|
| 925 | n/a | |
|---|
| 926 | n/a | class Point(namedtuple('Point', 'x y')): |
|---|
| 927 | n/a | 'Point class with optimized _make() and _replace() without error-checking' |
|---|
| 928 | n/a | __slots__ = () |
|---|
| 929 | n/a | _make = classmethod(tuple.__new__) |
|---|
| 930 | n/a | def _replace(self, _map=map, **kwds): |
|---|
| 931 | n/a | return self._make(_map(kwds.get, ('x', 'y'), self)) |
|---|
| 932 | n/a | |
|---|
| 933 | n/a | print(Point(11, 22)._replace(x=100)) |
|---|
| 934 | n/a | |
|---|
| 935 | n/a | Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
|---|
| 936 | n/a | print(Point3D.__doc__) |
|---|
| 937 | n/a | |
|---|
| 938 | n/a | import doctest |
|---|
| 939 | n/a | TestResults = namedtuple('TestResults', 'failed attempted') |
|---|
| 940 | n/a | print(TestResults(*doctest.testmod())) |
|---|