本文整理汇总了Python中collections.abc.Mapping方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Mapping方法的具体用法?Python abc.Mapping怎么用?Python abc.Mapping使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Mapping方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_test
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def run_test(work_type: FunctionType, job_sets: Sequence, trials: int,
pool_class: type, worker_count: int) -> Mapping:
pool = pool_class(worker_count)
if work_type == 'compute':
test_func = pool.run_compute_test
elif work_type == 'network':
test_func = pool.run_network_test
else:
raise Exception("Invalid work type: {}".format(work_type))
results = map(
lambda jobs: test_func(jobs, trials, show_progress=True),
tqdm(job_sets, desc=pool_class.__name__),
)
summarized_results = list(map(summarize_test, results))
pool.destroy_pool()
return summarized_results
示例2: visit_record
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def visit_record(self, type_):
if not isinstance(self.value, collections_abc.Mapping):
raise _OptionTypeError(self.value, type_)
unknown = set(self.value).difference(type_.__field_types__)
if unknown:
fields = ', '.join(sorted(map(repr, unknown)))
raise _OptionError('unknown fields: {}'.format(fields))
missing = set(type_.__field_types__).difference(self.value)
if missing:
fields = ', '.join(sorted(missing))
raise _OptionError('missing fields: {}'.format(fields))
for key, value_type in type_.__field_types__.items():
with self.push(self.value[key]):
self.visit(value_type)
示例3: extend
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def extend(self, *args, **kwargs):
"""Generic import function for any type of header-like object.
Adapted version of MutableMapping.update in order to insert items
with self.add instead of self.__setitem__
"""
if len(args) > 1:
raise TypeError("extend() takes at most 1 positional "
"arguments ({0} given)".format(len(args)))
other = args[0] if len(args) >= 1 else ()
if isinstance(other, HTTPHeaderDict):
for key, val in other.iteritems():
self.add(key, val)
elif isinstance(other, Mapping):
for key in other:
self.add(key, other[key])
elif hasattr(other, "keys"):
for key in other.keys():
self.add(key, other[key])
else:
for key, value in other:
self.add(key, value)
for key, value in kwargs.items():
self.add(key, value)
示例4: validate_config
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def validate_config(rules_: Mapping = AntiSpamConfig.rules) -> Dict[str, str]:
"""Validates the antispam configs."""
validation_errors = {}
for name, config in rules_.items():
if name not in RULE_FUNCTION_MAPPING:
log.error(
f"Unrecognized antispam rule `{name}`. "
f"Valid rules are: {', '.join(RULE_FUNCTION_MAPPING)}"
)
validation_errors[name] = f"`{name}` is not recognized as an antispam rule."
continue
for required_key in ('interval', 'max'):
if required_key not in config:
log.error(
f"`{required_key}` is required but was not "
f"set in rule `{name}`'s configuration."
)
validation_errors[name] = f"Key `{required_key}` is required but not set for rule `{name}`"
return validation_errors
示例5: _recursive_update
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def _recursive_update(original, new):
"""
Helper method which implements a recursive `dict.update`
method, used for updating the original configuration with
configuration specified by the user.
"""
for key, value in original.items():
if key not in new:
continue
if isinstance(value, Mapping):
if not any(isinstance(subvalue, Mapping) for subvalue in value.values()):
original[key].update(new[key])
_recursive_update(original[key], new[key])
else:
original[key] = new[key]
示例6: run_validators
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def run_validators(validators: Iterable[Validator], value: Any) -> None:
fields_errors = OrderedDict() # type: Dict[str, Any]
non_field_errors = [] # type: List[Any]
for validator in validators:
try:
validator(value)
except ValidationError as exc:
if isinstance(exc.detail, Mapping):
for field_name, field_errors in exc.detail.items():
fields_errors.setdefault(field_name, []).extend(
field_errors)
elif isinstance(exc.detail, list):
non_field_errors.extend(exc.detail)
if fields_errors:
errors = {}
errors.update(fields_errors)
errors.setdefault(
api_settings.NON_FIELD_ERRORS_KEY, []).extend(non_field_errors)
raise ValidationError(errors)
if non_field_errors:
# TODO: Issue #109 - remove type: ignore
raise ValidationError(non_field_errors) # type: ignore
示例7: _checkout
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def _checkout(self, item):
if isinstance(item, container_abcs.Mapping):
flag = True
for key in item.keys():
flag = flag and self._checkout(item[key])
return flag
if isinstance(item, container_abcs.Sequence):
flag = True
for val in item:
flag = flag and self._checkout(val)
return flag
if isinstance(item, (np.ndarray)):
if item.size > 1:
return False
else:
return True
if isinstance(item, (numbers.Number)):
return True
示例8: call_view
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def call_view(self, *args, **kwargs):
config = flask.current_app.config
parser = config.get('APISPEC_WEBARGS_PARSER', flaskparser.parser)
annotation = utils.resolve_annotations(self.func, 'args', self.instance)
if annotation.apply is not False:
for option in annotation.options:
schema = utils.resolve_schema(option['args'], request=flask.request)
parsed = parser.parse(schema, locations=option['kwargs']['locations'])
if getattr(schema, 'many', False):
args += tuple(parsed)
elif isinstance(parsed, Mapping):
kwargs.update(parsed)
else:
args += (parsed,)
return self.func(*args, **kwargs)
示例9: continue_from_headers
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def continue_from_headers(
cls,
headers, # type: typing.Mapping[str, str]
**kwargs # type: Any
):
# type: (...) -> Transaction
if cls is Span:
logger.warning(
"Deprecated: use Transaction.continue_from_headers "
"instead of Span.continue_from_headers."
)
parent = Transaction.from_traceparent(headers.get("sentry-trace"), **kwargs)
if parent is None:
parent = Transaction(**kwargs)
parent.same_process_as_parent = False
return parent
示例10: deepupdate
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def deepupdate(original, update):
"""Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
if not isinstance(original, abc.Mapping):
return update
for key, value in update.items():
if isinstance(value, abc.Mapping):
original[key] = deepupdate(original.get(key, {}), value)
else:
original[key] = value
return original
# XXX: Does this belong here?
示例11: prepare_response
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def prepare_response(response, spec, default_response_content_type):
"""Rework response according to OAS version"""
if isinstance(response, abc.Mapping):
# OAS 2
if spec.openapi_version.major < 3:
if 'example' in response:
response['examples'] = {
default_response_content_type: response.pop('example')
}
# OAS 3
else:
for field in ('schema', 'example', 'examples'):
if field in response:
(
response
.setdefault('content', {})
.setdefault(default_response_content_type, {})
[field]
) = response.pop(field)
示例12: path_helper
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def path_helper(self, rule, operations, parameters, **kwargs):
"""Get path from flask Rule and set path parameters in operations"""
for path_p in self.rule_to_params(rule):
# If a parameter with same name and location is already
# documented, update. Otherwise, append as new parameter.
p_doc = next(
(
p for p in parameters
if (
isinstance(p, Mapping) and
p['in'] == 'path' and
p['name'] == path_p['name']
)
),
None
)
if p_doc is not None:
# If parameter already documented, mutate to update doc
# Ensure manual doc overwrites auto doc
p_doc.update({**path_p, **p_doc})
else:
parameters.append(path_p)
return self.flaskpath2openapi(rule.rule)
示例13: cast_tensor_type
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [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
示例14: _asdict
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def _asdict(self):
d = {}
for k in dir(self):
if k.startswith('_'):
continue
try:
v = getattr(self, k)
except:
continue
if callable(v):
continue
if getattr(v, 'asdict', None):
v = v.asdict()
elif isinstance(v, abc.Mapping):
v = {k2: v2.asdict() if getattr(v2, 'asdict', None) else v2
for k2, v2 in v.items()}
d[k] = v
return d
示例15: to_representation
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Mapping [as 别名]
def to_representation(self, instance):
if isinstance(instance, Mapping):
resource_type = self._get_resource_type_from_mapping(instance)
serializer = self._get_serializer_from_resource_type(resource_type)
else:
resource_type = self.to_resource_type(instance)
serializer = self._get_serializer_from_model_or_instance(instance)
ret = serializer.to_representation(instance)
ret[self.resource_type_field_name] = resource_type
return ret