当前位置: 首页>>代码示例>>Python>>正文


Python abc.Hashable方法代码示例

本文整理汇总了Python中collections.abc.Hashable方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Hashable方法的具体用法?Python abc.Hashable怎么用?Python abc.Hashable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在collections.abc的用法示例。


在下文中一共展示了abc.Hashable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __contains__

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def __contains__(self, key):  # pylint:disable=too-many-return-statements
        "In a winding way, figures out if a key is in the KeyDict"
        try:
            key, idx = self.parse_and_index(key)
        except KeyError:
            return False
        except ValueError:  # multiple keys correspond
            return True
        if not isinstance(key, Hashable):
            return False
        if super().__contains__(key):  # pylint: disable=no-member
            if idx:
                try:
                    value = super().__getitem__(key)[idx]  # pylint: disable=no-member
                    return True if is_sweepvar(value) else not isnan(value)
                except TypeError:
                    raise TypeError("%s has an idx, but its value in this"
                                    " KeyDict is the scalar %s."
                                    % (key, super().__getitem__(key)))  # pylint: disable=no-member
                except IndexError:
                    raise IndexError("key %s with idx %s is out of bounds"
                                     " for value %s" %
                                     (key, idx, super().__getitem__(key)))  # pylint: disable=no-member
            return True
        return key in self.keymap 
开发者ID:convexengineering,项目名称:gpkit,代码行数:27,代码来源:keydict.py

示例2: test_Hashable

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def test_Hashable(self):
        # Check some non-hashables
        non_samples = [bytearray(), list(), set(), dict()]
        for x in non_samples:
            self.assertNotIsInstance(x, Hashable)
            self.assertFalse(issubclass(type(x), Hashable), repr(type(x)))
        # Check some hashables
        samples = [None,
                   int(), float(), complex(),
                   str(),
                   tuple(), frozenset(),
                   int, list, object, type, bytes()
                   ]
        for x in samples:
            self.assertIsInstance(x, Hashable)
            self.assertTrue(issubclass(type(x), Hashable), repr(type(x)))
        self.assertRaises(TypeError, Hashable)
        # Check direct subclassing
        class H(Hashable):
            def __hash__(self):
                return super().__hash__()
        self.assertEqual(hash(H()), 0)
        self.assertFalse(issubclass(int, H))
        self.validate_abstract_methods(Hashable, '__hash__')
        self.validate_isinstance(Hashable, '__hash__') 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:27,代码来源:test_collections.py

示例3: __call__

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def __call__(self, *args, **kw):
        if not isinstance(args, Hashable):
            # Uncacheable, a list, for instance.
            # Better to not cache than blow up.
            return self.func(*args)
        obj = args[0]
        try:
            cache = obj.__cache_meth
        except AttributeError:
            cache = obj.__cache_meth = {}
        key = (self.func, args[1:], frozenset(kw.items()))
        try:
            res = cache[key]
        except KeyError:
            res = cache[key] = self.func(*args, **kw)
        return res 
开发者ID:devitocodes,项目名称:devito,代码行数:18,代码来源:memoization.py

示例4: _validate_excludes

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def _validate_excludes(self, excluded_fields, field, value):
        """Ignore 'None' for excluded fields.

        Hopefully Cerberus allows this at some point in the future, then
        we can remove this.

        The rule's arguments are validated against this schema:
        {'type': ('hashable', 'list'),
         'schema': {'type': 'hashable'}}
        """
        if isinstance(excluded_fields, Hashable):
            excluded_fields = [excluded_fields]

        # Remove None fields and unrequire them
        not_none = []
        for excluded in excluded_fields:
            if self.document.get(excluded) is None:
                self._unrequired_by_excludes.add(excluded)
            else:
                not_none.append(excluded)

        return super()._validate_excludes(not_none, field, value) 
开发者ID:amiv-eth,项目名称:amivapi,代码行数:24,代码来源:validation.py

示例5: construct_mapping

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def construct_mapping(self, node, deep=False):
        if isinstance(node, MappingNode):
            self.flatten_mapping(node)
        if not isinstance(node, MappingNode):
            raise ConstructorError(None, None,
                                   "expected a mapping node, but found %s" % node.id,
                                   node.start_mark)
        mapping = OrderedDict()
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            if not isinstance(key, Hashable):
                raise ConstructorError("while constructing a mapping", node.start_mark,
                                       "found unhashable key", key_node.start_mark)
            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value
        return mapping 
开发者ID:ARM-software,项目名称:workload-automation,代码行数:18,代码来源:serializer.py

示例6: _freeze_init_parameters

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def _freeze_init_parameters(class_, args, kwargs):
        self_guard = object()
        init_signature = signature(class_.__init__)
        bound_signature = init_signature.bind(self_guard, *args, **kwargs)
        arguments = [('class_.__name__', class_.__name__)]
        for name, value in bound_signature.arguments.items():
            if value == self_guard:
                continue
            if isinstance(value, Hashable):
                arguments.append((name, type(value), value))
            else:
                arguments.append((name, type(value), repr(value)))
        return frozenset(arguments) 
开发者ID:Qiskit,项目名称:qiskit-terra,代码行数:15,代码来源:basepasses.py

示例7: test_direct_subclassing

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [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)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:8,代码来源:test_collections.py

示例8: test_registration

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [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)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:9,代码来源:test_collections.py

