Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 29 additions & 11 deletions Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
import _collections_abc
import sys as _sys

_sys.modules['collections.abc'] = _collections_abc
abc = _collections_abc

from itertools import chain as _chain
from itertools import repeat as _repeat
from itertools import starmap as _starmap
Expand All @@ -46,7 +49,8 @@
_collections_abc.MutableSequence.register(deque)

try:
from _collections import _deque_iterator
# Expose _deque_iterator to support pickling deque iterators
from _collections import _deque_iterator # noqa: F401
except ImportError:
pass

Expand All @@ -59,6 +63,8 @@
# with this instead.
from ._defaultdict import defaultdict

heapq = None # Lazily imported


################################################################################
### OrderedDict
Expand Down Expand Up @@ -461,7 +467,7 @@ def _make(cls, iterable):
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
raise TypeError(f'Got unexpected field names: {list(kwds)!r}')
return result

_replace.__doc__ = (f'Return a new {typename} object replacing specified '
Expand Down Expand Up @@ -499,6 +505,7 @@ def __getnewargs__(self):
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'__replace__': _replace,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
Expand Down Expand Up @@ -592,7 +599,7 @@ class Counter(dict):
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6.3

Expand Down Expand Up @@ -632,7 +639,10 @@ def most_common(self, n=None):
return sorted(self.items(), key=_itemgetter(1), reverse=True)

# Lazy import to speedup Python startup time
import heapq
global heapq
if heapq is None:
import heapq

return heapq.nlargest(n, self.items(), key=_itemgetter(1))

def elements(self):
Expand All @@ -642,7 +652,8 @@ def elements(self):
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']

# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1

>>> import math
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> math.prod(prime_factors.elements())
Expand Down Expand Up @@ -683,7 +694,7 @@ def update(self, iterable=None, /, **kwds):

'''
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# replace behavior results in some of the original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn't have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
Expand Down Expand Up @@ -1018,7 +1029,7 @@ def __getitem__(self, key):
return self.__missing__(key) # support subclasses that define __missing__

def get(self, key, default=None):
return self[key] if key in self else default
return self[key] if key in self else default # needs to make use of __contains__

def __len__(self):
return len(set().union(*self.maps)) # reuses stored hash values if possible
Expand All @@ -1030,7 +1041,10 @@ def __iter__(self):
return iter(d)

def __contains__(self, key):
return any(key in m for m in self.maps)
for mapping in self.maps:
if key in mapping:
return True
return False

def __bool__(self):
return any(self.maps)
Expand All @@ -1040,9 +1054,9 @@ def __repr__(self):
return f'{self.__class__.__name__}({", ".join(map(repr, self.maps))})'

@classmethod
def fromkeys(cls, iterable, *args):
'Create a ChainMap with a single dict created from the iterable.'
return cls(dict.fromkeys(iterable, *args))
def fromkeys(cls, iterable, value=None, /):
'Create a new ChainMap with keys from iterable and values set to value.'
return cls(dict.fromkeys(iterable, value))

def copy(self):
'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
Expand Down Expand Up @@ -1485,6 +1499,8 @@ def format_map(self, mapping):
return self.data.format_map(mapping)

def index(self, sub, start=0, end=_sys.maxsize):
if isinstance(sub, UserString):
sub = sub.data
return self.data.index(sub, start, end)

def isalpha(self):
Expand Down Expand Up @@ -1553,6 +1569,8 @@ def rfind(self, sub, start=0, end=_sys.maxsize):
return self.data.rfind(sub, start, end)

def rindex(self, sub, start=0, end=_sys.maxsize):
if isinstance(sub, UserString):
sub = sub.data
return self.data.rindex(sub, start, end)

def rjust(self, width, *args):
Expand Down
3 changes: 0 additions & 3 deletions Lib/collections/abc.py

This file was deleted.

Loading
Loading