本文整理汇总了Python中collections.abc.Iterable方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Iterable方法的具体用法?Python abc.Iterable怎么用?Python abc.Iterable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Iterable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_and_cast_args
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def check_and_cast_args(args):
"""Check and cast arguments for the dependency tracer.
Since autograd is expecting to compute derivatives, ints are not
allowable as arguments. However, for our purposes, casting ints
to floats will not affect dependency tracing.
"""
# Currently this function only casts int into floats and raises
# if the element is a string. This can be expanded to be more robust.
def check_and_cast(arg):
"""Attempt to cast the arg to something traceable. Otherwise, error."""
if isinstance(arg, str):
raise ValueError(f"Cannot build causal graph for arg {arg} of type str")
if isinstance(arg, int):
arg = float(arg)
return arg
if isinstance(args, Iterable):
return [check_and_cast(arg) for arg in args]
return check_and_cast(args)
示例2: is_incomplete_argument
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def is_incomplete_argument(current_params, cmd_param):
"""
:param current_params: the current params and values for this argument as already entered
:param cmd_param: the current command parameter
:return: whether or not the last argument is incomplete and corresponds to this cmd_param. In
other words whether or not the this cmd_param argument can still accept values
"""
if not isinstance(cmd_param, Argument):
return False
current_param_values = current_params[cmd_param.name]
if current_param_values is None:
return True
if cmd_param.nargs == -1:
return True
if isinstance(current_param_values, abc.Iterable) \
and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:
return True
return False
示例3: handle_emitter
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def handle_emitter(self):
"""
This emitter uses the user-implemented create_message() method to get
whatever data the robot gathered, convert it to a string if needed and
then use the emitter to send the data in a string utf-8 encoding to the
supervisor.
"""
data = self.create_message()
assert isinstance(data,
Iterable), "The action object should be Iterable"
string_message = ""
# message can either be a list that needs to be converted in a string
# or a straight-up string
if type(data) is list:
string_message = ",".join(map(str, data))
elif type(data) is str:
string_message = data
else:
raise TypeError(
"message must be either a comma-separated string or a 1D list")
string_message = string_message.encode("utf-8")
self.emitter.send(string_message)
示例4: _check_if_func_available
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def _check_if_func_available(func):
to_check = []
if isinstance(func, list):
to_check.extend(func)
elif isinstance(func, dict):
for f in func.values():
if isinstance(f, Iterable) and not isinstance(f, str):
to_check.extend(f)
else:
to_check.append(f)
else:
to_check.append(func)
for f in to_check:
if f not in _available_aggregation_functions:
return False
return True
示例5: __call__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def __call__(self, groupby):
indexed = groupby.op.build_mock_groupby()[self.selection]
if isinstance(indexed, pd_groupby.SeriesGroupBy):
self.output_types = [OutputType.series_groupby]
params = dict(shape=(groupby.shape[0],), name=self.selection,
dtype=groupby.dtypes[self.selection],
index_value=groupby.index_value,
key_dtypes=groupby.key_dtypes)
else:
self.output_types = [OutputType.dataframe_groupby]
if isinstance(self.selection, Iterable) and not isinstance(self.selection, str):
item_list = list(self.selection)
else:
item_list = [self.selection]
params = groupby.params.copy()
params['dtypes'] = new_dtypes = groupby.dtypes[item_list]
params['selection'] = self.selection
params['shape'] = (groupby.shape[0], len(item_list))
params['columns_value'] = parse_index(new_dtypes.index, store_data=True)
return self.new_tileable([groupby], **params)
示例6: df_groupby_getitem
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def df_groupby_getitem(df_groupby, item):
try:
hash(item)
hashable = True
except TypeError:
hashable = False
if hashable and item in df_groupby.dtypes:
output_types = [OutputType.series_groupby]
elif isinstance(item, Iterable) and all(it in df_groupby.dtypes for it in item):
output_types = [OutputType.dataframe_groupby]
else:
raise NameError('Cannot slice groupby with %r' % item)
if df_groupby.selection:
raise IndexError('Column(s) %r already selected' % df_groupby.selection)
op = GroupByIndex(selection=item, output_types=output_types)
return op(df_groupby)
示例7: _is_funcs_agg
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def _is_funcs_agg(func):
to_check = []
if isinstance(func, list):
to_check.extend(func)
elif isinstance(func, dict):
for f in func.values():
if isinstance(f, Iterable) and not isinstance(f, str):
to_check.extend(f)
else:
to_check.append(f)
else:
to_check.append(func)
for f in to_check:
if f not in _builtin_aggregation_functions:
return False
return True
示例8: _get_squeeze_shape
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def _get_squeeze_shape(shape, axis):
if axis is not None:
if isinstance(axis, Iterable):
axis = tuple(axis)
else:
axis = (axis,)
for ax in axis:
if shape[ax] != 1:
raise ValueError('cannot select an axis to squeeze out '
'which has size not equal to one')
shape = tuple(s for i, s in enumerate(shape) if i not in axis)
else:
axis = tuple(i for i, s in enumerate(shape) if s == 1)
shape = tuple(s for s in shape if s != 1)
return shape, axis
示例9: base_equal
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def base_equal(self, ob1, ob2):
if type(ob1) != type(ob2):
return False
def cmp(obj1, obj2):
if isinstance(obj1, np.ndarray):
return np.array_equal(obj1, obj2)
elif isinstance(obj1, Iterable) and \
not isinstance(obj1, str) and \
isinstance(obj2, Iterable) and \
not isinstance(obj2, str):
return all(cmp(it1, it2) for it1, it2 in itertools.zip_longest(obj1, obj2))
elif hasattr(obj1, 'key') and hasattr(obj2, 'key'):
return obj1.key == obj2.key
elif isinstance(obj1, ReferenceType) and isinstance(obj2, ReferenceType):
return cmp(obj1(), obj2())
else:
return obj1 == obj2
for slot in ob1.__slots__:
if not cmp(getattr(ob1, slot, None), getattr(ob2, slot, None)):
return False
return True
示例10: cast_tensor_type
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def cast_tensor_type(inputs, src_type, dst_type):
if isinstance(inputs, torch.Tensor):
return inputs.to(dst_type)
elif isinstance(inputs, str):
return inputs
elif isinstance(inputs, np.ndarray):
return inputs
elif isinstance(inputs, abc.Mapping):
return type(inputs)({
k: cast_tensor_type(v, src_type, dst_type)
for k, v in inputs.items()
})
elif isinstance(inputs, abc.Iterable):
return type(inputs)(
cast_tensor_type(item, src_type, dst_type) for item in inputs)
else:
return inputs
示例11: group_as_dict
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def group_as_dict(pairs):
"""Combines a list of key-value pairs to a dictionary of keys and value lists.
Does not require the pairs to be sorted by keys.
Parameters
----------
pairs : iterable
Iterable of key-value pairs
Returns
-------
dict
The dictionary of keys and value lists.
"""
dic = defaultdict(list)
for key, value in pairs:
dic[key].append(value)
return dic
示例12: files
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def files(self, files):
if not isinstance(files, utils.Iterable):
raise ValueError(f'Not an Iterable: {files}')
for f in files:
if not isinstance(f, utils.File):
raise ValueError(f'Not a File object: {f}')
elif f.is_absolute():
raise error.PathError(f, msg='Not a relative path')
if not files:
self._set_files(files=())
else:
# os.path.commonpath() returns '' if there is no common path and
# raises ValueError if there are absolute and relative paths.
try:
basepath = os.path.commonpath(files)
except ValueError:
basepath = ''
if basepath == '':
raise error.CommonPathError(files)
self._set_files(files, pathlib.Path(basepath))
示例13: filepaths
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def filepaths(self, filepaths):
if not isinstance(filepaths, utils.Iterable):
raise ValueError(f'Not an Iterable: {filepaths}')
filepaths = utils.Filepaths(filepaths) # Resolve directories
if not filepaths:
self._set_files(files=())
else:
# Make all paths absolute so we can find the common path. Do not
# resolve symlinks so the user isn't confronted with unexpected
# paths in case of an error.
cwd = pathlib.Path.cwd()
filepaths_abs = tuple(fp if fp.is_absolute() else cwd / fp
for fp in filepaths)
try:
basepath = pathlib.Path(os.path.commonpath(filepaths_abs))
except ValueError:
raise error.CommonPathError(filepaths)
filepaths = tuple(utils.File(fp, size=utils.real_size(fp))
for fp in filepaths)
self._set_files(filepaths, basepath)
示例14: role
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def role(self):
"""Return Jira role information.
:return: List of current user roles
:rtype: Iterable
"""
# https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#api-rest-api-3-role-get
url = self._options["server"] + "/rest/api/latest/role"
r = self._session.get(url)
return json_loads(r)
# Experimental
# Experimental support for iDalko Grid, expect API to change as it's using private APIs currently
# https://support.idalko.com/browse/IGRID-1017
示例15: iter_cast
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Iterable [as 别名]
def iter_cast(inputs, dst_type, return_type=None):
"""Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted to this type, otherwise an iterator.
Returns:
iterator or specified type: The converted object.
"""
if not isinstance(inputs, collections_abc.Iterable):
raise TypeError('inputs must be an iterable object')
if not isinstance(dst_type, type):
raise TypeError('"dst_type" must be a valid type')
out_iterable = six.moves.map(dst_type, inputs)
if return_type is None:
return out_iterable
else:
return return_type(out_iterable)