Python collections.abc.Hashable() Examples

The following are 30 code examples of collections.abc.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.abc , or try the search function .
Example #1
Source File: serializer.py    From workload-automation with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: validation.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: memoization.py    From devito with MIT License 6 votes vote down vote up
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 
Example #4
Source File: keydict.py    From gpkit with MIT License 6 votes vote down vote up
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 
Example #5
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 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 #6
Source File: test_collections.py    From ironpython3 with Apache License 2.0 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 #7
Source File: test_collections.py    From android_universal with MIT License 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 #8
Source File: test_collections.py    From Fluid-Designer with GNU General Public License v3.0 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 #9
Source File: test_hash.py    From android_universal with MIT License 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 #10
Source File: test_hash.py    From android_universal 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) 
Example #11
Source File: css_types.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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())])) 
Example #12
Source File: validators.py    From pydantic with MIT License 5 votes vote down vote up
def hashable_validator(v: Any) -> Hashable:
    if isinstance(v, Hashable):
        return v

    raise errors.HashableError() 
Example #13
Source File: test_dataclasses.py    From pydantic with MIT License 5 votes vote down vote up
def test_hashable_optional(default):
    @pydantic.dataclasses.dataclass
    class MyDataclass:
        v: Hashable = default

    MyDataclass()
    MyDataclass(v=None) 
Example #14
Source File: test_dataclasses.py    From pydantic with MIT License 5 votes vote down vote up
def test_hashable_required():
    @pydantic.dataclasses.dataclass
    class MyDataclass:
        v: Hashable

    MyDataclass(v=None)
    with pytest.raises(ValidationError) as exc_info:
        MyDataclass(v=[])
    assert exc_info.value.errors() == [
        {'loc': ('v',), 'msg': 'value is not a valid hashable', 'type': 'type_error.hashable'}
    ]
    with pytest.raises(TypeError) as exc_info:
        MyDataclass()
    assert str(exc_info.value) == "__init__() missing 1 required positional argument: 'v'" 
Example #15
Source File: test_edge_cases.py    From pydantic with MIT License 5 votes vote down vote up
def test_hashable_optional(default):
    class Model(BaseModel):
        v: Hashable = default

    Model(v=None)
    Model() 
Example #16
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
def test_direct_subclassing(self):
        for B in Hashable, Iterable, Iterator, Reversible, Sized, Container, Callable:
            class C(B):
                pass
            self.assertTrue(issubclass(C, B))
            self.assertFalse(issubclass(int, C)) 
Example #17
Source File: test_edge_cases.py    From pydantic with MIT License 5 votes vote down vote up
def test_hashable_required():
    class Model(BaseModel):
        v: Hashable

    Model(v=None)
    with pytest.raises(ValidationError) as exc_info:
        Model(v=[])
    assert exc_info.value.errors() == [
        {'loc': ('v',), 'msg': 'value is not a valid hashable', 'type': 'type_error.hashable'}
    ]
    with pytest.raises(ValidationError) as exc_info:
        Model()
    assert exc_info.value.errors() == [{'loc': ('v',), 'msg': 'field required', 'type': 'value_error.missing'}] 
Example #18
Source File: definition.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def parse_value(self, value):
        if isinstance(value, Hashable):
            enum_value = self._name_lookup.get(value)

            if enum_value:
                return enum_value.value

        return None 
Example #19
Source File: definition.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def serialize(self, value):
        # type: (Union[str, PyEnum]) -> Optional[str]
        if isinstance(value, PyEnum):
            # We handle PyEnum values
            value = value.value
        if isinstance(value, Hashable):
            enum_value = self._value_lookup.get(value)
            if enum_value:
                return enum_value.name

        return None 
Example #20
Source File: test_collections.py    From android_universal with MIT License 5 votes vote down vote up
def test_registration(self):
        for B in Hashable, Iterable, Iterator, Reversible, 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 #21
Source File: memoization.py    From devito with MIT License 5 votes vote down vote up
def __call__(self, *args):
        if not isinstance(args, 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: memoization.py    From devito with MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        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_gen
        except AttributeError:
            cache = obj.__cache_gen = {}
        key = (self.func, args[1:], frozenset(kwargs.items()))
        it = cache[key] if key in cache else self.func(*args, **kwargs)
        cache[key], result = tee(it)
        return result 
Example #23
Source File: utils.py    From lenticrypt with GNU General Public License v2.0 5 votes vote down vote up
def __hash__(self):
        if isinstance(self._mapping, Hashable):
            return hash(self._mapping)
        else:
            return hash(frozenset(self._mapping.keys())) 
Example #24
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 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 #25
Source File: test_collections.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 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 #26
Source File: test_concatenate.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #27
Source File: cmdmanager.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #28
Source File: css_types.py    From soupsieve with MIT License 5 votes vote down vote up
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())])) 
Example #29
Source File: proxy.py    From followthemoney with MIT License 5 votes vote down vote up
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) 
Example #30
Source File: test_collections.py    From ironpython3 with Apache License 2.0 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))