Using a function as a dictionary key

Is it bad form to use a function as a dictionary key? For example:

def add(a, b):
    return a + b

mydict = {add: "hello"}

      

+4


source to share


2 answers


Yes, that is perfectly true. For example, you can use it to store a counter of how many times a function has been 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}

      



However, this is a bit of a backward way of doing things. It would be much more common to use a simpler type as the key of a dictionary, such as a string or an integer.

+5


source


Functions are exposed through an instance of the class function

:

>>> def f():
...   pass
...
>>> f
<function f at 0x000001D397363E18>
>>> help(type(f))

class function(object)
 |  function(code, globals[, name[, argdefs[, closure]]])

      



Thus, a function class is derived from a class object

and inherits a method __hash__

. The default implementation of the method __hash__

in the class object

computes the hash using the return value id()

by rotating the right 4 bits . id()

object is a memory address.

So how do the functions get the hash. Anything that has an immutable state can technically have a hash.

0


source







All Articles