__init__.py 51 KB

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