def test_itemiterator_pickling(self):
data = {1:"a", 2:"b", 3:"c"}
# dictviews aren't picklable, only their iterators
itorg = iter(data.items())
d = pickle.dumps(itorg)
it = pickle.loads(d)
# note that the type of type of the unpickled iterator
# is not necessarily the same as the original. It is
# merely an object supporting the iterator protocol, yielding
# the same objects as the original one.
# self.assertEqual(type(itorg), type(it))
#self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(dict(it), data)
it = pickle.loads(d)
drop = next(it)
d = pickle.dumps(it)
it = pickle.loads(d)
del data[drop[0]]
self.assertEqual(dict(it), data)
python类abc()的实例源码
def test_union(self):
u = self.s.union(self.otherword)
for c in self.letters:
self.assertEqual(c in u, c in self.d or c in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
self.assertEqual(type(u), self.basetype)
self.assertRaises(PassThru, self.s.union, check_pass_thru())
self.assertRaises(TypeError, self.s.union, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd'))
self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg'))
self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc'))
self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef'))
self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg'))
# Issue #6573
x = self.thetype()
self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2]))
def test_iterator_pickling(self):
itorg = iter(self.s)
data = self.thetype(self.s)
d = pickle.dumps(itorg)
it = pickle.loads(d)
# Set iterators unpickle as list iterators due to the
# undefined order of set items.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(self.thetype(it), data)
it = pickle.loads(d)
try:
drop = next(it)
except StopIteration:
return
d = pickle.dumps(it)
it = pickle.loads(d)
self.assertEqual(self.thetype(it), data - self.thetype((drop,)))
def test_update(self):
retval = self.s.update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
self.assertIn(c, self.s)
self.assertRaises(PassThru, self.s.update, check_pass_thru())
self.assertRaises(TypeError, self.s.update, [[]])
for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p)), None)
self.assertEqual(s, set(q))
for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
q = 'ahi'
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p), C(q)), None)
self.assertEqual(s, set(s) | set(p) | set(q))
def check_pickle(self, itorg, seq):
d = pickle.dumps(itorg)
it = pickle.loads(d)
# Cannot assert type equality because dict iterators unpickle as list
# iterators.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(list(it), seq)
it = pickle.loads(d)
try:
next(it)
except StopIteration:
return
d = pickle.dumps(it)
it = pickle.loads(d)
self.assertEqual(list(it), seq[1:])
# Test basic use of iter() function
def test_itemiterator_pickling(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
data = {1:"a", 2:"b", 3:"c"}
# dictviews aren't picklable, only their iterators
itorg = iter(data.items())
d = pickle.dumps(itorg, proto)
it = pickle.loads(d)
# note that the type of type of the unpickled iterator
# is not necessarily the same as the original. It is
# merely an object supporting the iterator protocol, yielding
# the same objects as the original one.
# self.assertEqual(type(itorg), type(it))
self.assertIsInstance(it, collections.abc.Iterator)
self.assertEqual(dict(it), data)
it = pickle.loads(d)
drop = next(it)
d = pickle.dumps(it, proto)
it = pickle.loads(d)
del data[drop[0]]
self.assertEqual(dict(it), data)
def test_union(self):
u = self.s.union(self.otherword)
for c in self.letters:
self.assertEqual(c in u, c in self.d or c in self.otherword)
self.assertEqual(self.s, self.thetype(self.word))
self.assertEqual(type(u), self.basetype)
self.assertRaises(PassThru, self.s.union, check_pass_thru())
self.assertRaises(TypeError, self.s.union, [[]])
for C in set, frozenset, dict.fromkeys, str, list, tuple:
self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd'))
self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg'))
self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc'))
self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef'))
self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg'))
# Issue #6573
x = self.thetype()
self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2]))
def test_iterator_pickling(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
itorg = iter(self.s)
data = self.thetype(self.s)
d = pickle.dumps(itorg, proto)
it = pickle.loads(d)
# Set iterators unpickle as list iterators due to the
# undefined order of set items.
# self.assertEqual(type(itorg), type(it))
self.assertIsInstance(it, collections.abc.Iterator)
self.assertEqual(self.thetype(it), data)
it = pickle.loads(d)
try:
drop = next(it)
except StopIteration:
continue
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(self.thetype(it), data - self.thetype((drop,)))
def test_update(self):
retval = self.s.update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
self.assertIn(c, self.s)
self.assertRaises(PassThru, self.s.update, check_pass_thru())
self.assertRaises(TypeError, self.s.update, [[]])
for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p)), None)
self.assertEqual(s, set(q))
for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
q = 'ahi'
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p), C(q)), None)
self.assertEqual(s, set(s) | set(p) | set(q))
def check_pickle(self, itorg, seq):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
d = pickle.dumps(itorg, proto)
it = pickle.loads(d)
# Cannot assert type equality because dict iterators unpickle as list
# iterators.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(list(it), seq)
it = pickle.loads(d)
try:
next(it)
except StopIteration:
continue
d = pickle.dumps(it, proto)
it = pickle.loads(d)
self.assertEqual(list(it), seq[1:])
# Test basic use of iter() function
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
elif not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
else:
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
else:
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def quick_sort(*_coconut_match_to_args, **_coconut_match_to_kwargs):
_coconut_match_check = False
if (_coconut.len(_coconut_match_to_args) == 1) and (_coconut.isinstance(_coconut_match_to_args[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to_args[0]) >= 1):
tail = _coconut.list(_coconut_match_to_args[0][1:])
head = _coconut_match_to_args[0][0]
if (not _coconut_match_to_kwargs):
_coconut_match_check = True
if not _coconut_match_check:
_coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def quick_sort([head] + tail) ='" " in " + _coconut.repr(_coconut.repr(_coconut_match_to_args)))
_coconut_match_err.pattern = 'def quick_sort([head] + tail) ='
_coconut_match_err.value = _coconut_match_to_args
raise _coconut_match_err
"""Sort the input sequence using the quick sort algorithm."""
return (quick_sort([x for x in tail if x < head]) + [head] + quick_sort([x for x in tail if x >= head]))
# Test cases:
def test_itemiterator_pickling(self):
data = {1:"a", 2:"b", 3:"c"}
# dictviews aren't picklable, only their iterators
itorg = iter(data.items())
d = pickle.dumps(itorg)
it = pickle.loads(d)
# note that the type of type of the unpickled iterator
# is not necessarily the same as the original. It is
# merely an object supporting the iterator protocol, yielding
# the same objects as the original one.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(dict(it), data)
it = pickle.loads(d)
drop = next(it)
d = pickle.dumps(it)
it = pickle.loads(d)
del data[drop[0]]
self.assertEqual(dict(it), data)
def test_iterator_pickling(self):
itorg = iter(self.s)
data = self.thetype(self.s)
d = pickle.dumps(itorg)
it = pickle.loads(d)
# Set iterators unpickle as list iterators due to the
# undefined order of set items.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(self.thetype(it), data)
it = pickle.loads(d)
try:
drop = next(it)
except StopIteration:
return
d = pickle.dumps(it)
it = pickle.loads(d)
self.assertEqual(self.thetype(it), data - self.thetype((drop,)))
def test_update(self):
retval = self.s.update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
self.assertIn(c, self.s)
self.assertRaises(PassThru, self.s.update, check_pass_thru())
self.assertRaises(TypeError, self.s.update, [[]])
for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p)), None)
self.assertEqual(s, set(q))
for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
q = 'ahi'
for C in set, frozenset, dict.fromkeys, str, list, tuple:
s = self.thetype('abcba')
self.assertEqual(s.update(C(p), C(q)), None)
self.assertEqual(s, set(s) | set(p) | set(q))
def check_pickle(self, itorg, seq):
d = pickle.dumps(itorg)
it = pickle.loads(d)
# Cannot assert type equality because dict iterators unpickle as list
# iterators.
# self.assertEqual(type(itorg), type(it))
self.assertTrue(isinstance(it, collections.abc.Iterator))
self.assertEqual(list(it), seq)
it = pickle.loads(d)
try:
next(it)
except StopIteration:
return
d = pickle.dumps(it)
it = pickle.loads(d)
self.assertEqual(list(it), seq[1:])
# Test basic use of iter() function
def stable_repr(obj):
if isinstance(obj, str):
return repr(obj)
elif isinstance(obj, collections.abc.Mapping):
items = [stable_repr(k) + ':' + stable_repr(obj[k]) for k in obj.keys()]
return '{' + ', '.join(sorted(items)) + '}'
elif isinstance(obj, collections.abc.Set):
items = [stable_repr(x) for x in obj]
return '{' + ', '.join(sorted(items)) + '}'
elif isinstance(obj, collections.abc.Sequence):
return '[' + ', '.join(stable_repr(k) for k in obj) + ']'
else:
return repr(obj)
#
# A utility function that returns output of a command
def update(self, iterable=None, **kwds):
if iterable is not None:
if isinstance(iterable, collections.abc.Mapping): # <5>
pairs = iterable.items()
else:
pairs = ((k, v) for k, v in iterable) # <6>
for key, value in pairs:
self[key] = value # <7>
if kwds:
self.update(kwds) # <8>
# END STRKEYDICT
def _coconut_igetitem(iterable, index):
if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
return iterable[index]
if not _coconut.isinstance(index, _coconut.slice):
if index < 0:
return _coconut.collections.deque(iterable, maxlen=-index)[0]
return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
if index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
queue = _coconut.collections.deque(iterable, maxlen=-index.start)
if index.stop is not None:
queue = _coconut.tuple(queue)[:index.stop - index.start]
return queue
if (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
return _coconut.tuple(iterable)[index]
return _coconut.itertools.islice(iterable, index.start, index.stop, index.step)
def tee(iterable, n=2):
if n >= 0 and _coconut.isinstance(iterable, (_coconut.tuple, _coconut.frozenset)):
return (iterable,) * n
if n > 0 and (_coconut.hasattr(iterable, "__copy__") or _coconut.isinstance(iterable, _coconut.abc.Sequence)):
return (iterable,) + _coconut.tuple(_coconut.copy.copy(iterable) for _ in _coconut.range(n - 1))
return _coconut.itertools.tee(iterable, n)
def fmap(func, obj):
"""fmap(func, obj) creates a copy of obj with func applied to its contents.
Override by defining .__fmap__(func)."""
if _coconut.hasattr(obj, "__fmap__"):
return obj.__fmap__(func)
args = _coconut_starmap(func, obj.items()) if _coconut.isinstance(obj, _coconut.abc.Mapping) else _coconut_map(func, obj)
if _coconut.isinstance(obj, _coconut.tuple) and _coconut.hasattr(obj, "_make"):
return obj._make(args)
if _coconut.isinstance(obj, (_coconut.map, _coconut.range, _coconut.abc.Iterator)):
return args
if _coconut.isinstance(obj, _coconut.str):
return "".join(args)
return obj.__class__(args)
def sequence(iterable):
"Coerce iterable to sequence, if it is not already one."
return (iterable if isinstance(iterable, collections.abc.Sequence)
else tuple(iterable))
def issequence(x):
"Is x a sequence?"
return isinstance(x, collections.abc.Sequence)
def is_list_or_tuple(obj):
"""Returns True if obj is a list or a tuple"""
return (
isinstance(obj, collections.abc.Sequence) and
not(isinstance(obj, str) or isinstance(obj, bytes))
)