Python collections.abc.Container() Examples

The following are 19 code examples of collections.abc.Container(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections.abc , or try the search function .
Example #1
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_Container(self):
        non_samples = [None, 42, 3.14, 1j,
                       (lambda: (yield))(),
                       (x for x in []),
                       ]
        for x in non_samples:
            self.assertNotIsInstance(x, Container)
            self.assertFalse(issubclass(type(x), Container), repr(type(x)))
        samples = [bytes(), str(),
                   tuple(), list(), set(), frozenset(), dict(),
                   dict().keys(), dict().items(),
                   ]
        for x in samples:
            self.assertIsInstance(x, Container)
            self.assertTrue(issubclass(type(x), Container), repr(type(x)))
        self.validate_abstract_methods(Container, '__contains__')
        self.validate_isinstance(Container, '__contains__') 
Example #2
Source File: test_collections.py    From android_universal with MIT License 6 votes vote down vote up
def test_Container(self):
        non_samples = [None, 42, 3.14, 1j,
                       _test_gen(),
                       (x for x in []),
                       ]
        for x in non_samples:
            self.assertNotIsInstance(x, Container)
            self.assertFalse(issubclass(type(x), Container), repr(type(x)))
        samples = [bytes(), str(),
                   tuple(), list(), set(), frozenset(), dict(),
                   dict().keys(), dict().items(),
                   ]
        for x in samples:
            self.assertIsInstance(x, Container)
            self.assertTrue(issubclass(type(x), Container), repr(type(x)))
        self.validate_abstract_methods(Container, '__contains__')
        self.validate_isinstance(Container, '__contains__') 
Example #3
Source File: test_collections.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_Container(self):
        non_samples = [None, 42, 3.14, 1j,
                       (lambda: (yield))(),
                       (x for x in []),
                       ]
        for x in non_samples:
            self.assertNotIsInstance(x, Container)
            self.assertFalse(issubclass(type(x), Container), repr(type(x)))
        samples = [bytes(), str(),
                   tuple(), list(), set(), frozenset(), dict(),
                   dict().keys(), dict().items(),
                   ]
        for x in samples:
            self.assertIsInstance(x, Container)
            self.assertTrue(issubclass(type(x), Container), repr(type(x)))
        self.validate_abstract_methods(Container, '__contains__')
        self.validate_isinstance(Container, '__contains__') 
Example #4
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_Container(self):
        non_samples = [None, 42, 3.14, 1j,
                       (lambda: (yield))(),
                       (x for x in []),
                       ]
        for x in non_samples:
            self.assertNotIsInstance(x, Container)
            self.assertFalse(issubclass(type(x), Container), repr(type(x)))
        samples = [bytes(), str(),
                   tuple(), list(), set(), frozenset(), dict(),
                   dict().keys(), dict().items(),
                   ]
        for x in samples:
            self.assertIsInstance(x, Container)
            self.assertTrue(issubclass(type(x), Container), repr(type(x)))
        self.validate_abstract_methods(Container, '__contains__')
        self.validate_isinstance(Container, '__contains__') 
Example #5
Source File: test_collections.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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)) 
Example #6
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
def test_issue26915(self):
        # Container membership test should check identity first
        class CustomEqualObject:
            def __eq__(self, other):
                return False
        class CustomSequence(Sequence):
            def __init__(self, seq):
                self._seq = seq
            def __getitem__(self, index):
                return self._seq[index]
            def __len__(self):
                return len(self._seq)

        nan = float('nan')
        obj = CustomEqualObject()
        seq = CustomSequence([nan, obj, nan])
        containers = [
            seq,
            ItemsView({1: nan, 2: obj}),
            ValuesView({1: nan, 2: obj})
        ]
        for container in containers:
            for elem in container:
                self.assertIn(elem, container)
        self.assertEqual(seq.index(nan), 0)
        self.assertEqual(seq.index(obj), 1)
        self.assertEqual(seq.count(nan), 2)
        self.assertEqual(seq.count(obj), 1) 
Example #7
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
def test_registration(self):
        for B in Hashable, Iterable, Iterator, Reversible, 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)) 
Example #8
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
def test_direct_subclassing(self):
        for B in Hashable, Iterable, Iterator, Reversible, Sized, Container, Callable:
            class C(B):
                pass
            self.assertTrue(issubclass(C, B))
            self.assertFalse(issubclass(int, C)) 
Example #9
Source File: values.py    From py-good with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, container):
        assert isinstance(container, abc.Container), '`container` must support `in` operation'
        self.container = container

        # Name
        if isinstance(self.container, Map):
            self.name = self.container.name  # Inherit name
        else:
            # Format
            if isinstance(self.container, abc.Iterable):
                cs = _(u',').join(map(get_literal_name, self.container))
            else:
                cs = get_primitive_name(self.container)
            self.name = _(u'In({container})').format(container=cs) 
