Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if hashable
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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.
Reply
#3
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
(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/
Skaperen likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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.
buran likes this post
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020