def build(cls, obj):
if isinstance(obj, abc.Mapping):
return cls(obj)
elif isinstance(obj, abc.MutableSequence):
return [cls.build(item) for item in obj]
else: # <8>
return obj
python类MutableSequence()的实例源码
def build(cls, obj): # <5>
if isinstance(obj, abc.Mapping): # <6>
return cls(obj)
elif isinstance(obj, abc.MutableSequence): # <7>
return [cls.build(item) for item in obj]
else: # <8>
return obj
# END EXPLORE0
def __new__(cls, arg): # <1>
if isinstance(arg, abc.Mapping):
return super().__new__(cls) # <2>
elif isinstance(arg, abc.MutableSequence): # <3>
return [cls(item) for item in arg]
else:
return arg
def __new__(cls, arg):
if isinstance(arg, abc.Mapping):
return super().__new__(cls)
elif isinstance(arg, abc.MutableSequence):
return [cls(item) for item in arg]
else:
return arg
def test_MutableSequence(self):
for sample in [tuple, str, bytes]:
self.assertNotIsInstance(sample(), MutableSequence)
self.assertFalse(issubclass(sample, MutableSequence))
for sample in [list, bytearray]:
self.assertIsInstance(sample(), MutableSequence)
self.assertTrue(issubclass(sample, MutableSequence))
self.assertFalse(issubclass(str, MutableSequence))
self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
'__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
def get_longer(old, new):
"""Get the longer of two command sequences when one is a superset of
the other. Otherwise, return a list containing both.
"""
try:
pngs = ('\\begin', '\\end')
old_parts = {x for x in sep_RE.split(old) if x if x not in pngs}
new_parts = {y for y in sep_RE.split(new) if y if y not in pngs}
if new_parts == old_parts and new != old and any('\\begin' in c for c
in (old, new)):
return old if old.startswith('\\begin') else new
elif new_parts.issubset(old_parts):
return old
elif old_parts.issubset(new_parts):
return new
else:
return [old, new]
except TypeError:
# XXX Verify this test is necessary; smells like spam.
if not isinstance(old, abc.MutableSequence):
raise TypeError
# ``new`` must be returned from all combinations to get promoted.
leaders = set()
for sig in old:
res = get_longer(sig, new)
# Ensure 'foo' doesn't get split into ['f', 'o', 'o']
winners = (set(res) if isinstance(res, abc.MutableSequence)
else set((res,)))
sigs = (set(sig) if isinstance(sig, abc.MutableSequence) else
set((sig,)))
# ``new`` is always just a string.
losers = (sigs | set((new,))) - winners
leaders |= winners
leaders -= losers
return sorted(leaders)
return None
def gen_outdict(symbols_it):
"""Without the change of ``ntup.mode`` from str to list, output
would be roughly equivalent to:
>>> dict((gname, {ntup.name: ntup._asdict() for ntup in grp})
for gname, grp in gr_symtups)
...
"""
#
# TODO change all ``mode`` and ``atom`` vals to lists
from collections.abc import MutableSequence
outdict = {}
for groupname, group in symbols_it:
newgroup = {}
for ntup in group:
# ntup = ntup._replace(mode=[ntup.mode])
if ntup.name not in newgroup:
newgroup.update({ntup.name: ntup._asdict()})
else:
existing = newgroup[ntup.name]
for field in 'font symbol'.split():
assert existing[field] == ntup._asdict()[field]
for field in 'atom mode'.split():
if isinstance(existing[field], MutableSequence):
# For now, this can't exist without implementing above.
assert False
if ntup._asdict()[field] not in existing[field]:
existing[field].append(ntup._asdict()[field])
existing[field].sort()
else:
if existing[field] != ntup._asdict()[field]:
existing.update({field: sorted(
[existing[field], ntup._asdict()[field]])})
outdict.update({groupname: newgroup})
return outdict
# Among the first few lines of the source file are js var initializations for
# creating `module.exports` objects. These take the form: `var foo = "foo";`.
# Snag these and store them as a dict alongside original comment heading.
def fake_deepdiff(one, two, indent=4, path=None, strict_strings=None):
"""Compare two term dictionaries. ``strict_strings=False`` treats
strings that contain the same combination of words as equal.
"""
for k, v in one.items():
_one = v
_two = two.get(k)
if _one == _two:
continue
if all(isinstance(d, abc.MutableMapping) for d in (_one, _two)):
_path = path if path is not None else []
_path += ['{:<{width}}{}'.format('', k, width=indent)]
fake_deepdiff(_one, _two, indent + 4, _path, strict_strings)
continue
if (all(isinstance(l, abc.MutableSequence) for l in (_one, _two)) and
set(tuple(x) for x in _one if isinstance(x, abc.Sequence)) ==
set(tuple(x) for x in _two if isinstance(x, abc.Sequence))):
continue
if all(isinstance(l, str) for l in (_one, _two)):
if (strict_strings is False and
set(c.strip(';:,.?=_-\n') for c in _one.split()) ==
set(c.strip(';:,.?=_-\n') for c in _two.split())):
continue
else:
_one = _one.strip().replace('\n', '')
_two = _two.strip().replace('\n', '')
print('\n'.join(path) if path else '')
print('{:<{width}}{}'.format('', k, width=indent))
print('{:<{width}}one: {}'.format('', _one, width=indent + 4))
print('{:<{width}}two: {}'.format('', _two, width=indent + 4))
def test_MutableSequence(self):
for sample in [tuple, str, bytes]:
self.assertNotIsInstance(sample(), MutableSequence)
self.assertFalse(issubclass(sample, MutableSequence))
for sample in [list, bytearray]:
self.assertIsInstance(sample(), MutableSequence)
self.assertTrue(issubclass(sample, MutableSequence))
self.assertFalse(issubclass(str, MutableSequence))
self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
'__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
def test_MutableSequence(self):
for sample in [tuple, str, bytes]:
self.assertNotIsInstance(sample(), MutableSequence)
self.assertFalse(issubclass(sample, MutableSequence))
for sample in [list, bytearray]:
self.assertIsInstance(sample(), MutableSequence)
self.assertTrue(issubclass(sample, MutableSequence))
self.assertFalse(issubclass(str, MutableSequence))
self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
'__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
def __new__(cls, arg): # <1>
if isinstance(arg, abc.Mapping):
return super().__new__(cls) # <2>
elif isinstance(arg, abc.MutableSequence): # <3>
return [cls(item) for item in arg]
else:
return arg
# END EXPLORE2
# BEGIN EXPLORE1
def sequence_of_type(_type, mutable, instance, attribute, value):
"""
Validate that a value is a Sequence containing a specific type.
:arg _type: The type of the values inside of the sequence
:arg mutable: selects whether a sequence can be mutable or not
:mutable: only mutable sequences are allowed
:immutable: only immutable sequences are allowed
:both: both mutable and immutable sequences are allowed
:arg instance: The instance of the attr.s class that is being created
:arg attribute: The attribute of the attr.s class that is being set
:arg value: The value the attribute is being set to
This function will be used with the :meth:`attr.ib` validate parameter and
:func:`functools.partial`. Example::
@attr.s
class CommodityData:
type = attr.ib(validator=partial(enum_validator, CommodityType))
"""
if mutable == 'both':
msg = 'a Sequence'
elif mutable == 'mutable':
msg = 'a MutableSequence'
elif mutable == 'immutable':
msg = 'an Immutable Sequence'
else:
raise ValueError('sequence_of_type was given an improper argument for mutable')
if not isinstance(value, Sequence):
raise ValueError('{} is not {}'.format(value, msg))
if isinstance(value, MutableSequence):
if mutable == 'immutable':
raise ValueError('{} is not {}'.format(value, msg))
else:
if mutable == 'mutable':
raise ValueError('{} is not {}'.format(value, msg))
for entry in value:
if not isinstance(entry, _type):
raise ValueError('The Sequence element {} is not a {}'.format(value, _type))
def test_MutableSequence_mixins(self):
# Test the mixins of MutableSequence by creating a miminal concrete
# class inherited from it.
class MutableSequenceSubclass(MutableSequence):
def __init__(self):
self.lst = []
def __setitem__(self, index, value):
self.lst[index] = value
def __getitem__(self, index):
return self.lst[index]
def __len__(self):
return len(self.lst)
def __delitem__(self, index):
del self.lst[index]
def insert(self, index, value):
self.lst.insert(index, value)
mss = MutableSequenceSubclass()
mss.append(0)
mss.extend((1, 2, 3, 4))
self.assertEqual(len(mss), 5)
self.assertEqual(mss[3], 3)
mss.reverse()
self.assertEqual(mss[3], 1)
mss.pop()
self.assertEqual(len(mss), 4)
mss.remove(3)
self.assertEqual(len(mss), 3)
mss += (10, 20, 30)
self.assertEqual(len(mss), 6)
self.assertEqual(mss[-1], 30)
mss.clear()
self.assertEqual(len(mss), 0)
################################################################################
### Counter
################################################################################
def test_MutableSequence_mixins(self):
# Test the mixins of MutableSequence by creating a miminal concrete
# class inherited from it.
class MutableSequenceSubclass(MutableSequence):
def __init__(self):
self.lst = []
def __setitem__(self, index, value):
self.lst[index] = value
def __getitem__(self, index):
return self.lst[index]
def __len__(self):
return len(self.lst)
def __delitem__(self, index):
del self.lst[index]
def insert(self, index, value):
self.lst.insert(index, value)
mss = MutableSequenceSubclass()
mss.append(0)
mss.extend((1, 2, 3, 4))
self.assertEqual(len(mss), 5)
self.assertEqual(mss[3], 3)
mss.reverse()
self.assertEqual(mss[3], 1)
mss.pop()
self.assertEqual(len(mss), 4)
mss.remove(3)
self.assertEqual(len(mss), 3)
mss += (10, 20, 30)
self.assertEqual(len(mss), 6)
self.assertEqual(mss[-1], 30)
mss.clear()
self.assertEqual(len(mss), 0)
################################################################################
### Counter
################################################################################
def test_MutableSequence_mixins(self):
# Test the mixins of MutableSequence by creating a miminal concrete
# class inherited from it.
class MutableSequenceSubclass(MutableSequence):
def __init__(self):
self.lst = []
def __setitem__(self, index, value):
self.lst[index] = value
def __getitem__(self, index):
return self.lst[index]
def __len__(self):
return len(self.lst)
def __delitem__(self, index):
del self.lst[index]
def insert(self, index, value):
self.lst.insert(index, value)
mss = MutableSequenceSubclass()
mss.append(0)
mss.extend((1, 2, 3, 4))
self.assertEqual(len(mss), 5)
self.assertEqual(mss[3], 3)
mss.reverse()
self.assertEqual(mss[3], 1)
mss.pop()
self.assertEqual(len(mss), 4)
mss.remove(3)
self.assertEqual(len(mss), 3)
mss += (10, 20, 30)
self.assertEqual(len(mss), 6)
self.assertEqual(mss[-1], 30)
mss.clear()
self.assertEqual(len(mss), 0)
################################################################################
### Counter
################################################################################