Python collections.abc 模块,Iterable() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用collections.abc.Iterable()

项目:stig    作者:rndusr    | 项目源码 | 文件源码
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]
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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__')
项目:pswalker    作者:slaclab    | 项目源码 | 文件源码
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)
项目:pswalker    作者:slaclab    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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__')
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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")
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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())
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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__')
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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")
项目:signac-project-template    作者:glotzerlab    | 项目源码 | 文件源码
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
项目:signac-project-template    作者:glotzerlab    | 项目源码 | 文件源码
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
项目:signac-project-template    作者:glotzerlab    | 项目源码 | 文件源码
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
项目:signac-project-template    作者:glotzerlab    | 项目源码 | 文件源码
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
项目:SoS    作者:vatlab    | 项目源码 | 文件源码
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)
项目:phredutils    作者:doctaphred    | 项目源码 | 文件源码
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
项目:phredutils    作者:doctaphred    | 项目源码 | 文件源码
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)))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
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)
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
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)
项目:pymzn    作者:paolodragone    | 项目源码 | 文件源码
def _is_list(obj):
    return (isinstance(obj, Sized) and isinstance(obj, Iterable) and
            not isinstance(obj, (Set, Mapping)))
项目:pymzn    作者:paolodragone    | 项目源码 | 文件源码
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
项目:blstm-cws    作者:chantera    | 项目源码 | 文件源码
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]
项目:python3-utils    作者:soldni    | 项目源码 | 文件源码
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
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def non_string_iterable(v):
    """Return whether the object is any Iterable other than str."""
    return isinstance(v, Iterable) and not isinstance(v, str)
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
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)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def options(self):
        """Iterable of all valid values"""
        return self._options
项目:stig    作者:rndusr    | 项目源码 | 文件源码
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])
项目:stig    作者:rndusr    | 项目源码 | 文件源码
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]
项目:stig    作者:rndusr    | 项目源码 | 文件源码
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))
项目:hexchat-scripts    作者:dewiniaid    | 项目源码 | 文件源码
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
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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))
项目:blender-addons    作者:scorpion81    | 项目源码 | 文件源码
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)
项目:blender-addons    作者:scorpion81    | 项目源码 | 文件源码
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)
项目:pep    作者:pepkit    | 项目源码 | 文件源码
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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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))
项目:pinax-api    作者:pinax    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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)
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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
项目:multiset    作者:wheerd    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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))
项目:oci-python-sdk    作者:oracle    | 项目源码 | 文件源码
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