本文整理汇总了Python中collections.Container方法的典型用法代码示例。如果您正苦于以下问题:Python collections.Container方法的具体用法?Python collections.Container怎么用?Python collections.Container使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections
的用法示例。
在下文中一共展示了collections.Container方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _listlike_guard
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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
示例2: _normalize_mask_parameter
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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
示例3: _any_geom_to_shapely
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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
示例4: test_Container
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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__')
示例5: test_abc_registry
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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)
示例6: check
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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
示例7: chk_mkdir
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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)
示例8: validate_enum
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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)
示例9: __instancecheck__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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))
示例10: test_direct_subclassing
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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))
示例11: test_registration
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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))
示例12: is_container
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
def is_container(val):
return isinstance(val, collections.Container)\
and not isinstance(val, six.string_types) \
and not isinstance(val, bytes)
示例13: __add__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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
示例14: deep_getsizeof
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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)
示例15: test_multiple_inheritance
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Container [as 别名]
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