本文整理匯總了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
示例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)
示例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
示例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
示例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))
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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"
示例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
示例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)