def read(source):
"""Read palette from `source`
source: file handle, file name or iterable of strings
Returns list of string lines.
Raises TypeError or OSError.
"""
if hasattr(source, 'readlines') and callable(source.readlines):
lines = source.readlines()
elif isinstance(source, str):
try:
with open(source, mode='r') as f:
lines = f.readlines()
except OSError as e:
raise ThemeError('Unable to read {!r}: {}'.format(source, e.strerror))
elif isinstance(source, abc.Iterable):
lines = source
else:
raise TypeError('Invalid source: {!r}'.format(source))
return [l.rstrip('\n') for l in lines]
python类Iterable()的实例源码
def test_Iterable(self):
# Check some non-iterables
non_samples = [None, 42, 3.14, 1j]
for x in non_samples:
self.assertNotIsInstance(x, Iterable)
self.assertFalse(issubclass(type(x), Iterable), repr(type(x)))
# Check some iterables
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
(lambda: (yield))(),
(x for x in []),
]
for x in samples:
self.assertIsInstance(x, Iterable)
self.assertTrue(issubclass(type(x), Iterable), repr(type(x)))
# Check direct subclassing
class I(Iterable):
def __iter__(self):
return super().__iter__()
self.assertEqual(list(I()), [])
self.assertFalse(issubclass(str, I))
self.validate_abstract_methods(Iterable, '__iter__')
self.validate_isinstance(Iterable, '__iter__')
def isiterable(obj):
"""
Function that determines if an object is an iterable, not including
str.
Parameters
----------
obj : object
Object to test if it is an iterable.
Returns
-------
bool : bool
True if the obj is an iterable, False if not.
"""
if isinstance(obj, str):
return False
else:
return isinstance(obj, Iterable)
def isiterable(obj):
"""
Function that determines if an object is an iterable, not including
str.
Parameters
----------
obj : object
Object to test if it is an iterable.
Returns
-------
bool : bool
True if the obj is an iterable, False if not.
"""
if isinstance(obj, str):
return False
else:
return isinstance(obj, Iterable)
def test_Iterable(self):
# Check some non-iterables
non_samples = [None, 42, 3.14, 1j]
for x in non_samples:
self.assertNotIsInstance(x, Iterable)
self.assertFalse(issubclass(type(x), Iterable), repr(type(x)))
# Check some iterables
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
(lambda: (yield))(),
(x for x in []),
]
for x in samples:
self.assertIsInstance(x, Iterable)
self.assertTrue(issubclass(type(x), Iterable), repr(type(x)))
# Check direct subclassing
class I(Iterable):
def __iter__(self):
return super().__iter__()
self.assertEqual(list(I()), [])
self.assertFalse(issubclass(str, I))
self.validate_abstract_methods(Iterable, '__iter__')
self.validate_isinstance(Iterable, '__iter__')
def test_construct(self):
def _check_iterator(it):
self.assertIsInstance(it, abc.Iterator)
self.assertIsInstance(it, abc.Iterable)
s = struct.Struct('>ibcp')
it = s.iter_unpack(b"")
_check_iterator(it)
it = s.iter_unpack(b"1234567")
_check_iterator(it)
# Wrong bytes length
with self.assertRaises(struct.error):
s.iter_unpack(b"123456")
with self.assertRaises(struct.error):
s.iter_unpack(b"12345678")
# Zero-length struct
s = struct.Struct('>')
with self.assertRaises(struct.error):
s.iter_unpack(b"")
with self.assertRaises(struct.error):
s.iter_unpack(b"12")
def isdisjoint(self, other):
r"""Return True if the set has no elements in common with other.
Sets are disjoint iff their intersection is the empty set.
>>> ms = Multiset('aab')
>>> ms.isdisjoint('bc')
False
>>> ms.isdisjoint(Multiset('ccd'))
True
Args:
other: The other set to check disjointedness. Can also be an :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
if isinstance(other, _sequence_types + (BaseMultiset, )):
pass
elif not isinstance(other, Container):
other = self._as_multiset(other)
return all(element not in other for element in self._elements.keys())
def _as_mapping(iterable):
if isinstance(iterable, BaseMultiset):
return iterable._elements
if isinstance(iterable, dict):
return iterable
if isinstance(iterable, _all_basic_types):
pass # create dictionary below
elif isinstance(iterable, Mapping):
return iterable
elif not isinstance(iterable, Iterable):
raise TypeError("'%s' object is not iterable" % type(iterable))
mapping = dict()
for element in iterable:
if element in mapping:
mapping[element] += 1
else:
mapping[element] = 1
return mapping
def test_Iterable(self):
# Check some non-iterables
non_samples = [None, 42, 3.14, 1j]
for x in non_samples:
self.assertNotIsInstance(x, Iterable)
self.assertFalse(issubclass(type(x), Iterable), repr(type(x)))
# Check some iterables
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
(lambda: (yield))(),
(x for x in []),
]
for x in samples:
self.assertIsInstance(x, Iterable)
self.assertTrue(issubclass(type(x), Iterable), repr(type(x)))
# Check direct subclassing
class I(Iterable):
def __iter__(self):
return super().__iter__()
self.assertEqual(list(I()), [])
self.assertFalse(issubclass(str, I))
self.validate_abstract_methods(Iterable, '__iter__')
self.validate_isinstance(Iterable, '__iter__')
def test_construct(self):
def _check_iterator(it):
self.assertIsInstance(it, abc.Iterator)
self.assertIsInstance(it, abc.Iterable)
s = struct.Struct('>ibcp')
it = s.iter_unpack(b"")
_check_iterator(it)
it = s.iter_unpack(b"1234567")
_check_iterator(it)
# Wrong bytes length
with self.assertRaises(struct.error):
s.iter_unpack(b"123456")
with self.assertRaises(struct.error):
s.iter_unpack(b"12345678")
# Zero-length struct
s = struct.Struct('>')
with self.assertRaises(struct.error):
s.iter_unpack(b"")
with self.assertRaises(struct.error):
s.iter_unpack(b"12")
def cast_json(json_dict):
"""Convert an arbitrary JSON source into MongoDB
compatible format."""
DOT = '_'
DOLLAR = '\uff04'
if isinstance(json_dict, str):
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if six.PY2 and isinstance(json_dict, unicode): # noqa
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if isinstance(json_dict, Mapping):
return {cast_json(key): cast_json(value) for
key, value in json_dict.items()}
elif isinstance(json_dict, Iterable):
return [cast_json(o) for o in json_dict]
else:
return json_dict
def cast_json(json_dict):
"""Convert an arbitrary JSON source into MongoDB
compatible format."""
DOT = '_'
DOLLAR = '\uff04'
if isinstance(json_dict, str):
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if six.PY2 and isinstance(json_dict, unicode): # noqa
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if isinstance(json_dict, Mapping):
return {cast_json(key): cast_json(value) for
key, value in json_dict.items()}
elif isinstance(json_dict, Iterable):
return [cast_json(o) for o in json_dict]
else:
return json_dict
def cast_json(json_dict):
"""Convert an arbitrary JSON source into MongoDB
compatible format."""
DOT = '_'
DOLLAR = '\uff04'
if isinstance(json_dict, str):
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if six.PY2 and isinstance(json_dict, unicode): # noqa
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if isinstance(json_dict, Mapping):
return {cast_json(key): cast_json(value) for
key, value in json_dict.items()}
elif isinstance(json_dict, Iterable):
return [cast_json(o) for o in json_dict]
else:
return json_dict
def cast_json(json_dict):
"""Convert an arbitrary JSON source into MongoDB
compatible format."""
DOT = '_'
DOLLAR = '\uff04'
if isinstance(json_dict, str):
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if six.PY2 and isinstance(json_dict, unicode): # noqa
return json_dict.replace('.', DOT).replace('$', DOLLAR)
if isinstance(json_dict, Mapping):
return {cast_json(key): cast_json(value) for
key, value in json_dict.items()}
elif isinstance(json_dict, Iterable):
return [cast_json(o) for o in json_dict]
else:
return json_dict
def handle_extract_pattern(pattern, ifiles, _groups, _vars):
'''Handle input option pattern'''
if pattern is None or not pattern:
patterns = []
elif isinstance(pattern, str):
patterns = [pattern]
elif isinstance(pattern, Iterable):
patterns = pattern
else:
raise ValueError(f'Unacceptable value for parameter pattern: {pattern}')
#
for pattern in patterns:
res = extract_pattern(pattern, ifiles)
# now, assign the variables to env
for k, v in res.items():
if k in ('step_input', 'step_output', 'step_depends') or k.startswith('_'):
raise RuntimeError(f'Pattern defined variable {k} is not allowed')
env.sos_dict[k] = v
# also make k, v pair with _input
Base_Step_Executor.handle_paired_with(res.keys(), ifiles, _groups, _vars)
def frozen(struct):
"""Return an immutable, hashable version of the given data structure.
Iterators (including generators) are hashable but mutable, so they
are evaluated and returned as tuples---if they are infinite, this
function will not exit.
"""
if isinstance(struct, Mapping):
return frozenset((k, frozen(v)) for k, v in struct.items())
if isinstance(struct, Set):
return frozenset(frozen(item) for item in struct)
if isinstance(struct, Iterable): # Includes iterators and generators
return tuple(frozen(item) for item in struct)
hash(struct) # Raise TypeError for unhashable objects
return struct
def hashified(struct, use_none=False):
"""Return a hashable version of the given data structure.
If use_none is True, returns None instead of raising TypeError for
unhashable types: this will serve as a bad but sometimes passable
hash.
See also functools._make_key, which might be a better choice.
"""
try:
hash(struct)
except TypeError:
pass
else:
# Return the original object if it's already hashable
return struct
if isinstance(struct, Mapping):
return frozenset((k, hashified(v)) for k, v in struct.items())
if isinstance(struct, Set):
return frozenset(hashified(item) for item in struct)
if isinstance(struct, Iterable):
return tuple(hashified(item) for item in struct)
if use_none:
return None
raise TypeError('unhashable type: {.__name__!r}'.format(type(struct)))
def get_blenderID_key(bid):
if isinstance(bid, Iterable):
return "|".join("B" + e.rna_type.name + "#" + get_bid_name(e) for e in bid)
else:
return "B" + bid.rna_type.name + "#" + get_bid_name(bid)
def get_blenderID_name(bid):
if isinstance(bid, Iterable):
return "|".join(get_bid_name(e) for e in bid)
else:
return get_bid_name(bid)
def _is_list(obj):
return (isinstance(obj, Sized) and isinstance(obj, Iterable) and
not isinstance(obj, (Set, Mapping)))
def discretize(value, factor=100):
"""Discretize the given value, pre-multiplying by the given factor"""
if not isinstance(value, Iterable):
return int(value * factor)
int_value = list(deepcopy(value))
for i in range(len(int_value)):
int_value[i] = int(int_value[i] * factor)
return int_value
def take(self, indices):
if self._dtype is np.ndarray:
return self._samples.take(indices, axis=0)
elif isinstance(indices, Iterable):
return self._dtype(itemgetter(*indices)(self._samples))
return self._samples[indices]
def deep_iterate(li, pos=tuple(), yield_pos=False):
"""Iterate over all elements of Iterable li"""
for j, elem in enumerate(li):
if isinstance(elem, Iterable) and not isinstance(elem, str):
yield from deep_iterate(
elem, pos=(pos + (j, )), yield_pos=yield_pos
)
else:
yield (elem, pos + (j, )) if yield_pos else elem
def non_string_iterable(v):
"""Return whether the object is any Iterable other than str."""
return isinstance(v, Iterable) and not isinstance(v, str)
def __init__(self, d={}, normalize=str.lower, base_factory=dict):
self.normalize = normalize
self._d = base_factory()
self._k = {}
if isinstance(d, abc.Mapping):
for k, v in d.items():
self.__setitem__(k, v)
elif isinstance(d, abc.Iterable):
for (k, v) in d:
self.__setitem__(k, v)
def options(self):
"""Iterable of all valid values"""
return self._options
def options(self, options):
if not isinstance(options, abc.Iterable):
raise ValueError('Not an iterable: %r', options)
else:
self._options = tuple(options)
for name in ('_default', '_value'):
if getattr(self, name) not in self.options:
setattr(self, name, self.options[0])
def convert(self, value):
if isinstance(value, str):
lst = self.type(value.strip() for value in value.split(','))
elif isinstance(value, abc.Iterable):
lst = self.type(value)
else:
raise ValueError('Not a {}'.format(self.typename))
# Resolve aliases
return [self.resolve_alias(item) for item in lst]
def options(self, options):
if options is None:
self._options = None
elif isinstance(options, abc.Iterable):
self._options = tuple(options)
# Purge new invalid items
for name in ('_default', '_value'):
lst = getattr(self, name)
invalid_items = set(lst).difference(self.options)
for item in invalid_items:
while item in lst:
lst.remove(item)
else:
raise TypeError('options must be sequence or None, not %s: %r' % (type(options).__name__, options))
def color(cls, fg=None, bg=None, text=None):
if isinstance(fg, Iterable) and bg is None:
return cls.color(*fg)
if fg is None and bg is None:
return ""
fg = "" if fg is None else "{:02d}".format(fg)
bg = "" if bg is None else "{:02d}".format(bg)
rv = cls.COLOR + fg
if bg:
rv += "," + bg
if text is None:
return rv
return rv + text + rv