Python collections.Hashable() Examples

The following are 30 code examples of collections.Hashable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module collections , or try the search function .
Example #1
Source File: LinearProbingHashTable.py    From ands with MIT License 6 votes vote down vote up
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 
Example #2
Source File: LinearProbingHashTable.py    From ands with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: memoize.py    From funsor with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: match.py    From forge with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: immutable.py    From BAG_framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #6
Source File: __init__.py    From quantified-self with MIT License 6 votes vote down vote up
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 
Example #7
Source File: utils.py    From magnum with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: posterior.py    From sampyl with MIT License 6 votes vote down vote up
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 
Example #9
Source File: posterior.py    From sampyl with MIT License 6 votes vote down vote up
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 
Example #10
Source File: posterior.py    From sampyl with MIT License 6 votes vote down vote up
def logp(self, state):
        """ Return 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.
            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 = self.logp_func(*state.values())
            self._logp_cache[frozen_state] = logp_value

        return logp_value 
Example #11
Source File: posterior.py    From sampyl with MIT License 6 votes vote down vote up
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 = grad_vec(self.grad_func, state)
            return grad_value

        if frozen_state in self._grad_cache:
            grad_value = self._grad_cache[frozen_state]
        else:
            grad_value = grad_vec(self.grad_func, state)
            self._grad_cache[frozen_state] = grad_value

        return grad_value 
Example #12
Source File: attacks.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #13
Source File: attacks.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #14
Source File: decorators.py    From thewarden with MIT License 5 votes vote down vote up
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 
Example #15
Source File: types.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #16
Source File: memoized.py    From apk_api_key_extractor with Apache License 2.0 5 votes vote down vote up
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 
Example #17
Source File: basenji_fetch_app2.py    From basenji with Apache License 2.0 5 votes vote down vote up
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 
Example #18
Source File: basenji_fetch_app1.py    From basenji with Apache License 2.0 5 votes vote down vote up
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 
Example #19
Source File: basenji_fetch_app.py    From basenji with Apache License 2.0 5 votes vote down vote up
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 
Example #20
Source File: reqparse.py    From picoCTF with MIT License 5 votes vote down vote up
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" 
Example #21
Source File: util.py    From hexgen with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #22
Source File: test_hash.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_hashable(self):
        objects = (self.default_expected +
                   self.fixed_expected)
        for obj in objects:
            self.assertIsInstance(obj, Hashable) 
Example #23
Source File: test_hash.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_not_hashable(self):
        for obj in self.error_expected:
            self.assertNotIsInstance(obj, Hashable)


# Issue #4701: Check that some builtin types are correctly hashable
#  (This test only used to fail in Python 3.0, but has been included
#   in 2.x along with the lazy call to PyType_Ready in PyObject_Hash) 
Example #24
Source File: macros.py    From pyth with MIT License 5 votes vote down vote up
def is_hash(a):
    return isinstance(a, collections.Hashable) 
Example #25
Source File: util.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #26
Source File: inference.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def is_hashable(obj):
    """Return True if hash(obj) 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(obj, collections.Hashable), which
    # can be faster than calling hash. That is 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(obj)
    except TypeError:
        return False
    else:
        return True 
Example #27
Source File: util.py    From indy-plenum with Apache License 2.0 5 votes vote down vote up
def mostCommonElement(elements: Iterable[T], to_hashable_f: Callable=None):
    """
    Find the most frequent element of a collection.

    :param elements: An iterable of elements
    :param to_hashable_f: (optional) if defined will be used to get
        hashable presentation for non-hashable elements. Otherwise json.dumps
        is used with sort_keys=True
    :return: element which is the most frequent in the collection and
        the number of its occurrences
    """
    class _Hashable(collections.abc.Hashable):
        def __init__(self, orig):
            self.orig = orig

            if isinstance(orig, collections.Hashable):
                self.hashable = orig
            elif to_hashable_f is not None:
                self.hashable = to_hashable_f(orig)
            else:
                self.hashable = json.dumps(orig, sort_keys=True)

        def __eq__(self, other):
            return self.hashable == other.hashable

        def __hash__(self):
            return hash(self.hashable)

    _elements = (_Hashable(el) for el in elements)
    most_common, counter = Counter(_elements).most_common(n=1)[0]
    return most_common.orig, counter 
Example #28
Source File: LinearProbingHashTable.py    From ands with MIT License 5 votes vote down vote up
def put(self, key: object, value: object) -> None:
        """Inserts the pair (key: value) in this map.

        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")

        self._put(key, value, self._n)

        assert is_hash_table(self) 
Example #29
Source File: terms.py    From funsor with Apache License 2.0 5 votes vote down vote up
def reflect(cls, *args, **kwargs):
    """
    Construct a funsor, populate ``._ast_values``, and cons hash.
    This is the only interpretation allowed to construct funsors.
    """
    if len(args) > len(cls._ast_fields):
        # handle varargs
        new_args = tuple(args[:len(cls._ast_fields) - 1]) + (args[len(cls._ast_fields) - 1 - len(args):],)
        assert len(new_args) == len(cls._ast_fields)
        _, args = args, new_args

    # JAX DeviceArray has .__hash__ method but raise the unhashable error there.
    cache_key = tuple(id(arg) if type(arg).__name__ == "DeviceArray" or not isinstance(arg, Hashable)
                      else arg for arg in args)
    if cache_key in cls._cons_cache:
        return cls._cons_cache[cache_key]

    arg_types = tuple(typing.Tuple[tuple(map(type, arg))]
                      if (type(arg) is tuple and all(isinstance(a, Funsor) for a in arg))
                      else typing.Tuple if (type(arg) is tuple and not arg)
                      else type(arg) for arg in args)
    cls_specific = (cls.__origin__ if cls.__args__ else cls)[arg_types]
    result = super(FunsorMeta, cls_specific).__call__(*args)
    result._ast_values = args

    # alpha-convert eagerly upon binding any variable
    result = _alpha_mangle(result)

    cls._cons_cache[cache_key] = result
    return result 
Example #30
Source File: test_hash.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_hashable(self):
        objects = (self.default_expected +
                   self.fixed_expected)
        for obj in objects:
            self.assertIsInstance(obj, Hashable)