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


Python collections.Hashable方法代码示例

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


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

示例1: get

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def get(self, key: object) -> object:
        """Returns the value associated with key.

        If key is None, a TypeError is raised, because keys cannot be None."""
        assert is_hash_table(self)

        if key is None:
            raise TypeError("key cannot be None.")
        if not isinstance(key, Hashable):
            raise TypeError("key must be an instance of a hashable type")

        value = LinearProbingHashTable._get(key, self._keys, self._values,
                                            self._n)

        assert is_hash_table(self)

        return value 
开发者ID:nbro,项目名称:ands,代码行数:19,代码来源:LinearProbingHashTable.py

示例2: delete

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def delete(self, key: object) -> object:
        """Deletes the mapping between key and its associated value.

        If there's no mapping, nothing is done."""
        assert is_hash_table(self)

        if key is None:
            raise TypeError("key cannot be None.")
        if not isinstance(key, Hashable):
            raise TypeError("key must be an instance of a hashable type")

        try:
            i = self._keys.index(key)
            v = self._values[i]
            self._keys[i] = self._values[i] = None
            return v
        except ValueError:
            pass
        finally:
            assert is_hash_table(self) 
开发者ID:nbro,项目名称:ands,代码行数:22,代码来源:LinearProbingHashTable.py

示例3: memoize

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def memoize(cache=None):
    """
    Exploit cons-hashing to do implicit common subexpression elimination
    """
    if cache is None:
        cache = {}

    @interpreter.interpretation(interpreter._INTERPRETATION)  # use base
    def memoize_interpretation(cls, *args):
        key = (cls,) + tuple(id(arg) if (type(arg).__name__ == "DeviceArray") or not isinstance(arg, Hashable)
                             else arg for arg in args)
        if key not in cache:
            cache[key] = cls(*args)
        return cache[key]

    with interpreter.interpretation(memoize_interpretation):
        yield cache 
开发者ID:pyro-ppl,项目名称:funsor,代码行数:19,代码来源:memoize.py

示例4: projections

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def projections(value, match_value=True):
    if match_value and isinstance(value, collections.Hashable):
        yield value
    traits = getattr(value, "MATCH_TRAITS", None)
    if traits is not None:
        if isinstance(traits, tuple):
            for t in traits:
                yield t
        else:
            yield traits
    if not isinstance(value, Marker):
        if isinstance(value, super):
            for cls in value.__self_class__.__mro__[1:]:
                yield cls
        else:
            for cls in value.__class__.__mro__:
                yield cls 
开发者ID:datawire,项目名称:forge,代码行数:19,代码来源:match.py

示例5: to_immutable

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def to_immutable(obj: Any) -> ImmutableType:
    """Convert the given Python object into an immutable type."""
    if obj is None:
        return obj
    if isinstance(obj, Hashable):
        # gets around cases of tuple of un-hashable types.
        try:
            hash(obj)
            return obj
        except TypeError:
            pass
    if isinstance(obj, tuple):
        return tuple((to_immutable(v) for v in obj))
    if isinstance(obj, list):
        return ImmutableList([to_immutable(v) for v in obj])
    if isinstance(obj, set):
        return ImmutableList([to_immutable(v) for v in sorted(obj)])
    if isinstance(obj, dict):
        return ImmutableSortedDict(obj)

    raise ValueError('Cannot convert the following object to immutable type: {}'.format(obj)) 
开发者ID:ucb-art,项目名称:BAG_framework,代码行数:23,代码来源:immutable.py

示例6: tag

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def tag(self, *tags):
        """
        Tags the job with one or more unique indentifiers.

        Tags must be hashable. Duplicate tags are discarded.

        :param tags: A unique list of ``Hashable`` tags.
        :return: The invoked job instance
        """
        if any([not isinstance(tag, collections.Hashable) for tag in tags]):
            raise TypeError("Every tag should be hashable")

        if not all(isinstance(tag, collections.Hashable) for tag in tags):
            raise TypeError("Tags must be hashable")
        self.tags.update(tags)
        return self 
开发者ID:DongjunLee,项目名称:quantified-self,代码行数:18,代码来源:__init__.py

示例7: memoized

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def memoized(func):
    """A decorator to cache function's return value"""
    cache = {}

    @functools.wraps(func)
    def wrapper(*args):
        if not isinstance(args, collections.Hashable):
            # args is not cacheable. just call the function.
            return func(*args)
        if args in cache:
            return cache[args]
        else:
            value = func(*args)
            cache[args] = value
            return value
    return wrapper 
开发者ID:openstack,项目名称:magnum,代码行数:18,代码来源:utils.py

