Default Value
Rick Johnson
rantingrickjohnson at gmail.com
Fri Jun 21 22:40:46 EDT 2013
On Friday, June 21, 2013 8:38:21 PM UTC-5, Ian wrote:
> The answer to this conundrum is staring you in the face.
Thanks for posting a solution for this. Not sure if i'll
ever need it, but nice to know.
> Note that the TypeError complains that you passed it an
> "unhashable" type, and not that you passed it a "mutable"
> type. If you want to take a mutable type and make it
> hashable, just add a __hash__ method.
>
> class HashableList(list):
> def __hash__(self):
> return 42
> >>> d = dict()
> >>> hl = HashableList(range(5))
> >>> hl2 = HashableList(range(6, 10))
> >>> d[hl] = 10
> >>> d[hl2] = 20
> >>> d
> {[0, 1, 2, 3, 4]: 10, [6, 7, 8, 9]: 20}
>
> Additionally, instances of user-defined classes are, by
> default, both mutable and hashable. This is safe because
> equality and hashing for such objects are by default based
> on identity. If you override the __eq__ method though,
> then you lose hashability unless you explicitly override
> __hash__ as well.
Hey, you went above and beyond to provide that last bit of info.
Thanks again!
More information about the Python-list
mailing list