Example #10
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #11
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #12
Source File: utils.py    From aiohttp-remotes with MIT License 5 votes vote down vote up
def parse_trusted_list(lst):
    if isinstance(lst, str) or not isinstance(lst, Sequence):
        raise TypeError(MSG)
    out = []
    has_ellipsis = False
    for elem in lst:
        if elem is ...:
            has_ellipsis = True
            new_elem = ...
        else:
            if has_ellipsis:
                raise ValueError(
                    "Ellipsis is allowed only at the end of list")
            if isinstance(elem, str) or not isinstance(elem, Container):
                raise TypeError(MSG)
            new_elem = []
            for item in elem:
                if isinstance(item, IP_CLASSES):
                    new_elem.append(item)
                    continue
                try:
                    new_elem.append(ip_address(item))
                except ValueError:
                    try:
                        new_elem.append(ip_network(item))
                    except ValueError:
                        raise ValueError(
                            "{!r} is not IPv4 or IPv6 address or network"
                            .format(item))
        out.append(new_elem)
    return out 
Example #13
Source File: test_collections.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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)) 
Example #14
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #15
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #16
Source File: test_md.py    From python-mbedtls with MIT License 5 votes vote down vote up
def test_algorithms():
    assert isinstance(hashlib.algorithms_guaranteed, Collection)
    assert hashlib.algorithms_guaranteed

    assert isinstance(hashlib.algorithms_available, Collection)
    assert hashlib.algorithms_available

    assert frozenset(hashlib.algorithms_guaranteed).issubset(
        hashlib.algorithms_available
    ) 
Example #17
Source File: scalecomposite.py    From dimod with Apache License 2.0 5 votes vote down vote up
def _check_params(ignored_variables, ignored_interactions):
    """Helper for sample methods"""

    if ignored_variables is None:
        ignored_variables = set()
    elif not isinstance(ignored_variables, abc.Container):
        ignored_variables = set(ignored_variables)

    if ignored_interactions is None:
        ignored_interactions = set()
    elif not isinstance(ignored_interactions, abc.Container):
        ignored_interactions = set(ignored_interactions)

    return ignored_variables, ignored_interactions 
Example #18
Source File: core.py    From django-more with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def apply(self, attrs=None, kattrs=None, merge=False):
        """ Apply new attributes or classes to the target """
        for attr in attrs:
            kattrs = kattrs or {}
            # Treat objects as assigned to their name
            if hasattr(attr, "__name__"):
                kattrs[attr.__name__] = attr
            else:
                kattrs[attr] = inspect.getattr_static(self.source, attr)
        for attr, value in kattrs.items():
            old_value = inspect.getattr_static(self.target, attr, None)
            # If callable, preserve old func
            if callable(value) and callable(old_value):
                # Prevent duplicate patching
                if value in patchy_records:
                    continue
                patchy_records[value] = old_value

            # Merge collections and classes instead of replacing
            if merge:
                if isinstance(old_value, abc.Container):
                    if isinstance(value, abc.Mapping) and isinstance(old_value, abc.MutableMapping):
                        old_value.update(value)
                        logger.info('Merging mapping {mod}.{attr}'.format(mod=self.target.__name__, attr=attr))
                    elif isinstance(value, abc.Sequence) and isinstance(old_value, abc.MutableSequence):
                        old_value.extend(value)
                        logger.info('Merging sequence {mod}.{attr}'.format(mod=self.target.__name__, attr=attr))
                    elif isinstance(value, abc.Set) and isinstance(old_value, abc.MutableSet):
                        old_value.update(value)
                        logger.info('Merging set {mod}.{attr}'.format(mod=self.target.__name__, attr=attr))
                    else:
                        setattr(self.target, attr, value)
                        logger.info("Couldn't merge collection {target}.{attr}, replaced instead".format(
                            target=self.target.__name__,
                            attr=attr))
                    continue
                elif isinstance(old_value, type):
                    logger.info('Merging class for {target}.{attr}'.format(
                        target=self.target.__name__, attr=attr))
                    self.cls(old_value, value).auto()
                    continue
            logger.info('Setting value {target}.{attr}'.format(target=self.target.__name__, attr=attr))
            # Apply patched value
            setattr(self.target, attr, value) 
Example #19
Source File: bqm.py    From dimod with Apache License 2.0 4 votes vote down vote up
def scale(self, scalar, ignored_variables=None, ignored_interactions=None,
              ignore_offset=False):
        """Multiply all the biases by the specified scalar.

        Args:
            scalar (number):
                Value by which to scale the energy range of the binary
                quadratic model.

            ignored_variables (iterable, optional):
                Biases associated with these variables are not scaled.

            ignored_interactions (iterable[tuple], optional):
                As an iterable of 2-tuples. Biases associated with these
                interactions are not scaled.

            ignore_offset (bool, default=False):
                If True, the offset is not scaled.

        """

        if ignored_variables is None:
            ignored_variables = set()
        elif not isinstance(ignored_variables, Container):
            ignored_variables = set(ignored_variables)

        if ignored_interactions is None:
            ignored_interactions = set()
        elif not isinstance(ignored_interactions, Container):
            ignored_interactions = set(ignored_interactions)

        linear = self.linear
        for v in linear:
            if v in ignored_variables:
                continue
            linear[v] *= scalar

        quadratic = self.quadratic
        for u, v in quadratic:
            if (u, v) in ignored_interactions or (v, u) in ignored_interactions:
                continue
            quadratic[(u, v)] *= scalar

        if not ignore_offset:
            self.offset *= scalar