示例8: logp

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def logp(self, state):
        """ Return log P(X) given a :ref:`state <state>` X"""
        frozen_state = state.freeze()
        if not isinstance(frozen_state, collections.Hashable):
            # uncacheable. a list, for instance.
            # better to not cache than blow up.
            logp_value, _ = self.logp_func(*state.values())
            return logp_value

        if frozen_state in self._logp_cache:
            logp_value = self._logp_cache[frozen_state]
        else:
            logp_value, grad_value = self.logp_func(*state.values())
            self._logp_cache[frozen_state] = logp_value
            self._grad_cache[frozen_state] = grad_value

        return logp_value 
开发者ID:mcleonard,项目名称:sampyl,代码行数:19,代码来源:posterior.py

示例9: grad

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def grad(self, state):
        """ Return grad log P(X) given a :ref:`state <state>` X """
        # Freeze the state as a tuple so we can use it as a dictionary key
        frozen_state = state.freeze()
        if not isinstance(frozen_state, collections.Hashable):
            # uncacheable. a list, for instance.
            # better to not cache than blow up.
            _, grad_value = self.logp_func(*state.values())
            return grad_value

        if frozen_state in self._grad_cache:
            grad_value = self._grad_cache[frozen_state]
        else:
            logp_value, grad_value = self.logp_func(*state.values())
            self._logp_cache[frozen_state] = logp_value
            self._grad_cache[frozen_state] = grad_value

        return grad_value 
开发者ID:mcleonard,项目名称:sampyl,代码行数:20,代码来源:posterior.py

示例10: construct_variables

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def construct_variables(self, kwargs):
        """
        Construct the inputs to the attack graph to be used by generate_np.

        :param kwargs: Keyword arguments to generate_np.
        :return: Structural and feedable arguments as well as a unique key
                 for the graph given these inputs.
        """
        # the set of arguments that are structural properties of the attack
        # if these arguments are different, we must construct a new graph
        fixed = dict(
            (k, v) for k, v in kwargs.items() if k in self.structural_kwargs)

        # the set of arguments that are passed as placeholders to the graph
        # on each call, and can change without constructing a new graph
        feedable = dict(
            (k, v) for k, v in kwargs.items() if k in self.feedable_kwargs)

        if len(fixed) + len(feedable) < len(kwargs):
            warnings.warn("Supplied extra keyword arguments that are not "
                          "used in the graph computation. They have been "
                          "ignored.")

        if not all(
                isinstance(value, collections.Hashable)
                for value in fixed.values()):
            # we have received a fixed value that isn't hashable
            # this means we can't cache this graph for later use,
            # and it will have to be discarded later
            hash_key = None
        else:
            # create a unique key for this set of fixed paramaters
            hash_key = tuple(sorted(fixed.items()))

        return fixed, feedable, hash_key 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:37,代码来源:attacks.py

示例11: __call__

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            # uncacheable. a list, for instance.
            # better to not cache than blow up.
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            return value 
开发者ID:pxsocs,项目名称:thewarden,代码行数:13,代码来源:decorators.py

示例12: is_hashable

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def is_hashable(arg):
    """Return True if hash(arg) will succeed, False otherwise.

    Some types will pass a test against collections.Hashable but fail when they
    are actually hashed with hash().

    Distinguish between these and other types by trying the call to hash() and
    seeing if they raise TypeError.

    Examples
    --------
    >>> a = ([],)
    >>> isinstance(a, collections.Hashable)
    True
    >>> is_hashable(a)
    False
    """

    # unfortunately, we can't use isinstance(arg, collections.Hashable), which
    # can be faster than calling hash, because numpy scalars on Python 3 fail
    # this test

    # reconsider this decision once this numpy bug is fixed:
    # https://github.com/numpy/numpy/issues/5562

    try:
        hash(arg)
    except TypeError:
        return False
    else:
        return True 
开发者ID:J535D165,项目名称:recordlinkage,代码行数:33,代码来源:types.py

示例13: _handle_arg_type

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def _handle_arg_type(arg, param):
    if isinstance(arg.type, Hashable) and arg.type in PY_TYPES:
        param["type"] = PY_TYPES[arg.type]
    elif hasattr(arg.type, "__apidoc__"):
        param["type"] = arg.type.__apidoc__["name"]
        param["in"] = "body"
    elif hasattr(arg.type, "__schema__"):
        param.update(arg.type.__schema__)
    elif arg.location == "files":
        param["type"] = "file"
    else:
        param["type"] = "string" 
开发者ID:picoCTF,项目名称:picoCTF,代码行数:14,代码来源:reqparse.py

示例14: __call__

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            # uncacheable. a list, for instance.
            # better to not cache than blow up.
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
        return value 
开发者ID:eranimo,项目名称:hexgen,代码行数:13,代码来源:util.py

示例15: test_hashable

# 需要导入模块: import collections [as 别名]
# 或者: from collections import Hashable [as 别名]
def test_hashable(self):
        objects = (self.default_expected +
                   self.fixed_expected)
        for obj in objects:
            self.assertIsInstance(obj, Hashable) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:7,代码来源:test_hash.py


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