Python Forum
if hashable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: if hashable (/thread-40788.html)



if hashable - Skaperen - Sep-24-2023

a function is getting a value that is expected to be the key where another function stores an object into a dictionary, or replaces on there if it already exists. it is possible to get an unhashable value that can't be a dictionary key, for which this function needs to output a custom error message to explain what is wrong. so this function needs to do its own test of the value. there seems to be two simple ways to carry out this test. both raise TypeError if the key is unhashable. is there any reason to choose one over the other (name is the argument it gets the key value in)?

1.
hash(name)
2.
{name:0}
i thought of doing number 2 above before i remembered the builtin hash() function. which way is better?


RE: if hashable - Gribouillis - Sep-24-2023

You could use collections.abc.Hashable

>>> from collections.abc import Hashable
>>> isinstance('spam', Hashable)
True
>>> isinstance([], Hashable)
False
Well, thinking again, it doesn't seem to work well for what you want to do
>>> from collections.abc import Hashable
>>> isinstance((1, []), Hashable)
True
>>> {(1, []): 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Then a reason to prefer hash() over the dict is that it doesn't attempt to build a dictionary instance.


RE: if hashable - Skaperen - Sep-24-2023

things like that, building a dict instance (then destructing it), could be costly. that is some of my concern. and it makes the code less obscure ... probably more pythonic.


RE: if hashable - buran - Sep-25-2023

(Sep-24-2023, 01:14 AM)Skaperen Wrote: for which this function needs to output a custom error message to explain what is wrong. so this function needs to do its own test of the value.
No, it does not need to do test of the value, use try/except instead to gracefully handle the error.
https://docs.python.org/3/glossary.html#term-EAFP
https://realpython.com/python-lbyl-vs-eafp/


RE: if hashable - Skaperen - Sep-25-2023

i learned this as EAFF back in my mainframe days (when i met Grace Hopper in person). i'll try to refer to it as EAFP from now on. actually i learned the longer acronym, EtAFFTtAFP or EAFFTAFP. back then.