__init__.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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 some of the 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))