Python collections.Hashable() Examples

The following are code examples for showing how to use collections.Hashable(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: zippy   Author: securesystemslab   File: test_collections.py    (license) View Source Project 6 votes vote down vote up
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__') 
Example 2
Project: taf   Author: taf3   File: utils.py    (license) View Source Project 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 3
Project: wdmapper   Author: gbv   File: test_link.py    (license) View Source Project 6 votes vote down vote up
def test_sets():
    a = Link('foo', 'bar', 'doz')
    b = Link('foo', 'bar', 'doz')
    c = Link('42')

    assert isinstance(a, collections.Hashable)
    assert hash(a) == hash(b)
    assert hash(b) != hash(c)

    s1 = set([a])
    s2 = set([b])
    s3 = set([c])

    assert (s1 - s2) == set()
    assert (s1 | s2) == set([a])
    assert (s1 | s2 | s3) == set([a,b,c])
    assert ((s1 | s2 | s3) - s1) == set([c]) 
Example 4
Project: matchminer-engine   Author: dfci   File: cerberus.py    (license) View Source Project 6 votes vote down vote up
def _validate_excludes(self, excludes, field, value):
        """ {'type': ['hashable', 'hashables']} """
        if isinstance(excludes, Hashable):
            excludes = [excludes]

        # Save required field to be checked latter
        if 'required' in self.schema[field] and self.schema[field]['required']:
            self._unrequired_by_excludes.add(field)
        for exclude in excludes:
            if (exclude in self.schema and
               'required' in self.schema[exclude] and
                    self.schema[exclude]['required']):

                self._unrequired_by_excludes.add(exclude)

        if [True for key in excludes if key in self.document]:
            # Wrap each field in `excludes` list between quotes
            exclusion_str = ', '.join("'{0}'"
                                      .format(word) for word in excludes)
            self._error(field, errors.EXCLUDES_FIELD, exclusion_str) 
Example 5
Project: AerisCloud   Author: AerisCloud   File: utils.py    (license) View Source Project 6 votes vote down vote up
def memoized(func):
    _cache = {}

    def _deco(*args, **kwargs):
        if 'clear_cache' in kwargs or 'clear_cache_only' in kwargs:
            _cache.clear()
            if 'clear_cache_only' in kwargs:
                return  # we don't care about the output
            del kwargs['clear_cache']
        if not isinstance(args, collections.Hashable):
            return func(*args, **kwargs)
        if args in _cache:
            return _cache[args]
        else:
            value = func(*args, **kwargs)
            _cache[args] = value
            return value

    return update_wrapper(_deco, func) 
Example 6
Project: forge   Author: datawire   File: match.py    (license) View Source Project 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 7
Project: kino-bot   Author: DongjunLee   File: __init__.py    (license) View Source Project 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 8
Project: girder_worker   Author: girder   File: utils.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def to_frozenset(item):
    """Recursively convert 'item' to a frozenset"""
    if isinstance(item, Hashable):
        return item

    if isinstance(item, dict):
        return frozenset([(k, to_frozenset(v)) for k, v in item.items()])

    if isinstance(item, list):
        return frozenset([to_frozenset(v) for v in item]) 
Example 9
Project: petronia   Author: groboclown   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_mapping(self, node, deep=False):
        if not isinstance(node, MappingNode):
            raise ConstructorError(None, None,
                    "expected a mapping node, but found %s" % node.id,
                    node.start_mark)
        mapping = {}
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            if not isinstance(key, collections.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 
Example 10
Project: deb-python-functools32   Author: openstack   File: test_functools32.py    (license) View Source Project 5 votes vote down vote up
def test_hash(self):
        def mycmp(x, y):
            return y - x
        key = functools.cmp_to_key(mycmp)
        k = key(10)
        self.assertRaises(TypeError, hash, k)
        self.assertFalse(isinstance(k, collections.Hashable)) 
Example 11
Project: centos-base-consul   Author: zeroc0d3lab   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_mapping(self, node, deep=False):
		if not isinstance(node, nodes.MappingNode):
			raise ConstructorError(
				None, None,
				'expected a mapping node, but found %s' % node.id,
				node.start_mark
			)
		mapping = {}
		for key_node, value_node in node.value:
			key = self.construct_object(key_node, deep=deep)
			if not isinstance(key, collections.Hashable):
				self.echoerr(
					'While constructing a mapping', node.start_mark,
					'found unhashable key', key_node.start_mark
				)
				continue
			elif type(key.value) != unicode:
				self.echoerr(
					'Error while constructing a mapping', node.start_mark,
					'found key that is not a string', key_node.start_mark
				)
				continue
			elif key in mapping:
				self.echoerr(
					'Error while constructing a mapping', node.start_mark,
					'found duplicate key', key_node.start_mark
				)
				continue
			value = self.construct_object(value_node, deep=deep)
			mapping[key] = value
		return mapping 
Example 12
Project: lemongraph   Author: NationalSecurityAgency   File: serializer.py    (license) View Source Project 5 votes vote down vote up
def msgpack_encode_hashable(x):
    if not isinstance(x, collections.Hashable):
        raise ValueError(x)
    return messagepack.packb(x) 
Example 13
Project: radar   Author: amoose136   File: test_multiarray.py    (license) View Source Project 5 votes vote down vote up
def test_collections_hashable(self):
        x = np.array([])
        self.assertFalse(isinstance(x, collections.Hashable)) 
Example 14
Project: scikit-kge   Author: mnick   File: util.py    (license) View Source Project 5 votes vote down vote up
def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            # uncachable, return direct function application
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            val = self.func(*args)
            self.cache[args] = val
            return val 
Example 15
Project: cli   Author: madcore-ai   File: memoize.py    (license) View Source Project 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.set_cache(value, *args)
            return value 
Example 16
Project: antgo   Author: jianzfb   File: utils.py    (license) View Source Project 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
Project: DevOps   Author: YoLoveLife   File: mathstuff.py    (license) View Source Project 5 votes vote down vote up
def unique(a):
    if isinstance(a,collections.Hashable):
        c = set(a)
    else:
        c = []
        for x in a:
            if x not in c:
                c.append(x)
    return c 
Example 18
Project: DevOps   Author: YoLoveLife   File: mathstuff.py    (license) View Source Project 5 votes vote down vote up
def intersect(a, b):
    if isinstance(a,collections.Hashable) and isinstance(b,collections.Hashable):
        c = set(a) & set(b)
    else:
        c = unique(filter(lambda x: x in b, a))
    return c 
Example 19
Project: DevOps   Author: YoLoveLife   File: mathstuff.py    (license) View Source Project 5 votes vote down vote up
def difference(a, b):
    if isinstance(a,collections.Hashable) and isinstance(b,collections.Hashable):
        c = set(a) - set(b)
    else:
        c = unique(filter(lambda x: x not in b, a))
    return c 
Example 20
Project: DevOps   Author: YoLoveLife   File: mathstuff.py    (license) View Source Project 5 votes vote down vote up
def symmetric_difference(a, b):
    if isinstance(a,collections.Hashable) and isinstance(b,collections.Hashable):
        c = set(a) ^ set(b)
    else:
        c = unique(filter(lambda x: x not in intersect(a,b), union(a,b)))
    return c 
Example 21
Project: DevOps   Author: YoLoveLife   File: mathstuff.py    (license) View Source Project 5 votes vote down vote up
def union(a, b):
    if isinstance(a,collections.Hashable) and isinstance(b,collections.Hashable):
        c = set(a) | set(b)
    else:
        c = unique(a + b)
    return c 
Example 22
Project: CommunityCellularManager   Author: facebookincubator   File: dictdiff.py    (license) View Source Project 5 votes vote down vote up
def _make_hashable(o):
    if isinstance(o, collections.Hashable):
        return o
    # Py2 requires string class name, not Unicode (which literals are)
    return type(str(''), (type(o),), dict(__hash__=_uni_hash))(o) 
Example 23
Project: CommunityCellularManager   Author: facebookincubator   File: dictdiff.py    (license) View Source Project 5 votes vote down vote up
def _make_hashable(o):
    if isinstance(o, collections.Hashable):
        return o
    # Py2 requires string class name, not Unicode (which literals are)
    return type(str(''), (type(o),), dict(__hash__=_uni_hash))(o) 
Example 24
Project: CommunityCellularManager   Author: facebookincubator   File: dictdiff.py    (license) View Source Project 5 votes vote down vote up
def _make_hashable(o):
    if isinstance(o, collections.Hashable):
        return o
    # Py2 requires string class name, not Unicode (which literals are)
    return type(str(''), (type(o),), dict(__hash__=_uni_hash))(o) 
Example 25
Project: qiime2   Author: qiime2   File: test_grammar.py    (license) View Source Project 5 votes vote down vote up
def test_hashable(self):
        a = grammar.TypeExpression('X')
        b = grammar.TypeExpression('Y', fields=(a,))
        c = grammar.TypeExpression('Y', fields=(a,))
        d = grammar.TypeExpression('Z', predicate=grammar.Predicate("stuff"))

        self.assertIsInstance(a, collections.Hashable)
        # There really shouldn't be a collision between these:
        self.assertNotEqual(hash(a), hash(d))

        self.assertEqual(b, c)
        self.assertEqual(hash(b), hash(c))

    # TODO: Test dictionaries work well 
Example 26
Project: zippy   Author: securesystemslab   File: test_matrices.py    (license) View Source Project 5 votes vote down vote up
def test_hash():
    for cls in classes[-2:]:
        s = set([cls.eye(1), cls.eye(1)])
        assert len(s) == 1 and s.pop() == cls.eye(1)
    # issue 3979
    for cls in classes[:2]:
        assert not isinstance(cls.eye(1), collections.Hashable) 
Example 27
Project: zippy   Author: securesystemslab   File: test_collections.py    (license) View Source Project 5 votes vote down vote up
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)) 
Example 28
Project: zippy   Author: securesystemslab   File: test_collections.py    (license) View Source Project 5 votes vote down vote up
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)) 
Example 29
Project: zippy   Author: securesystemslab   File: test_functools.py    (license) View Source Project 5 votes vote down vote up
def test_hash(self):
        def mycmp(x, y):
            return y - x
        key = functools.cmp_to_key(mycmp)
        k = key(10)
        self.assertRaises(TypeError, hash, k)
        self.assertFalse(isinstance(k, collections.Hashable)) 
