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: posterior.py From sampyl with MIT License | 6 votes |
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 #2
Source File: LinearProbingHashTable.py From ands with MIT License | 6 votes |
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 #3
Source File: LinearProbingHashTable.py From ands with MIT License | 6 votes |
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 #4
Source File: memoize.py From funsor with Apache License 2.0 | 6 votes |
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 #5
Source File: immutable.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 |
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 |
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: match.py From forge with Apache License 2.0 | 6 votes |
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 #9
Source File: posterior.py From sampyl with MIT License | 6 votes |
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 #10
Source File: posterior.py From sampyl with MIT License | 6 votes |
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 |
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: __init__.py From PyFlow with Apache License 2.0 | 5 votes |
def getHashableDataTypes(): if len(__HASHABLE_TYPES) == 0: for pin in getAllPinClasses(): t = pin.internalDataStructure() if t is not type(None) and t is not None: if isinstance(pin.internalDataStructure()(), collections.Hashable): __HASHABLE_TYPES.append(pin.__name__) return copy(__HASHABLE_TYPES)
Example #13
Source File: test_anchor.py From fontParts with MIT License | 5 votes |
def test_is_hashable(self): anchor_one = self.getAnchor_generic() self.assertTrue( isinstance(anchor_one, collections.Hashable) ) # ------- # Parents # -------
Example #14
Source File: test_layer.py From fontParts with MIT License | 5 votes |
def test_is_hashable(self): layer_one = self.getLayer_glyphs() self.assertTrue( isinstance(layer_one, collections.Hashable) ) # -------- # Equality # --------
Example #15
Source File: test_image.py From fontParts with MIT License | 5 votes |
def test_is_hashable(self): image_one = self.getImage_generic() self.assertTrue( isinstance(image_one, collections.Hashable) ) # -------- # Equality # --------
Example #16
Source File: umsgpack.py From slim with zlib License | 5 votes |
def _unpack_map(code, fp, options): if (ord(code) & 0xf0) == 0x80: length = (ord(code) & ~0xf0) elif code == b'\xde': length = struct.unpack(">H", _read_except(fp, 2))[0] elif code == b'\xdf': length = struct.unpack(">I", _read_except(fp, 4))[0] else: raise Exception("logic error, not map: 0x%02x" % ord(code)) d = {} if not options.get('use_ordered_dict') \ else collections.OrderedDict() for _ in xrange(length): # Unpack key k = _unpack(fp, options) if isinstance(k, list): # Attempt to convert list into a hashable tuple k = _deep_list_to_tuple(k) elif not isinstance(k, collections.Hashable): raise UnhashableKeyException( "encountered unhashable key: %s, %s" % (str(k), str(type(k)))) elif k in d: raise DuplicateKeyException( "encountered duplicate key: %s, %s" % (str(k), str(type(k)))) # Unpack value v = _unpack(fp, options) try: d[k] = v except TypeError: raise UnhashableKeyException( "encountered unhashable key: %s" % str(k)) return d
Example #17
Source File: umsgpack.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def _unpack_map(code, read_fn): if (ord(code) & 0xf0) == 0x80: length = (ord(code) & ~0xf0) elif code == b'\xde': length = struct.unpack(">H", read_fn(2))[0] elif code == b'\xdf': length = struct.unpack(">I", read_fn(4))[0] else: raise Exception("logic error, not map: 0x%02x" % ord(code)) d = {} for i in range(length): # Unpack key k = _unpackb(read_fn) if not isinstance(k, collections.Hashable): raise KeyNotPrimitiveException("encountered non-primitive key type: %s" % str(type(k))) elif k in d: raise KeyDuplicateException("encountered duplicate key: %s, %s" % (str(k), str(type(k)))) # Unpack value v = _unpackb(read_fn) d[k] = v return d ########################################
Example #18
Source File: params_helper.py From pyvivado with MIT License | 5 votes |
def make_hashable(d): if isinstance(d, collections.OrderedDict): hs = [] for k, v in d.items(): hs.append((k, make_hashable(v))) h = tuple(hs) elif isinstance(d, dict): hs = [] for k, v in d.items(): hs.append((k, make_hashable(v))) h = frozenset(hs) elif (isinstance(d, list) or isinstance(d, tuple)): hs = [] for v in d: hs.append(make_hashable(v)) h = tuple(hs) elif (isinstance(d, set) or isinstance(d, frozenset)): hs = [] for v in d: hs.append(make_hashable(v)) h = frozenset(hs) elif not isinstance(d, collections.Hashable): logger.error('Cannot hash {}'.format(d)) h = d else: h = d return h
Example #19
Source File: test_functools.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_hash(self): def mycmp(x, y): return y - x key = self.cmp_to_key(mycmp) k = key(10) self.assertRaises(TypeError, hash, k) self.assertNotIsInstance(k, collections.Hashable)
Example #20
Source File: test_glyph.py From fontParts with MIT License | 5 votes |
def test_is_hashable(self): glyph_one = self.getGlyph_generic() self.assertTrue( isinstance(glyph_one, collections.Hashable) ) # -------- # Equality # --------
Example #21
Source File: test_font.py From fontParts with MIT License | 5 votes |
def test_hash_is_hasbable(self): font_one = self.getFont_glyphs() self.assertEqual( isinstance(font_one, collections.Hashable), True ) # -------- # Equality # --------
Example #22
Source File: test_info.py From fontParts with MIT License | 5 votes |
def test_hash(self): info = self.getInfo_generic() self.assertEqual( isinstance(info, collections.Hashable), True ) # -------- # Equality # --------
Example #23
Source File: test_segment.py From fontParts with MIT License | 5 votes |
def test_hash(self): segment = self.getSegment_line() self.assertEqual( isinstance(segment, collections.Hashable), False ) # -------- # Equality # --------
Example #24
Source File: test_bPoint.py From fontParts with MIT License | 5 votes |
def test_hash(self): bPoint = self.getBPoint_corner() self.assertEqual( isinstance(bPoint, collections.Hashable), False ) # -------- # Equality # --------
Example #25
Source File: util.py From data.world-py with Apache License 2.0 | 5 votes |
def __call__(self, func): def wrapper(*args, **kwargs): """ :param *args: """ key = self.key_mapper(*args) or args obj = args[0] if not hasattr(obj, '__memoized__'): try: obj.__memoized__ = {} instance_cache = obj.__memoized__ except AttributeError: if not hasattr(wrapper, '__memoized__'): wrapper.__memoized__ = {} instance_cache = wrapper.__memoized__ else: try: instance_cache = obj.__memoized__ except AttributeError: instance_cache = wrapper.__memoized__ instance_cache[id(func)] = instance_cache.get(id(func), {}) if not isinstance(key, collections.Hashable): # uncacheable. a list, for instance. # better to not cache than blow up. return func(*args) val = (instance_cache[id(func)][key] if key in instance_cache[id(func)] else func(*args)) instance_cache[id(func)][key] = val return val return wrapper
Example #26
Source File: utils.py From VDAIC2017 with MIT License | 5 votes |
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 #27
Source File: __init__.py From Needl with MIT License | 5 votes |
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 #28
Source File: test_hash.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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 #29
Source File: test_hash.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_hashable(self): objects = (self.default_expected + self.fixed_expected) for obj in objects: self.assertIsInstance(obj, Hashable)
Example #30
Source File: constructor.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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