python类Container()的实例源码

_typecheck.py 文件源码 项目:DeepLearning_VirtualReality_BigData_Project 作者: rashmitripathi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
op_graph.py 文件源码 项目:ngraph 作者: NervanaSystems 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def __init__(self, returns, *args, **kwargs):
        if isinstance(returns, collections.Container):
            all = type(returns)(as_op(ret) for ret in returns)
        elif isinstance(returns, Op):
            all = [as_op(returns)]
        elif returns is not None:
            raise ValueError()
        else:
            all = []

        self.values = all
        self.returns = returns
        super(ComputationOp, self).__init__(all=all, **kwargs)

        def is_input(arg):
            return arg.tensor.is_input

        placeholders = self.placeholders()
        if len(args) == 1 and args[0] == 'all':
            args = placeholders

        args = tuple(as_op(arg) for arg in args)
        arg_tensors = set(arg.tensor for arg in args)
        missing_tensors = [t for t in placeholders - arg_tensors]

        if len(missing_tensors) > 0:
            raise ValueError(("All used placeholders must be supplied to a "
                              "computation. Currently missed {}."
                              ).format(missing_tensors))

        for arg in args:
            if not (arg.tensor.is_input):
                raise ValueError((
                    'The arguments to a computation must all be Ops with property '
                    'is_input=True, but the op passed had is_input=False.'
                    'In most cases you want to pass placeholder ops in as arguments.  '
                    '{op} was passed in, of type {op_type}.'
                ).format(
                    op=arg,
                    op_type=arg.__class__.__name__,
                ))

        self.parameters = args
        for arg in args:
            self.add_control_dep(arg)
normalize_yaml.py 文件源码 项目:inspire-schemas 作者: inspirehep 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def process_tree(value, key=None, parent_key=None):
    def _process_leaf(value, key=None, parent_key=None):
        if key == 'description' and parent_key != 'properties':
            return DescriptionContent(value.strip())

        return value

    def _enforce_strict_types(dictionary):
        if dictionary.get('type') == 'object':
            dictionary.setdefault('additionalProperties', False)
        elif dictionary.get('type') == 'string':
            dictionary.setdefault('minLength', 1)
        elif dictionary.get('type') == 'array':
            dictionary.setdefault('uniqueItems', True)
            dictionary.setdefault('minItems', 1)

        return dictionary

    def _ensure_values_have_types(properties, parent_key):
        for key, val in properties.iteritems():
            if not val.get('type') and not val.get('$ref'):
                warnings.warn(
                    u'"{}" field of "{}" does not have a type'.format(
                        key, parent_key
                    )
                )

    def _is_leaf(value):
        return (not isinstance(value, collections.Container)
                or isinstance(value, basestring))

    if _is_leaf(value):
        return _process_leaf(value, key, parent_key)

    elif isinstance(value, list):
        return [process_tree(v) for v in value]

    elif isinstance(value, dict):
        value = _enforce_strict_types(value)
        if key == 'properties':
            _ensure_values_have_types(value, parent_key)
        return {k: process_tree(v, k, key) for k, v in value.iteritems()}

    else:
        raise TypeError(u"'{}' has unexpected type: {}".format(
            value, type(value).__name__))
__init__.py 文件源码 项目:ansible-provider-docs 作者: alibaba 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def hash_params(params):
    """
    Construct a data structure of parameters that is hashable.

    This requires changing any mutable data structures into immutable ones.
    We chose a frozenset because role parameters have to be unique.

    .. warning::  this does not handle unhashable scalars.  Two things
        mitigate that limitation:

        1) There shouldn't be any unhashable scalars specified in the yaml
        2) Our only choice would be to return an error anyway.
    """
    # Any container is unhashable if it contains unhashable items (for
    # instance, tuple() is a Hashable subclass but if it contains a dict, it
    # cannot be hashed)
    if isinstance(params, collections.Container) and not isinstance(params, (text_type, binary_type)):
        if isinstance(params, collections.Mapping):
            try:
                # Optimistically hope the contents are all hashable
                new_params = frozenset(params.items())
            except TypeError:
                new_params = set()
                for k, v in params.items():
                    # Hash each entry individually
                    new_params.update((k, hash_params(v)))
                new_params = frozenset(new_params)

        elif isinstance(params, (collections.Set, collections.Sequence)):
            try:
                # Optimistically hope the contents are all hashable
                new_params = frozenset(params)
            except TypeError:
                new_params = set()
                for v in params:
                    # Hash each entry individually
                    new_params.update(hash_params(v))
                new_params = frozenset(new_params)
        else:
            # This is just a guess.
            new_params = frozenset(params)
        return new_params

    # Note: We do not handle unhashable scalars but our only choice would be
    # to raise an error there anyway.
    return frozenset((params,))


问题


面经


文章

微信
公众号

扫码关注公众号