示例9: __call__

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def __call__(self, func):
        def wrapper(*args, **kwargs):
            """

            :param *args:
            """
            key = self.key_mapper(*args) or args
            obj = args[0]

            if not hasattr(obj, '__memoized__'):
                try:
                    obj.__memoized__ = {}
                    instance_cache = obj.__memoized__
                except AttributeError:
                    if not hasattr(wrapper, '__memoized__'):
                        wrapper.__memoized__ = {}
                    instance_cache = wrapper.__memoized__
            else:
                try:
                    instance_cache = obj.__memoized__
                except AttributeError:
                    instance_cache = wrapper.__memoized__

            instance_cache[id(func)] = instance_cache.get(id(func), {})

            if not isinstance(key, collections.Hashable):
                # uncacheable. a list, for instance.
                # better to not cache than blow up.
                return func(*args)

            val = (instance_cache[id(func)][key]
                   if key in instance_cache[id(func)]
                   else func(*args))
            instance_cache[id(func)][key] = val
            return val

        return wrapper 
开发者ID:datadotworld,项目名称:data.world-py,代码行数:39,代码来源:util.py

示例10: test_issubclass_hashable

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def test_issubclass_hashable(bi_cls):
    """All hashable bidict types should implement :class:`collections.abc.Hashable`."""
    assert issubclass(bi_cls, Hashable) 
开发者ID:jab,项目名称:bidict,代码行数:5,代码来源:test_class_relationships.py

示例11: add

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def add(self, prop, values, cleaned=False, quiet=False):
        """Add the given value(s) to the property if they are not empty."""
        prop = self._get_prop(prop, quiet=quiet)
        if prop is None:
            return

        # Don't allow setting the reverse properties:
        if prop.stub:
            if quiet:
                return
            msg = gettext("Stub property (%s): %s")
            raise InvalidData(msg % (self.schema, prop))

        for value in ensure_list(values):
            if not cleaned:
                value = prop.type.clean(value, countries=self.countries)
            if value is None or not isinstance(value, Hashable):
                continue
            if prop.type == registry.entity and value == self.id:
                msg = gettext("Self-relationship (%s): %s")
                raise InvalidData(msg % (self.schema, prop))

            # Somewhat hacky: limit the maximum size of any particular
            # field to avoid overloading upstream aleph/elasticsearch.
            value_size = prop.type.values_size(value)
            if prop.type.max_size is not None:
                if self._size + value_size > prop.type.max_size:
                    # msg = "[%s] too large. Rejecting additional values."
                    # log.warning(msg, prop.name)
                    continue
            self._size += value_size

            if prop not in self._properties:
                self._properties[prop] = OrderedSet()
            self._properties[prop].add(value) 
开发者ID:alephdata,项目名称:followthemoney,代码行数:37,代码来源:proxy.py

示例12: __init__

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def __init__(self, *args, **kwargs):
        """Initialize."""

        arg = args[0] if args else kwargs
        is_dict = isinstance(arg, dict)
        if (
            is_dict and not all([isinstance(v, Hashable) for v in arg.values()]) or
            not is_dict and not all([isinstance(k, Hashable) and isinstance(v, Hashable) for k, v in arg])
        ):
            raise TypeError('All values must be hashable')

        self._d = dict(*args, **kwargs)
        self._hash = hash(tuple([(type(x), x, type(y), y) for x, y in sorted(self._d.items())])) 
开发者ID:facelessuser,项目名称:soupsieve,代码行数:15,代码来源:css_types.py

示例13: get_cmdcls

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def get_cmdcls(self, cmdname, interface='ACTIVE', exclusive=False):
        """
        Resolve command name `cmdname` to command class

        If `interface` is 'ACTIVE', return command class from
        `active_commands`.

        If `interface` is 'ANY', return command class from `all_commands`.

        If `interface` is anything else, it must be an existing interface and
        only a command that supports it is returned.

        If `exclusive` evaluates to True, the returned command class does not
        support any other interfaces.

        Returns None if no matching command class is registered.
        """
        if interface == 'ACTIVE':
            cmdpool = self.active_commands
        elif interface == 'ANY':
            cmdpool = self.all_commands
        elif isinstance(interface, abc.Hashable):
            try:
                cmdpool = tuple(self._cmds[interface].values())
            except KeyError:
                raise ValueError('Unknown interface: {!r}'.format(interface))
        else:
            raise RuntimeError('Interface type must be hashable: {!r}'.format(interface))

        for cmd in cmdpool:
            if cmdname in cmd.names:
                if not exclusive:
                    return cmd
                elif cmd.provides == (interface,):
                    return cmd 
开发者ID:rndusr,项目名称:stig,代码行数:37,代码来源:cmdmanager.py

示例14: map_values

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def map_values(mapping, path, key, old_parent, new_parent, new_items):
    ret = default_exit(path, key, old_parent, new_parent, new_items)
    for k, v in ret.items():
        if isinstance(v, Hashable) and v in mapping:
            ret[k] = mapping[v]
    return ret 
开发者ID:theislab,项目名称:anndata,代码行数:8,代码来源:test_concatenate.py

示例15: __hash__

# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Hashable [as 别名]
def __hash__(self):
        if isinstance(self._mapping, Hashable):
            return hash(self._mapping)
        else:
            return hash(frozenset(self._mapping.keys())) 
开发者ID:ESultanik,项目名称:lenticrypt,代码行数:7,代码来源:utils.py


注:本文中的collections.abc.Hashable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。