本文整理汇总了Python中collections.abc.Sized方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Sized方法的具体用法?Python abc.Sized怎么用?Python abc.Sized使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Sized方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_collection_sizes
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def get_collection_sizes(obj, collections: Optional[Tuple]=None,
get_only_non_empty=False):
"""
Iterates over `collections` of the gives object and gives its byte size
and number of items in collection
"""
from pympler import asizeof
collections = collections or (list, dict, set, deque, abc.Sized)
if not isinstance(collections, tuple):
collections = tuple(collections)
result = []
for attr_name in dir(obj):
attr = getattr(obj, attr_name)
if isinstance(attr, collections) and (
not get_only_non_empty or len(attr) > 0):
result.append(
(attr_name, len(attr), asizeof.asizeof(attr, detail=1)))
return result
示例2: set_marker
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def set_marker(self, marker):
if (isinstance(marker, np.ndarray) and marker.ndim == 2 and
marker.shape[1] == 2):
self._marker_function = self._set_vertices
elif isinstance(marker, str) and cbook.is_math_text(marker):
self._marker_function = self._set_mathtext_path
elif isinstance(marker, Path):
self._marker_function = self._set_path_marker
elif (isinstance(marker, Sized) and len(marker) in (2, 3) and
marker[1] in (0, 1, 2, 3)):
self._marker_function = self._set_tuple_marker
elif (not isinstance(marker, (np.ndarray, list)) and
marker in self.markers):
self._marker_function = getattr(
self, '_set_' + self.markers[marker])
else:
try:
Path(marker)
self._marker_function = self._set_vertices
except ValueError:
raise ValueError('Unrecognized marker style {!r}'
.format(marker))
self._marker = marker
self._recache()
示例3: test_Sized
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def test_Sized(self):
non_samples = [None, 42, 3.14, 1j,
(lambda: (yield))(),
(x for x in []),
]
for x in non_samples:
self.assertNotIsInstance(x, Sized)
self.assertFalse(issubclass(type(x), Sized), repr(type(x)))
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
]
for x in samples:
self.assertIsInstance(x, Sized)
self.assertTrue(issubclass(type(x), Sized), repr(type(x)))
self.validate_abstract_methods(Sized, '__len__')
self.validate_isinstance(Sized, '__len__')
示例4: test_Sized
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def test_Sized(self):
non_samples = [None, 42, 3.14, 1j,
_test_gen(),
(x for x in []),
]
for x in non_samples:
self.assertNotIsInstance(x, Sized)
self.assertFalse(issubclass(type(x), Sized), repr(type(x)))
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
]
for x in samples:
self.assertIsInstance(x, Sized)
self.assertTrue(issubclass(type(x), Sized), repr(type(x)))
self.validate_abstract_methods(Sized, '__len__')
self.validate_isinstance(Sized, '__len__')
示例5: compute_row_reduction
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def compute_row_reduction(func, value, **kwargs):
final_sizes = {len(x) for x in value if isinstance(x, Sized)}
if not final_sizes:
return func(value)
(final_size,) = final_sizes
raw = func(list(map(promote_to_sequence(final_size), value)), **kwargs)
return pd.Series(raw).squeeze()
示例6: test_parameter_grid
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def test_parameter_grid():
# Test basic properties of ParameterGrid.
params1 = {"foo": [1, 2, 3]}
grid1 = ParameterGrid(params1)
assert isinstance(grid1, Iterable)
assert isinstance(grid1, Sized)
assert_equal(len(grid1), 3)
assert_grid_iter_equals_getitem(grid1)
params2 = {"foo": [4, 2],
"bar": ["ham", "spam", "eggs"]}
grid2 = ParameterGrid(params2)
assert_equal(len(grid2), 6)
# loop to assert we can iterate over the grid multiple times
for i in range(2):
# tuple + chain transforms {"a": 1, "b": 2} to ("a", 1, "b", 2)
points = set(tuple(chain(*(sorted(p.items())))) for p in grid2)
assert_equal(points,
set(("bar", x, "foo", y)
for x, y in product(params2["bar"], params2["foo"])))
assert_grid_iter_equals_getitem(grid2)
# Special case: empty grid (useful to get default estimator settings)
empty = ParameterGrid({})
assert_equal(len(empty), 1)
assert_equal(list(empty), [{}])
assert_grid_iter_equals_getitem(empty)
assert_raises(IndexError, lambda: empty[1])
has_empty = ParameterGrid([{'C': [1, 10]}, {}, {'C': [.5]}])
assert_equal(len(has_empty), 4)
assert_equal(list(has_empty), [{'C': 1}, {'C': 10}, {}, {'C': .5}])
assert_grid_iter_equals_getitem(has_empty)
示例7: track
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def track(
self,
sequence: Union[Iterable[ProgressType], Sequence[ProgressType]],
total: int = None,
task_id: Optional[TaskID] = None,
description="Working...",
) -> Iterable[ProgressType]:
"""[summary]
Args:
sequence (Sequence[ProgressType]): A sequence of values you want to iterate over and track progress.
total: (int, optional): Total number of steps. Default is len(sequence).
task_id: (TaskID): Task to track. Default is new task.
description: (str, optional): Description of task, if new task is created.
Returns:
Iterable[ProgressType]: An iterable of values taken from the provided sequence.
"""
if total is None:
if isinstance(sequence, Sized):
task_total = len(sequence)
else:
raise ValueError(
f"unable to get size of {sequence!r}, please specify 'total'"
)
else:
task_total = total
if task_id is None:
task_id = self.add_task(description, total=task_total)
else:
self.update(task_id, total=task_total)
with self:
for completed, value in enumerate(sequence, 1):
yield value
self.update(task_id, completed=completed)
示例8: from_list
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def from_list(name, colors, N=256, gamma=1.0):
"""
Make a linear segmented colormap with *name* from a sequence
of *colors* which evenly transitions from colors[0] at val=0
to colors[-1] at val=1. *N* is the number of rgb quantization
levels.
Alternatively, a list of (value, color) tuples can be given
to divide the range unevenly.
"""
if not cbook.iterable(colors):
raise ValueError('colors must be iterable')
if (isinstance(colors[0], Sized) and len(colors[0]) == 2
and not isinstance(colors[0], str)):
# List of value, color pairs
vals, colors = zip(*colors)
else:
vals = np.linspace(0, 1, len(colors))
cdict = dict(red=[], green=[], blue=[], alpha=[])
for val, color in zip(vals, colors):
r, g, b, a = to_rgba(color)
cdict['red'].append((val, r, r))
cdict['green'].append((val, g, g))
cdict['blue'].append((val, b, b))
cdict['alpha'].append((val, a, a))
return LinearSegmentedColormap(name, cdict, N, gamma)
示例9: test_direct_subclassing
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [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))
示例10: test_registration
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
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))
示例11: from_list
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def from_list(name, colors, N=256, gamma=1.0):
"""
Make a linear segmented colormap with *name* from a sequence
of *colors* which evenly transitions from colors[0] at val=0
to colors[-1] at val=1. *N* is the number of rgb quantization
levels.
Alternatively, a list of (value, color) tuples can be given
to divide the range unevenly.
"""
if not np.iterable(colors):
raise ValueError('colors must be iterable')
if (isinstance(colors[0], Sized) and len(colors[0]) == 2
and not isinstance(colors[0], str)):
# List of value, color pairs
vals, colors = zip(*colors)
else:
vals = np.linspace(0, 1, len(colors))
cdict = dict(red=[], green=[], blue=[], alpha=[])
for val, color in zip(vals, colors):
r, g, b, a = to_rgba(color)
cdict['red'].append((val, r, r))
cdict['green'].append((val, g, g))
cdict['blue'].append((val, b, b))
cdict['alpha'].append((val, a, a))
return LinearSegmentedColormap(name, cdict, N, gamma)
示例12: _is_list
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def _is_list(obj):
return (
isinstance(obj, Sized) and isinstance(obj, Iterable) and
not isinstance(obj, (str, Set, Mapping))
)
示例13: is_iterable_and_sized
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def is_iterable_and_sized(obj):
return isinstance(obj, Iterable) and isinstance(obj, Sized)
示例14: __call__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
def __call__(self, v):
if not isinstance(v, abc.Sized):
raise Invalid(_(u'Input is not a collection'), u'Collection', get_type_name(type(v)))
length = len(v)
# Validate
if self.min is not None and length < self.min:
raise self.min_error(length)
if self.max is not None and length > self.max:
raise self.max_error(length)
# Ok
return v
示例15: test_direct_subclassing
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sized [as 别名]
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))