Is it considered bad form to use a function as a dictionary key? For example:
def add(a, b):
return a + b
mydict = {add: "hello"}
Is it considered bad form to use a function as a dictionary key? For example:
def add(a, b):
return a + b
mydict = {add: "hello"}
Yes, that's perfectly valid. You could for instance use it to store a counter to how many times a function was called:
def hi():
print('hi')
funcs = {hi: 0}
print(funcs)
# {<function hi at 0x10fb39950>: 0}
for func in funcs:
func()
# hi
funcs[func] += 1
print(funcs)
# {<function hi at 0x10fb39950>: 1}
Functions are represented through instance of function
class:
>>> def f():
... pass
...
>>> f
<function f at 0x000001D397363E18>
>>> help(type(f))
class function(object)
| function(code, globals[, name[, argdefs[, closure]]])
So the function class is derived from object
class and inherits __hash__
method. The default implementation of __hash__
method in object
class computes hash using return value of id()
by rotating right 4 bits. The id()
of object is memory address.
So that's how functions get hash. Anything that has some immutable state can technically have hash.