Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/smanonr..../lib64/python3..../collecti...
File: __init__.py
'''This module implements specialized container datatypes providing
[0] Fix | Delete
alternatives to Python's general purpose built-in containers, dict,
[1] Fix | Delete
list, set, and tuple.
[2] Fix | Delete
[3] Fix | Delete
* namedtuple factory function for creating tuple subclasses with named fields
[4] Fix | Delete
* deque list-like container with fast appends and pops on either end
[5] Fix | Delete
* ChainMap dict-like class for creating a single view of multiple mappings
[6] Fix | Delete
* Counter dict subclass for counting hashable objects
[7] Fix | Delete
* OrderedDict dict subclass that remembers the order entries were added
[8] Fix | Delete
* defaultdict dict subclass that calls a factory function to supply missing values
[9] Fix | Delete
* UserDict wrapper around dictionary objects for easier dict subclassing
[10] Fix | Delete
* UserList wrapper around list objects for easier list subclassing
[11] Fix | Delete
* UserString wrapper around string objects for easier string subclassing
[12] Fix | Delete
[13] Fix | Delete
'''
[14] Fix | Delete
[15] Fix | Delete
__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
[16] Fix | Delete
'UserString', 'Counter', 'OrderedDict', 'ChainMap']
[17] Fix | Delete
[18] Fix | Delete
import _collections_abc
[19] Fix | Delete
from operator import itemgetter as _itemgetter, eq as _eq
[20] Fix | Delete
from keyword import iskeyword as _iskeyword
[21] Fix | Delete
import sys as _sys
[22] Fix | Delete
import heapq as _heapq
[23] Fix | Delete
from _weakref import proxy as _proxy
[24] Fix | Delete
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
[25] Fix | Delete
from reprlib import recursive_repr as _recursive_repr
[26] Fix | Delete
[27] Fix | Delete
try:
[28] Fix | Delete
from _collections import deque
[29] Fix | Delete
except ImportError:
[30] Fix | Delete
pass
[31] Fix | Delete
else:
[32] Fix | Delete
_collections_abc.MutableSequence.register(deque)
[33] Fix | Delete
[34] Fix | Delete
try:
[35] Fix | Delete
from _collections import defaultdict
[36] Fix | Delete
except ImportError:
[37] Fix | Delete
pass
[38] Fix | Delete
[39] Fix | Delete
[40] Fix | Delete
def __getattr__(name):
[41] Fix | Delete
# For backwards compatibility, continue to make the collections ABCs
[42] Fix | Delete
# through Python 3.6 available through the collections module.
[43] Fix | Delete
# Note, no new collections ABCs were added in Python 3.7
[44] Fix | Delete
if name in _collections_abc.__all__:
[45] Fix | Delete
obj = getattr(_collections_abc, name)
[46] Fix | Delete
import warnings
[47] Fix | Delete
warnings.warn("Using or importing the ABCs from 'collections' instead "
[48] Fix | Delete
"of from 'collections.abc' is deprecated since Python 3.3, "
[49] Fix | Delete
"and in 3.10 it will stop working",
[50] Fix | Delete
DeprecationWarning, stacklevel=2)
[51] Fix | Delete
globals()[name] = obj
[52] Fix | Delete
return obj
[53] Fix | Delete
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
[54] Fix | Delete
[55] Fix | Delete
################################################################################
[56] Fix | Delete
### OrderedDict
[57] Fix | Delete
################################################################################
[58] Fix | Delete
[59] Fix | Delete
class _OrderedDictKeysView(_collections_abc.KeysView):
[60] Fix | Delete
[61] Fix | Delete
def __reversed__(self):
[62] Fix | Delete
yield from reversed(self._mapping)
[63] Fix | Delete
[64] Fix | Delete
class _OrderedDictItemsView(_collections_abc.ItemsView):
[65] Fix | Delete
[66] Fix | Delete
def __reversed__(self):
[67] Fix | Delete
for key in reversed(self._mapping):
[68] Fix | Delete
yield (key, self._mapping[key])
[69] Fix | Delete
[70] Fix | Delete
class _OrderedDictValuesView(_collections_abc.ValuesView):
[71] Fix | Delete
[72] Fix | Delete
def __reversed__(self):
[73] Fix | Delete
for key in reversed(self._mapping):
[74] Fix | Delete
yield self._mapping[key]
[75] Fix | Delete
[76] Fix | Delete
class _Link(object):
[77] Fix | Delete
__slots__ = 'prev', 'next', 'key', '__weakref__'
[78] Fix | Delete
[79] Fix | Delete
class OrderedDict(dict):
[80] Fix | Delete
'Dictionary that remembers insertion order'
[81] Fix | Delete
# An inherited dict maps keys to values.
[82] Fix | Delete
# The inherited dict provides __getitem__, __len__, __contains__, and get.
[83] Fix | Delete
# The remaining methods are order-aware.
[84] Fix | Delete
# Big-O running times for all methods are the same as regular dictionaries.
[85] Fix | Delete
[86] Fix | Delete
# The internal self.__map dict maps keys to links in a doubly linked list.
[87] Fix | Delete
# The circular doubly linked list starts and ends with a sentinel element.
[88] Fix | Delete
# The sentinel element never gets deleted (this simplifies the algorithm).
[89] Fix | Delete
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
[90] Fix | Delete
# The prev links are weakref proxies (to prevent circular references).
[91] Fix | Delete
# Individual links are kept alive by the hard reference in self.__map.
[92] Fix | Delete
# Those hard references disappear when a key is deleted from an OrderedDict.
[93] Fix | Delete
[94] Fix | Delete
def __init__(self, other=(), /, **kwds):
[95] Fix | Delete
'''Initialize an ordered dictionary. The signature is the same as
[96] Fix | Delete
regular dictionaries. Keyword argument order is preserved.
[97] Fix | Delete
'''
[98] Fix | Delete
try:
[99] Fix | Delete
self.__root
[100] Fix | Delete
except AttributeError:
[101] Fix | Delete
self.__hardroot = _Link()
[102] Fix | Delete
self.__root = root = _proxy(self.__hardroot)
[103] Fix | Delete
root.prev = root.next = root
[104] Fix | Delete
self.__map = {}
[105] Fix | Delete
self.__update(other, **kwds)
[106] Fix | Delete
[107] Fix | Delete
def __setitem__(self, key, value,
[108] Fix | Delete
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
[109] Fix | Delete
'od.__setitem__(i, y) <==> od[i]=y'
[110] Fix | Delete
# Setting a new item creates a new link at the end of the linked list,
[111] Fix | Delete
# and the inherited dictionary is updated with the new key/value pair.
[112] Fix | Delete
if key not in self:
[113] Fix | Delete
self.__map[key] = link = Link()
[114] Fix | Delete
root = self.__root
[115] Fix | Delete
last = root.prev
[116] Fix | Delete
link.prev, link.next, link.key = last, root, key
[117] Fix | Delete
last.next = link
[118] Fix | Delete
root.prev = proxy(link)
[119] Fix | Delete
dict_setitem(self, key, value)
[120] Fix | Delete
[121] Fix | Delete
def __delitem__(self, key, dict_delitem=dict.__delitem__):
[122] Fix | Delete
'od.__delitem__(y) <==> del od[y]'
[123] Fix | Delete
# Deleting an existing item uses self.__map to find the link which gets
[124] Fix | Delete
# removed by updating the links in the predecessor and successor nodes.
[125] Fix | Delete
dict_delitem(self, key)
[126] Fix | Delete
link = self.__map.pop(key)
[127] Fix | Delete
link_prev = link.prev
[128] Fix | Delete
link_next = link.next
[129] Fix | Delete
link_prev.next = link_next
[130] Fix | Delete
link_next.prev = link_prev
[131] Fix | Delete
link.prev = None
[132] Fix | Delete
link.next = None
[133] Fix | Delete
[134] Fix | Delete
def __iter__(self):
[135] Fix | Delete
'od.__iter__() <==> iter(od)'
[136] Fix | Delete
# Traverse the linked list in order.
[137] Fix | Delete
root = self.__root
[138] Fix | Delete
curr = root.next
[139] Fix | Delete
while curr is not root:
[140] Fix | Delete
yield curr.key
[141] Fix | Delete
curr = curr.next
[142] Fix | Delete
[143] Fix | Delete
def __reversed__(self):
[144] Fix | Delete
'od.__reversed__() <==> reversed(od)'
[145] Fix | Delete
# Traverse the linked list in reverse order.
[146] Fix | Delete
root = self.__root
[147] Fix | Delete
curr = root.prev
[148] Fix | Delete
while curr is not root:
[149] Fix | Delete
yield curr.key
[150] Fix | Delete
curr = curr.prev
[151] Fix | Delete
[152] Fix | Delete
def clear(self):
[153] Fix | Delete
'od.clear() -> None. Remove all items from od.'
[154] Fix | Delete
root = self.__root
[155] Fix | Delete
root.prev = root.next = root
[156] Fix | Delete
self.__map.clear()
[157] Fix | Delete
dict.clear(self)
[158] Fix | Delete
[159] Fix | Delete
def popitem(self, last=True):
[160] Fix | Delete
'''Remove and return a (key, value) pair from the dictionary.
[161] Fix | Delete
[162] Fix | Delete
Pairs are returned in LIFO order if last is true or FIFO order if false.
[163] Fix | Delete
'''
[164] Fix | Delete
if not self:
[165] Fix | Delete
raise KeyError('dictionary is empty')
[166] Fix | Delete
root = self.__root
[167] Fix | Delete
if last:
[168] Fix | Delete
link = root.prev
[169] Fix | Delete
link_prev = link.prev
[170] Fix | Delete
link_prev.next = root
[171] Fix | Delete
root.prev = link_prev
[172] Fix | Delete
else:
[173] Fix | Delete
link = root.next
[174] Fix | Delete
link_next = link.next
[175] Fix | Delete
root.next = link_next
[176] Fix | Delete
link_next.prev = root
[177] Fix | Delete
key = link.key
[178] Fix | Delete
del self.__map[key]
[179] Fix | Delete
value = dict.pop(self, key)
[180] Fix | Delete
return key, value
[181] Fix | Delete
[182] Fix | Delete
def move_to_end(self, key, last=True):
[183] Fix | Delete
'''Move an existing element to the end (or beginning if last is false).
[184] Fix | Delete
[185] Fix | Delete
Raise KeyError if the element does not exist.
[186] Fix | Delete
'''
[187] Fix | Delete
link = self.__map[key]
[188] Fix | Delete
link_prev = link.prev
[189] Fix | Delete
link_next = link.next
[190] Fix | Delete
soft_link = link_next.prev
[191] Fix | Delete
link_prev.next = link_next
[192] Fix | Delete
link_next.prev = link_prev
[193] Fix | Delete
root = self.__root
[194] Fix | Delete
if last:
[195] Fix | Delete
last = root.prev
[196] Fix | Delete
link.prev = last
[197] Fix | Delete
link.next = root
[198] Fix | Delete
root.prev = soft_link
[199] Fix | Delete
last.next = link
[200] Fix | Delete
else:
[201] Fix | Delete
first = root.next
[202] Fix | Delete
link.prev = root
[203] Fix | Delete
link.next = first
[204] Fix | Delete
first.prev = soft_link
[205] Fix | Delete
root.next = link
[206] Fix | Delete
[207] Fix | Delete
def __sizeof__(self):
[208] Fix | Delete
sizeof = _sys.getsizeof
[209] Fix | Delete
n = len(self) + 1 # number of links including root
[210] Fix | Delete
size = sizeof(self.__dict__) # instance dictionary
[211] Fix | Delete
size += sizeof(self.__map) * 2 # internal dict and inherited dict
[212] Fix | Delete
size += sizeof(self.__hardroot) * n # link objects
[213] Fix | Delete
size += sizeof(self.__root) * n # proxy objects
[214] Fix | Delete
return size
[215] Fix | Delete
[216] Fix | Delete
update = __update = _collections_abc.MutableMapping.update
[217] Fix | Delete
[218] Fix | Delete
def keys(self):
[219] Fix | Delete
"D.keys() -> a set-like object providing a view on D's keys"
[220] Fix | Delete
return _OrderedDictKeysView(self)
[221] Fix | Delete
[222] Fix | Delete
def items(self):
[223] Fix | Delete
"D.items() -> a set-like object providing a view on D's items"
[224] Fix | Delete
return _OrderedDictItemsView(self)
[225] Fix | Delete
[226] Fix | Delete
def values(self):
[227] Fix | Delete
"D.values() -> an object providing a view on D's values"
[228] Fix | Delete
return _OrderedDictValuesView(self)
[229] Fix | Delete
[230] Fix | Delete
__ne__ = _collections_abc.MutableMapping.__ne__
[231] Fix | Delete
[232] Fix | Delete
__marker = object()
[233] Fix | Delete
[234] Fix | Delete
def pop(self, key, default=__marker):
[235] Fix | Delete
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
[236] Fix | Delete
value. If key is not found, d is returned if given, otherwise KeyError
[237] Fix | Delete
is raised.
[238] Fix | Delete
[239] Fix | Delete
'''
[240] Fix | Delete
if key in self:
[241] Fix | Delete
result = self[key]
[242] Fix | Delete
del self[key]
[243] Fix | Delete
return result
[244] Fix | Delete
if default is self.__marker:
[245] Fix | Delete
raise KeyError(key)
[246] Fix | Delete
return default
[247] Fix | Delete
[248] Fix | Delete
def setdefault(self, key, default=None):
[249] Fix | Delete
'''Insert key with a value of default if key is not in the dictionary.
[250] Fix | Delete
[251] Fix | Delete
Return the value for key if key is in the dictionary, else default.
[252] Fix | Delete
'''
[253] Fix | Delete
if key in self:
[254] Fix | Delete
return self[key]
[255] Fix | Delete
self[key] = default
[256] Fix | Delete
return default
[257] Fix | Delete
[258] Fix | Delete
@_recursive_repr()
[259] Fix | Delete
def __repr__(self):
[260] Fix | Delete
'od.__repr__() <==> repr(od)'
[261] Fix | Delete
if not self:
[262] Fix | Delete
return '%s()' % (self.__class__.__name__,)
[263] Fix | Delete
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
[264] Fix | Delete
[265] Fix | Delete
def __reduce__(self):
[266] Fix | Delete
'Return state information for pickling'
[267] Fix | Delete
inst_dict = vars(self).copy()
[268] Fix | Delete
for k in vars(OrderedDict()):
[269] Fix | Delete
inst_dict.pop(k, None)
[270] Fix | Delete
return self.__class__, (), inst_dict or None, None, iter(self.items())
[271] Fix | Delete
[272] Fix | Delete
def copy(self):
[273] Fix | Delete
'od.copy() -> a shallow copy of od'
[274] Fix | Delete
return self.__class__(self)
[275] Fix | Delete
[276] Fix | Delete
@classmethod
[277] Fix | Delete
def fromkeys(cls, iterable, value=None):
[278] Fix | Delete
'''Create a new ordered dictionary with keys from iterable and values set to value.
[279] Fix | Delete
'''
[280] Fix | Delete
self = cls()
[281] Fix | Delete
for key in iterable:
[282] Fix | Delete
self[key] = value
[283] Fix | Delete
return self
[284] Fix | Delete
[285] Fix | Delete
def __eq__(self, other):
[286] Fix | Delete
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
[287] Fix | Delete
while comparison to a regular mapping is order-insensitive.
[288] Fix | Delete
[289] Fix | Delete
'''
[290] Fix | Delete
if isinstance(other, OrderedDict):
[291] Fix | Delete
return dict.__eq__(self, other) and all(map(_eq, self, other))
[292] Fix | Delete
return dict.__eq__(self, other)
[293] Fix | Delete
[294] Fix | Delete
[295] Fix | Delete
try:
[296] Fix | Delete
from _collections import OrderedDict
[297] Fix | Delete
except ImportError:
[298] Fix | Delete
# Leave the pure Python version in place.
[299] Fix | Delete
pass
[300] Fix | Delete
[301] Fix | Delete
[302] Fix | Delete
################################################################################
[303] Fix | Delete
### namedtuple
[304] Fix | Delete
################################################################################
[305] Fix | Delete
[306] Fix | Delete
try:
[307] Fix | Delete
from _collections import _tuplegetter
[308] Fix | Delete
except ImportError:
[309] Fix | Delete
_tuplegetter = lambda index, doc: property(_itemgetter(index), doc=doc)
[310] Fix | Delete
[311] Fix | Delete
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
[312] Fix | Delete
"""Returns a new subclass of tuple with named fields.
[313] Fix | Delete
[314] Fix | Delete
>>> Point = namedtuple('Point', ['x', 'y'])
[315] Fix | Delete
>>> Point.__doc__ # docstring for the new class
[316] Fix | Delete
'Point(x, y)'
[317] Fix | Delete
>>> p = Point(11, y=22) # instantiate with positional args or keywords
[318] Fix | Delete
>>> p[0] + p[1] # indexable like a plain tuple
[319] Fix | Delete
33
[320] Fix | Delete
>>> x, y = p # unpack like a regular tuple
[321] Fix | Delete
>>> x, y
[322] Fix | Delete
(11, 22)
[323] Fix | Delete
>>> p.x + p.y # fields also accessible by name
[324] Fix | Delete
33
[325] Fix | Delete
>>> d = p._asdict() # convert to a dictionary
[326] Fix | Delete
>>> d['x']
[327] Fix | Delete
11
[328] Fix | Delete
>>> Point(**d) # convert from a dictionary
[329] Fix | Delete
Point(x=11, y=22)
[330] Fix | Delete
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
[331] Fix | Delete
Point(x=100, y=22)
[332] Fix | Delete
[333] Fix | Delete
"""
[334] Fix | Delete
[335] Fix | Delete
# Validate the field names. At the user's option, either generate an error
[336] Fix | Delete
# message or automatically replace the field name with a valid name.
[337] Fix | Delete
if isinstance(field_names, str):
[338] Fix | Delete
field_names = field_names.replace(',', ' ').split()
[339] Fix | Delete
field_names = list(map(str, field_names))
[340] Fix | Delete
typename = _sys.intern(str(typename))
[341] Fix | Delete
[342] Fix | Delete
if rename:
[343] Fix | Delete
seen = set()
[344] Fix | Delete
for index, name in enumerate(field_names):
[345] Fix | Delete
if (not name.isidentifier()
[346] Fix | Delete
or _iskeyword(name)
[347] Fix | Delete
or name.startswith('_')
[348] Fix | Delete
or name in seen):
[349] Fix | Delete
field_names[index] = f'_{index}'
[350] Fix | Delete
seen.add(name)
[351] Fix | Delete
[352] Fix | Delete
for name in [typename] + field_names:
[353] Fix | Delete
if type(name) is not str:
[354] Fix | Delete
raise TypeError('Type names and field names must be strings')
[355] Fix | Delete
if not name.isidentifier():
[356] Fix | Delete
raise ValueError('Type names and field names must be valid '
[357] Fix | Delete
f'identifiers: {name!r}')
[358] Fix | Delete
if _iskeyword(name):
[359] Fix | Delete
raise ValueError('Type names and field names cannot be a '
[360] Fix | Delete
f'keyword: {name!r}')
[361] Fix | Delete
[362] Fix | Delete
seen = set()
[363] Fix | Delete
for name in field_names:
[364] Fix | Delete
if name.startswith('_') and not rename:
[365] Fix | Delete
raise ValueError('Field names cannot start with an underscore: '
[366] Fix | Delete
f'{name!r}')
[367] Fix | Delete
if name in seen:
[368] Fix | Delete
raise ValueError(f'Encountered duplicate field name: {name!r}')
[369] Fix | Delete
seen.add(name)
[370] Fix | Delete
[371] Fix | Delete
field_defaults = {}
[372] Fix | Delete
if defaults is not None:
[373] Fix | Delete
defaults = tuple(defaults)
[374] Fix | Delete
if len(defaults) > len(field_names):
[375] Fix | Delete
raise TypeError('Got more default values than field names')
[376] Fix | Delete
field_defaults = dict(reversed(list(zip(reversed(field_names),
[377] Fix | Delete
reversed(defaults)))))
[378] Fix | Delete
[379] Fix | Delete
# Variables used in the methods and docstrings
[380] Fix | Delete
field_names = tuple(map(_sys.intern, field_names))
[381] Fix | Delete
num_fields = len(field_names)
[382] Fix | Delete
arg_list = repr(field_names).replace("'", "")[1:-1]
[383] Fix | Delete
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
[384] Fix | Delete
tuple_new = tuple.__new__
[385] Fix | Delete
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
[386] Fix | Delete
[387] Fix | Delete
# Create all the named tuple methods to be added to the class namespace
[388] Fix | Delete
[389] Fix | Delete
s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
[390] Fix | Delete
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
[391] Fix | Delete
# Note: exec() has the side-effect of interning the field names
[392] Fix | Delete
exec(s, namespace)
[393] Fix | Delete
__new__ = namespace['__new__']
[394] Fix | Delete
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
[395] Fix | Delete
if defaults is not None:
[396] Fix | Delete
__new__.__defaults__ = defaults
[397] Fix | Delete
[398] Fix | Delete
@classmethod
[399] Fix | Delete
def _make(cls, iterable):
[400] Fix | Delete
result = tuple_new(cls, iterable)
[401] Fix | Delete
if _len(result) != num_fields:
[402] Fix | Delete
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
[403] Fix | Delete
return result
[404] Fix | Delete
[405] Fix | Delete
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
[406] Fix | Delete
'or iterable')
[407] Fix | Delete
[408] Fix | Delete
def _replace(self, /, **kwds):
[409] Fix | Delete
result = self._make(_map(kwds.pop, field_names, self))
[410] Fix | Delete
if kwds:
[411] Fix | Delete
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
[412] Fix | Delete
return result
[413] Fix | Delete
[414] Fix | Delete
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
[415] Fix | Delete
'fields with new values')
[416] Fix | Delete
[417] Fix | Delete
def __repr__(self):
[418] Fix | Delete
'Return a nicely formatted representation string'
[419] Fix | Delete
return self.__class__.__name__ + repr_fmt % self
[420] Fix | Delete
[421] Fix | Delete
def _asdict(self):
[422] Fix | Delete
'Return a new dict which maps field names to their values.'
[423] Fix | Delete
return _dict(_zip(self._fields, self))
[424] Fix | Delete
[425] Fix | Delete
def __getnewargs__(self):
[426] Fix | Delete
'Return self as a plain tuple. Used by copy and pickle.'
[427] Fix | Delete
return _tuple(self)
[428] Fix | Delete
[429] Fix | Delete
# Modify function metadata to help with introspection and debugging
[430] Fix | Delete
for method in (__new__, _make.__func__, _replace,
[431] Fix | Delete
__repr__, _asdict, __getnewargs__):
[432] Fix | Delete
method.__qualname__ = f'{typename}.{method.__name__}'
[433] Fix | Delete
[434] Fix | Delete
# Build-up the class namespace dictionary
[435] Fix | Delete
# and use type() to build the result class
[436] Fix | Delete
class_namespace = {
[437] Fix | Delete
'__doc__': f'{typename}({arg_list})',
[438] Fix | Delete
'__slots__': (),
[439] Fix | Delete
'_fields': field_names,
[440] Fix | Delete
'_field_defaults': field_defaults,
[441] Fix | Delete
# alternate spelling for backward compatibility
[442] Fix | Delete
'_fields_defaults': field_defaults,
[443] Fix | Delete
'__new__': __new__,
[444] Fix | Delete
'_make': _make,
[445] Fix | Delete
'_replace': _replace,
[446] Fix | Delete
'__repr__': __repr__,
[447] Fix | Delete
'_asdict': _asdict,
[448] Fix | Delete
'__getnewargs__': __getnewargs__,
[449] Fix | Delete
}
[450] Fix | Delete
for index, name in enumerate(field_names):
[451] Fix | Delete
doc = _sys.intern(f'Alias for field number {index}')
[452] Fix | Delete
class_namespace[name] = _tuplegetter(index, doc)
[453] Fix | Delete
[454] Fix | Delete
result = type(typename, (tuple,), class_namespace)
[455] Fix | Delete
[456] Fix | Delete
# For pickling to work, the __module__ variable needs to be set to the frame
[457] Fix | Delete
# where the named tuple is created. Bypass this step in environments where
[458] Fix | Delete
# sys._getframe is not defined (Jython for example) or sys._getframe is not
[459] Fix | Delete
# defined for arguments greater than 0 (IronPython), or where the user has
[460] Fix | Delete
# specified a particular module.
[461] Fix | Delete
if module is None:
[462] Fix | Delete
try:
[463] Fix | Delete
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
[464] Fix | Delete
except (AttributeError, ValueError):
[465] Fix | Delete
pass
[466] Fix | Delete
if module is not None:
[467] Fix | Delete
result.__module__ = module
[468] Fix | Delete
[469] Fix | Delete
return result
[470] Fix | Delete
[471] Fix | Delete
[472] Fix | Delete
########################################################################
[473] Fix | Delete
### Counter
[474] Fix | Delete
########################################################################
[475] Fix | Delete
[476] Fix | Delete
def _count_elements(mapping, iterable):
[477] Fix | Delete
'Tally elements from the iterable.'
[478] Fix | Delete
mapping_get = mapping.get
[479] Fix | Delete
for elem in iterable:
[480] Fix | Delete
mapping[elem] = mapping_get(elem, 0) + 1
[481] Fix | Delete
[482] Fix | Delete
try: # Load C helper function if available
[483] Fix | Delete
from _collections import _count_elements
[484] Fix | Delete
except ImportError:
[485] Fix | Delete
pass
[486] Fix | Delete
[487] Fix | Delete
class Counter(dict):
[488] Fix | Delete
'''Dict subclass for counting hashable items. Sometimes called a bag
[489] Fix | Delete
or multiset. Elements are stored as dictionary keys and their counts
[490] Fix | Delete
are stored as dictionary values.
[491] Fix | Delete
[492] Fix | Delete
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
[493] Fix | Delete
[494] Fix | Delete
>>> c.most_common(3) # three most common elements
[495] Fix | Delete
[('a', 5), ('b', 4), ('c', 3)]
[496] Fix | Delete
>>> sorted(c) # list all unique elements
[497] Fix | Delete
['a', 'b', 'c', 'd', 'e']
[498] Fix | Delete
>>> ''.join(sorted(c.elements())) # list elements with repetitions
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function