def test_direct_subclassing(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C(B):
pass
self.assertTrue(issubclass(C, B))
self.assertFalse(issubclass(int, C))
python类Iterable()的实例源码
def test_registration(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C:
__hash__ = None # Make sure it isn't hashable by default
self.assertFalse(issubclass(C, B), B.__name__)
B.register(C)
self.assertTrue(issubclass(C, B))
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 piface_config_bundles(request, resources):
"""
Provide the ATAC-Seq pipeline interface as a fixture, including resources.
Note that this represents the configuration data for the interface for a
single pipeline. In order to use this in the form that a PipelineInterface
expects, this needs to be the value to which a key is mapped within a
larger Mapping.
:param pytest._pytest.fixtures.SubRequest request: hook into test case
requesting this fixture, which is queried for a resources value with
which to override the default if it's present.
:param Mapping resources: pipeline interface resource specification
:return Iterable[Mapping]: collection of bundles of pipeline interface
configuration bundles
"""
iface_config_datas = request.getfixturevalue("config_bundles")
if isinstance(iface_config_datas, Mapping):
data_bundles = iface_config_datas.values()
elif isinstance(iface_config_datas, Iterable):
data_bundles = iface_config_datas
else:
raise TypeError("Expected mapping or list collection of "
"PipelineInterface data: {} ({})".format(
iface_config_datas, type(iface_config_datas)))
resource_specification = request.getfixturevalue("resources") \
if "resources" in request.fixturenames else resources
for config_bundle in data_bundles:
config_bundle.update(resource_specification)
return iface_config_datas
def test_direct_subclassing(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C(B):
pass
self.assertTrue(issubclass(C, B))
self.assertFalse(issubclass(int, C))
def test_registration(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C:
__hash__ = None # Make sure it isn't hashable by default
self.assertFalse(issubclass(C, B), B.__name__)
B.register(C)
self.assertTrue(issubclass(C, B))
def get_serializable_data(self, request=None):
if isinstance(self.data, abc.Iterable):
ret = []
data = self.data
if request is not None:
per_page, page_number = self.get_pagination_values(request)
paginator = Paginator(data, per_page)
self._current_page = data = paginator.page(page_number)
# Obtain pagination meta-data
paginator = dict(paginator=dict(
count=paginator.count,
num_pages=paginator.num_pages
))
self.meta.update(paginator)
for x in data:
ret.append(x.serializable(
links=self.links,
linkage=self.linkage,
included=self.included,
request=request,
))
return ret
elif isinstance(self.data, Resource):
return self.data.serializable(
links=self.links,
linkage=self.linkage,
included=self.included,
request=request,
)
else:
return self.data
def difference(self, *others):
r"""Return a new multiset with all elements from the others removed.
>>> ms = Multiset('aab')
>>> sorted(ms.difference('bc'))
['a', 'a']
You can also use the ``-`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabbbc')
>>> sorted(ms - Multiset('abd'))
['a', 'b', 'b', 'c']
For a variant of the operation which modifies the multiset in place see
:meth:`difference_update`.
Args:
others: The other sets to remove from the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The resulting difference multiset.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_multiset, others):
for element, multiplicity in other.items():
if element in _elements:
old_multiplicity = _elements[element]
new_multiplicity = old_multiplicity - multiplicity
if new_multiplicity > 0:
_elements[element] = new_multiplicity
_total -= multiplicity
else:
del _elements[element]
_total -= old_multiplicity
result._total = _total
return result
def union(self, *others):
r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities.
>>> ms = Multiset('aab')
>>> sorted(ms.union('bc'))
['a', 'a', 'b', 'c']
You can also use the ``|`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms | Multiset('aaa'))
['a', 'a', 'a', 'b']
For a variant of the operation which modifies the multiset in place see
:meth:`union_update`.
Args:
*others: The other sets to union the multiset with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the union.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
if multiplicity > old_multiplicity:
_elements[element] = multiplicity
_total += multiplicity - old_multiplicity
result._total = _total
return result
def combine(self, *others):
r"""Return a new multiset with all elements from the multiset and the others with their multiplicities summed up.
>>> ms = Multiset('aab')
>>> sorted(ms.combine('bc'))
['a', 'a', 'b', 'b', 'c']
You can also use the ``+`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms + Multiset('a'))
['a', 'a', 'a', 'b']
For a variant of the operation which modifies the multiset in place see
:meth:`update`.
Args:
others: The other sets to add to the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the addition of the sets.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
new_multiplicity = old_multiplicity + multiplicity
if old_multiplicity > 0 and new_multiplicity <= 0:
del _elements[element]
_total -= old_multiplicity
elif new_multiplicity > 0:
_elements[element] = new_multiplicity
_total += multiplicity
result._total = _total
return result
def intersection(self, *others):
r"""Return a new multiset with elements common to the multiset and all others.
>>> ms = Multiset('aab')
>>> sorted(ms.intersection('abc'))
['a', 'b']
You can also use the ``&`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms & Multiset('aaac'))
['a', 'a']
For a variant of the operation which modifies the multiset in place see
:meth:`intersection_update`.
Args:
others: The other sets intersect with the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the intersection of the sets.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in list(_elements.items()):
new_multiplicity = other.get(element, 0)
if new_multiplicity < multiplicity:
if new_multiplicity > 0:
_elements[element] = new_multiplicity
_total -= multiplicity - new_multiplicity
else:
del _elements[element]
_total -= multiplicity
result._total = _total
return result
def _as_multiset(cls, other):
if isinstance(other, BaseMultiset):
return other
if isinstance(other, _all_basic_types):
pass
elif not isinstance(other, Iterable):
raise TypeError("'%s' object is not iterable" % type(other)) # pragma: no cover
return cls(other)
def update(self, *others):
r"""Like :meth:`dict.update` but add multiplicities instead of replacing them.
>>> ms = Multiset('aab')
>>> ms.update('abc')
>>> sorted(ms)
['a', 'a', 'a', 'b', 'b', 'c']
Note that the operator ``+=`` is equivalent to :meth:`update`, except that the operator will only
accept sets to avoid accidental errors.
>>> ms += Multiset('bc')
>>> sorted(ms)
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`combine`.
Args:
others: The other sets to add to this multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
_elements = self._elements
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
self[element] += multiplicity
def union_update(self, *others):
r"""Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> ms |= Multiset('bccd')
>>> sorted(ms)
['a', 'a', 'b', 'c', 'c', 'd']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`union`.
Args:
others: The other sets to union this multiset with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
_elements = self._elements
_total = self._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
if multiplicity > old_multiplicity:
_elements[element] = multiplicity
_total += multiplicity - old_multiplicity
self._total = _total
def intersection_update(self, *others):
r"""Update the multiset, keeping only elements found in it and all others.
>>> ms = Multiset('aab')
>>> ms.intersection_update('bc')
>>> sorted(ms)
['b']
You can also use the ``&=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabc')
>>> ms &= Multiset('abbd')
>>> sorted(ms)
['a', 'b']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`intersection`.
Args:
others: The other sets to intersect this multiset with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
for other in map(self._as_mapping, others):
for element, current_count in list(self.items()):
multiplicity = other.get(element, 0)
if multiplicity < current_count:
self[element] = multiplicity
def symmetric_difference_update(self, other):
r"""Update the multiset to contain only elements in either this multiset or the other but not both.
>>> ms = Multiset('aab')
>>> ms.symmetric_difference_update('abc')
>>> sorted(ms)
['a', 'c']
You can also use the ``^=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabbbc')
>>> ms ^= Multiset('abd')
>>> sorted(ms)
['a', 'b', 'b', 'c', 'd']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`symmetric_difference`.
Args:
other: The other set to take the symmetric difference with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
other = self._as_multiset(other)
elements = set(self.distinct_elements()) | set(other.distinct_elements())
for element in elements:
multiplicity = self[element]
other_count = other[element]
self[element] = (multiplicity - other_count if multiplicity > other_count else other_count - multiplicity)
def test_direct_subclassing(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C(B):
pass
self.assertTrue(issubclass(C, B))
self.assertFalse(issubclass(int, C))
def test_registration(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C:
__hash__ = None # Make sure it isn't hashable by default
self.assertFalse(issubclass(C, B), B.__name__)
B.register(C)
self.assertTrue(issubclass(C, B))
def to_dict(obj):
"""Helper to flatten models into dicts for rendering.
The following conversions are applied:
* datetime.date, datetime.datetime, datetime.time
are converted into ISO8601 UTC strings
"""
# Shortcut strings so they don't count as Iterables
if isinstance(obj, six.string_types):
return obj
elif obj is NONE_SENTINEL:
return None
elif isinstance(obj, (datetime.datetime, datetime.time)):
# always use UTC
if not obj.tzinfo:
obj = pytz.utc.localize(obj)
if isinstance(obj, datetime.datetime):
# only datetime.datetime takes a separator
return obj.isoformat(sep="T")
return obj.isoformat()
elif isinstance(obj, datetime.date):
# datetime.date doesn't have a timezone
return obj.isoformat()
elif isinstance(obj, abc.Mapping):
return {k: to_dict(v) for k, v in six.iteritems(obj)}
elif isinstance(obj, abc.Iterable):
return [to_dict(v) for v in obj]
# Not a string, datetime, dict, list, or model - return directly
elif not hasattr(obj, "swagger_types"):
return obj
# Collect attrs from obj according to swagger_types into a dict
as_dict = {}
for key in six.iterkeys(obj.swagger_types):
value = getattr(obj, key, missing_attr)
if value is not missing_attr:
as_dict[key] = to_dict(value)
return as_dict