hashable

What makes a user-defined class unhashable?

What makes a user-defined class unhashable? Question: The docs say that a class is hashable as long as it defines __hash__ method and __eq__ method. However: class X(list): # read-only interface of `tuple` and `list` should be the same, so reuse tuple.__hash__ __hash__ = tuple.__hash__ x1 = X() s = {x1} # TypeError: unhashable type: …

Total answers: 5

Why can't I use a list as a dict key in python?

Why can't I use a list as a dict key in python? Exactly what can and cannot be used, and why? Question: I found that the following are all valid: >>> d = {} >>> d[None] = ‘foo’ >>> d[(1, 3)] = ‘baz’ Even a module can be used as a dict key: >>> import …

Total answers: 11

Using @functools.lru_cache with dictionary arguments

Using @functools.lru_cache with dictionary arguments Question: I have a method that takes (among others) a dictionary as an argument. The method is parsing strings and the dictionary provides replacements for some substrings, so it doesn’t have to be mutable. This function is called quite often, and on redundant elements so I figured that caching it …

Total answers: 9

Check for mutability in Python?

Check for mutability in Python? Question: Consider this code: a = {…} # a is an dict with arbitrary contents b = a.copy() What role does mutability play in the keys and values of the dicts? How do I ensure changes to keys or values of one dict are not reflected in the other? How …

Total answers: 7