Python collections.Container() Examples

The following are 30 code examples for showing how to use collections.Container(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module collections , or try the search function .

Example 1
Project: endpoints-python   Author: cloudendpoints   File: users_id_token.py    License: Apache License 2.0 6 votes vote down vote up
def _listlike_guard(obj, name, iterable_only=False, log_warning=True):
  """
  We frequently require passed objects to support iteration or
  containment expressions, but not be strings. (Of course, strings
  support iteration and containment, but not usefully.)  If the passed
  object is a string, we'll wrap it in a tuple and return it. If it's
  already an iterable, we'll return it as-is. Otherwise, we'll raise a
  TypeError.
  """
  required_type = (_Iterable,) if iterable_only else (_Container, _Iterable)
  required_type_name = ' or '.join(t.__name__ for t in required_type)

  if not isinstance(obj, required_type):
    raise ValueError('{} must be of type {}'.format(name, required_type_name))
  # at this point it is definitely the right type, but might be a string
  if isinstance(obj, basestring):
    if log_warning:
      _logger.warning('{} passed as a string; should be list-like'.format(name))
    return (obj,)
  return obj 
Example 2
Project: buzzard   Author: airware   File: _a_source_vector.py    License: Apache License 2.0 6 votes vote down vote up
def _normalize_mask_parameter(mask):
        if isinstance(mask, sg.base.BaseGeometry):
            return mask, None
        elif isinstance(mask, Footprint):
            return mask.poly, None
        elif isinstance(mask, collections.Container):
            mask = [float(v) for v in mask]
            minx, maxx, miny, maxy = mask
            mask = minx, miny, maxx, maxy
            return None, mask
        elif mask is None:
            return None, None
        else: # pragma: no cover
            raise TypeError('`mask` should be a Footprint, an extent or a shapely object')

    # Deprecation 
Example 3
Project: ironpython2   Author: IronLanguages   File: test_collections.py    License: 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 = [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
Project: ironpython2   Author: IronLanguages   File: test_dictviews.py    License: Apache License 2.0 6 votes vote down vote up
def test_abc_registry(self):
        d = dict(a=1)

        self.assertIsInstance(d.viewkeys(), collections.KeysView)
        self.assertIsInstance(d.viewkeys(), collections.MappingView)
        self.assertIsInstance(d.viewkeys(), collections.Set)
        self.assertIsInstance(d.viewkeys(), collections.Sized)
        self.assertIsInstance(d.viewkeys(), collections.Iterable)
        self.assertIsInstance(d.viewkeys(), collections.Container)

        self.assertIsInstance(d.viewvalues(), collections.ValuesView)
        self.assertIsInstance(d.viewvalues(), collections.MappingView)
        self.assertIsInstance(d.viewvalues(), collections.Sized)

        self.assertIsInstance(d.viewitems(), collections.ItemsView)
        self.assertIsInstance(d.viewitems(), collections.MappingView)
        self.assertIsInstance(d.viewitems(), collections.Set)
        self.assertIsInstance(d.viewitems(), collections.Sized)
        self.assertIsInstance(d.viewitems(), collections.Iterable)
        self.assertIsInstance(d.viewitems(), collections.Container) 
Example 5
Project: BinderFilter   Author: dxwu   File: test_collections.py    License: MIT License 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 = [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 6
Project: oss-ftp   Author: aliyun   File: test_collections.py    License: MIT License 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 = [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 7
Project: FATE   Author: FederatedAI   File: sample_param.py    License: Apache License 2.0 6 votes vote down vote up
def check(self):
        descr = "sample param"
        self.mode = self.check_and_change_lower(self.mode,
                                                ["random", "stratified"],
                                                descr)

        self.method = self.check_and_change_lower(self.method,
                                                  ["upsample", "downsample"],
                                                  descr)

        if self.mode == "stratified" and self.fractions is not None:
            if not isinstance(self.fractions, list):
                raise ValueError("fractions of sample param when using stratified should be list")
            for ele in self.fractions:
                if not isinstance(ele, collections.Container) or len(ele) != 2:
                    raise ValueError(
                        "element in fractions of sample param using stratified should be a pair like [label_i, rate_i]")

        return True 
Example 8
Project: gcblue   Author: gcblue   File: test_collections.py    License: BSD 3-Clause "New" or "Revised" License 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 = [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 9
Project: CTFCrackTools-V2   Author: Acmesec   File: test_collections.py    License: 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 = [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 10
Project: CTFCrackTools   Author: Acmesec   File: test_collections.py    License: 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 = [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 11
Project: pytorch-UNet   Author: cosmic-cortex   File: kaggle_dsb18_preprocessing.py    License: MIT License 5 votes vote down vote up
def chk_mkdir(*paths: Container) -> None:
    """
    Creates folders if they do not exist.

    Args:
        paths: Container of paths to be created.
    """
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path) 
Example 12
Project: buzzard   Author: airware   File: test_vectorsource_getsetdata_general.py    License: Apache License 2.0 5 votes vote down vote up
def _any_geom_to_shapely(geom):
    """Any geom to shapely object. Points should have homogeneous dimensions size."""
    if isinstance(geom, (sg.LineString, sg.Point, sg.Polygon, sg.MultiPolygon)):
        return geom
    if isinstance(geom, dict):
        return sg.shape(geom['geometry'])
    if isinstance(geom, collections.Container):
        geom = np.asarray(geom)
        if geom.ndim == 1:
            return sg.Point(geom.tolist())
        elif geom.ndim == 2:
            return sg.LineString(geom.tolist())
        elif geom.ndim == 3:
            return sg.Polygon(*geom.tolist())
        elif geom.ndim == 4:
            return sg.MultiPolygon([
                sg.Polygon(*poly)
                for poly in geom.tolist()
            ])
    assert False 
Example 13
Project: pledgeservice   Author: MayOneUS   File: validator.py    License: Apache License 2.0 5 votes vote down vote up
def validate_enum(self, x, fieldname, schema, options=None):
        '''
        Validates that the value of the field is equal to one of the
        specified option values
        '''
        value = x.get(fieldname)
        if value is not None:
            if not isinstance(options, Container):
                raise SchemaError("Enumeration %r for field '%s' must be a "
                                  "container", (options, fieldname))
            if value not in options:
                self._error("Value %(value)r for field '%(fieldname)s' is not "
                            "in the enumeration: %(options)r",
                            value, fieldname, options=options) 
Example 14
Project: lambda-packs   Author: ryfeus   File: _typecheck.py    License: MIT License 5 votes vote down vote up
def __instancecheck__(self, instance):
    return (isinstance(instance, collections.Iterable)
            and isinstance(instance, collections.Sized)
            and isinstance(instance, collections.Container)
            and all(isinstance(x, self._type) for x in instance)) 
Example 15
Project: ironpython2   Author: IronLanguages   File: test_collections.py    License: 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 16
Project: ironpython2   Author: IronLanguages   File: test_collections.py    License: 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:
                __metaclass__ = type
                __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 17
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: _typecheck.py    License: MIT License 5 votes vote down vote up
def __instancecheck__(self, instance):
    return (isinstance(instance, collections.Iterable)
            and isinstance(instance, collections.Sized)
            and isinstance(instance, collections.Container)
            and all(isinstance(x, self._type) for x in instance)) 
Example 18
Project: finam-export   Author: ffeast   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def is_container(val):
    return isinstance(val, collections.Container)\
             and not isinstance(val, six.string_types) \
             and not isinstance(val, bytes) 
Example 19
Project: zxbasic   Author: boriel   File: tree.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __add__(self, other):
            if not isinstance(other, Tree.ChildrenList):
                assert isinstance(other, collections.Container)

            result = Tree.ChildrenList(self.parent)
            for x in self:
                result.append(x)
            for x in other:
                result.append(x)
            return result 
Example 20
Project: BinderFilter   Author: dxwu   File: test_collections.py    License: MIT License 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 21
Project: BinderFilter   Author: dxwu   File: test_collections.py    License: MIT License 5 votes vote down vote up
def test_registration(self):
        for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
            class C:
                __metaclass__ = type
                __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 22
Project: oss-ftp   Author: aliyun   File: test_collections.py    License: MIT License 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 23
Project: oss-ftp   Author: aliyun   File: test_collections.py    License: MIT License 5 votes vote down vote up
def test_registration(self):
        for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
            class C:
                __metaclass__ = type
                __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 24
Project: torba   Author: lbryio   File: util.py    License: MIT License 5 votes vote down vote up
def deep_getsizeof(obj):
    """Find the memory footprint of a Python object.

    Based on code from code.tutsplus.com: http://goo.gl/fZ0DXK

    This is a recursive function that drills down a Python object graph
    like a dictionary holding nested dictionaries with lists of lists
    and tuples and sets.

    The sys.getsizeof function does a shallow size of only. It counts each
    object inside a container as pointer only regardless of how big it
    really is.
    """

    ids = set()

    def size(o):
        if id(o) in ids:
            return 0

        r = sys.getsizeof(o)
        ids.add(id(o))

        if isinstance(o, (str, bytes, bytearray, array.array)):
            return r

        if isinstance(o, Mapping):
            return r + sum(size(k) + size(v) for k, v in o.items())

        if isinstance(o, Container):
            return r + sum(size(x) for x in o)

        return r

    return size(obj) 
Example 25
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: test_list.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_multiple_inheritance(self):
        """
        Issue #96 (for newdict instead of newobject)
        """
        import collections

        class Base(list):
            pass

        class Foo(Base, collections.Container):
            def __contains__(self, item):
                return False 
Example 26
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: test_bytes.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_multiple_inheritance(self):
        """
        Issue #96 (for newbytes instead of newobject)
        """
        import collections

        class Base(bytes):
            pass

        class Foo(Base, collections.Container):
            def __contains__(self, item):
                return False 
Example 27
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: test_object.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_multiple_inheritance(self):
        """
        Issue #96
        """
        import collections

        class Base(object):
            pass

        class Foo(Base, collections.Container):
            def __contains__(self, item):
                return False 
Example 28
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: test_dict.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_multiple_inheritance(self):
        """
        Issue #96 (for newdict instead of newobject)
        """
        import collections

        class Base(dict):
            pass

        class Foo(Base, collections.Container):
            def __contains__(self, item):
                return False 
Example 29
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: test_int.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_multiple_inheritance(self):
        """
        Issue #96 (for newint instead of newobject)
        """
        import collections

        class Base(int):
            pass

        class Foo(Base, collections.Container):
            def __add__(self, other):
                return 0 
Example 30
Project: python-mbedtls   Author: Synss   File: test_md.py    License: 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
    )