Python collections.Container() Examples

The following are 30 code examples of collections.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 , or try the search function .
Example #1
Source File: users_id_token.py    From endpoints-python with 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
Source File: _a_source_vector.py    From buzzard with 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
Source File: sample_param.py    From FATE with 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 #4
Source File: test_collections.py    From ironpython2 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 = [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 CTFCrackTools 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 = [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
Source File: test_dictviews.py    From ironpython2 with 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 #7
Source File: test_collections.py    From gcblue with 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 #8
Source File: test_collections.py    From oss-ftp with 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 #9
Source File: test_collections.py    From BinderFilter with 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 #10
Source File: test_collections.py    From CTFCrackTools-V2 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 = [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
Source File: test_int.py    From kgsgo-dataset-preprocessor with 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 #12
Source File: _typecheck.py    From keras-lambda with 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 #13
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 #14
Source File: util.py    From lbry-sdk with 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 #15
Source File: test_collections.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #16
Source File: test_collections.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #17
Source File: test_collections.py    From CTFCrackTools-V2 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 #18
Source File: test_collections.py    From CTFCrackTools-V2 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:
                __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 #19
Source File: frames.py    From stagger with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _in_version(self, *versions):
        "Returns true if this frame is in any of the specified versions of ID3."
        for version in versions:
            if (self._version == version
                or (isinstance(self._version, collections.Container) 
                    and version in self._version)):
                return True
        return False 
Example #20
Source File: events.py    From picraft with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def matches_pos(self, test, pos):
        if test is None:
            return True
        if isinstance(test, Vector):
            return test == pos.floor()
        if isinstance(test, Container):
            return pos.floor() in test
        raise TypeError(
                "%r is not a valid position test; expected Vector or "
                "sequence of Vector" % test) 
Example #21
Source File: events.py    From picraft with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def matches_pos(self, pos):
        if self.pos is None:
            return True
        if isinstance(self.pos, Vector):
            return self.pos == pos
        if isinstance(self.pos, Container):
            return pos in self.pos
        raise TypeError(
                "%r is not a valid position test; expected Vector or "
                "sequence of Vector" % pos) 
Example #22
Source File: events.py    From picraft with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def matches_face(self, face):
        if self.face is None:
            return True
        if isinstance(self.face, str):
            return self.face == face
        if isinstance(self.face, Container):
            return face in self.face
        raise TypeError(
                "%r is not a valid face test; expected string or sequence "
                "of strings" % face) 
Example #23
Source File: test_collections.py    From CTFCrackTools 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 #24
Source File: test_collections.py    From CTFCrackTools 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:
                __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 #25
Source File: kaggle_dsb18_preprocessing.py    From pytorch-UNet with 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 #26
Source File: test_collections.py    From BinderFilter with 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 #27
Source File: test_vectorsource_getsetdata_general.py    From buzzard with 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 #28
Source File: validator.py    From pledgeservice with 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 #29
Source File: _typecheck.py    From lambda-packs with 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 #30
Source File: test_collections.py    From ironpython2 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))