Example 30
Project: zippy   Author: securesystemslab   File: test_hash.py    (license) View Source Project 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 
Example 31
Project: analytics-platform-ops   Author: ministryofjustice   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_mapping(self, node, deep=False):
        if not isinstance(node, MappingNode):
            raise ConstructorError(None, None,
                    "expected a mapping node, but found %s" % node.id,
                    node.start_mark)
        mapping = {}
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            if not isinstance(key, collections.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 
Example 32
Project: aws-ec2rescue-linux   Author: awslabs   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_mapping(self, node, deep=False):
        if not isinstance(node, MappingNode):
            raise ConstructorError(None, None,
                    "expected a mapping node, but found %s" % node.id,
                    node.start_mark)
        mapping = {}
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            if not isinstance(key, collections.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 
Example 33
Project: fandango   Author: tango-controls   File: functional.py    (license) View Source Project 5 votes vote down vote up
def isHashable(seq):
    if not isinstance(seq,Hashable):
        return False
    elif isSequence(seq): 
        return all(isHashable(s) for s in seq)
    else:
        return True 
Example 34
Project: trex-http-proxy   Author: alwye   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_mapping(self, node, deep=False):
        if not isinstance(node, MappingNode):
            raise ConstructorError(None, None,
                    "expected a mapping node, but found %s" % node.id,
                    node.start_mark)
        mapping = {}
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            if not isinstance(key, collections.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 
Example 35
Project: krpcScripts   Author: jwvanderbeck   File: test_multiarray.py    (license) View Source Project 5 votes vote down vote up
def test_collections_hashable(self):
        x = np.array([])
        self.assertFalse(isinstance(x, collections.Hashable)) 
Example 36
Project: oil   Author: oilshell   File: test_hash.py    (license) View Source Project 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 37
Project: oil   Author: oilshell   File: test_hash.py    (license) View Source Project 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 38
Project: python2-tracer   Author: extremecoders-re   File: test_hash.py    (license) View Source Project 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 39
Project: python2-tracer   Author: extremecoders-re   File: test_hash.py    (license) View Source Project 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 40
Project: actsys   Author: intel-ctrlsys   File: RDict.py    (license) View Source Project 5 votes vote down vote up
def __check_key_type(key):
        if not isinstance(key, list) or any([not isinstance(elt, Hashable) or elt is None for elt in key]):
            raise TypeError('RDict keys must be lists of hashable, non-None objects.') 
Example 41
Project: actsys   Author: intel-ctrlsys   File: ResourceTree.py    (license) View Source Project 5 votes vote down vote up
def __get_plugin(self, plugin_description):
        try:
            if isinstance(plugin_description, Hashable) and plugin_description is not None:
                if plugin_description in self.saved_plugins:
                    return self.saved_plugins[plugin_description]
                raise RuntimeError("Plugin not previously defined")
            elif isinstance(plugin_description, dict):
                return Plugin.plugin(plugin_description)
            raise RuntimeError("Plugin description not dict or Hashable")
        except RuntimeError as ex:
            exception_string = "\n\t".join(str(ex).splitlines())
            self.logger.warn("Could not instantiate plugin from: "+str(plugin_description)+exception_string) 
Example 42
Project: algorithms   Author: andrew310   File: heldKarp.py    (license) View Source Project 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 43
Project: islam-buddy   Author: hamir   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_mapping(self, node, deep=False):
        # type: (Any, bool) -> Any
        """deep is True when creating an object/mapping recursively,
        in that case want the underlying elements available during construction
        """
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None, None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark)
        mapping = {}
        for key_node, value_node in node.value:
            # keys can be list -> deep
            key = self.construct_object(key_node, deep=True)
            # lists are not hashable, but tuples are
            if not isinstance(key, collections.Hashable):  # type: ignore
                if isinstance(key, list):
                    key = tuple(key)
            if PY2:
                try:
                    hash(key)
                except TypeError as exc:
                    raise ConstructorError(
                        "while constructing a mapping", node.start_mark,
                        "found unacceptable key (%s)" %
                        exc, key_node.start_mark)
            else:
                if not isinstance(key, collections.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 
Example 44
Project: islam-buddy   Author: hamir   File: constructor.py    (license) View Source Project 5 votes vote down vote up
def construct_setting(self, node, typ, deep=False):
        # type: (Any, Any, bool) -> Any
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None, None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark)
        if node.comment:
            typ._yaml_add_comment(node.comment[:2])
            if len(node.comment) > 2:
                typ.yaml_end_comment_extend(node.comment[2], clear=True)
        if node.anchor:  # type: ignore
            from ruamel.yaml.serializer import templated_id
            if not templated_id(node.anchor):
                typ.yaml_set_anchor(node.anchor)
        for key_node, value_node in node.value:
            # keys can be list -> deep
            key = self.construct_object(key_node, deep=True)
            # lists are not hashable, but tuples are
            if not isinstance(key, collections.Hashable):  # type: ignore
                if isinstance(key, list):
                    key = tuple(key)
            if PY2:
                try:
                    hash(key)
                except TypeError as exc:
                    raise ConstructorError(
                        "while constructing a mapping", node.start_mark,
                        "found unacceptable key (%s)" %
                        exc, key_node.start_mark)
            else:
                if not isinstance(key, collections.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)  # NOQA
            if key_node.comment:
                typ._yaml_add_comment(key_node.comment, key=key)
            if value_node.comment:
                typ._yaml_add_comment(value_node.comment, value=key)
            typ.add(key) 
Example 45
Project: Needl   Author: eth0izzle   File: __init__.py    (license) View Source Project 5 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 46
Project: web_ctp   Author: molebot   File: test_functools.py    (license) View Source Project 5 votes vote down vote up
def test_hash(self):
        def mycmp(x, y):
            return y - x
        key = functools.cmp_to_key(mycmp)
        k = key(10)
        self.assertRaises(TypeError, hash, k)
        self.assertNotIsInstance(k, collections.Hashable) 
Example 47
Project: web_ctp   Author: molebot   File: test_hash.py    (license) View Source Project 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 48
Project: web_ctp   Author: molebot   File: test_hash.py    (license) View Source Project 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 
Example 49
Project: matchminer-engine   Author: dfci   File: schema.py    (license) View Source Project 5 votes vote down vote up
def _validate_type_hashable(self, value):
        if isinstance(value, Hashable):
            return True 
Example 50
Project: PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda   Author: SignalMedia   File: common.py    (license) View Source Project 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