8

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"}
101
  • 8,514
  • 6
  • 43
  • 69
ViralSpiral
  • 83
  • 1
  • 1
  • 4

2 Answers2

15

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}
101
  • 8,514
  • 6
  • 43
  • 69
3

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.

Shital Shah
  • 63,284
  • 17
  • 238
  • 185