我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用collections.abc.Hashable()。
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__')
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 not 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
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))
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))