當前位置: 首頁>>代碼示例>>Python>>正文


Python abc.Mapping方法代碼示例

本文整理匯總了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 
開發者ID:JohnStarich,項目名稱:python-pool-performance,代碼行數:18,代碼來源:pools.py

示例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) 
開發者ID:vmagamedov,項目名稱:hiku,代碼行數:19,代碼來源:query.py

示例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) 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:27,代碼來源:_collections.py

示例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 
開發者ID:python-discord,項目名稱:bot,代碼行數:21,代碼來源:antispam.py

示例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] 
開發者ID:python-discord,項目名稱:bot,代碼行數:19,代碼來源:constants.py

示例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 
開發者ID:apragacz,項目名稱:django-rest-registration,代碼行數:25,代碼來源:validation.py

示例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 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:22,代碼來源:text_logger.py

示例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) 
開發者ID:jmcarp,項目名稱:flask-apispec,代碼行數:18,代碼來源:wrapper.py

示例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 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:18,代碼來源:tracing.py

示例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? 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:18,代碼來源:utils.py

示例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) 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:21,代碼來源:utils.py

示例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) 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:27,代碼來源:plugins.py

示例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 
開發者ID:xvjiarui,項目名稱:GCNet,代碼行數:19,代碼來源:utils.py

示例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 
開發者ID:CiscoTestAutomation,項目名稱:genielibs,代碼行數:20,代碼來源:stream.py

示例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 
開發者ID:apirobot,項目名稱:django-rest-polymorphic,代碼行數:13,代碼來源:serializers.py


注:本文中的collections.abc.Mapping方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。