jfa
jfa

Reputation: 1101

Syntax for a dictionary of functions?

I'm trying to test the concept of using a dictionary to call functions, since python doesn't have a case switch and I don't want write out a slew of if statements. However, whenever I try to put the function in to a dict, I get the following:

def hello():
...    print 'hello world'
... 
>>> fundict = {'hello':hello()}
hello world
>>> fundict
{'hello': None}
>>> fundict = {'hello':hello}
>>> fundict['hello']
<function hello at 0x7fa539a87578>

How do I call fundict so it runs hello() when called? I looked at a few other stack questions, but I'm not getting the hang of the syntax, or perhaps not understanding what it's doing that it's giving me an address.

Upvotes: 3

Views: 111

Answers (2)

Stan
Stan

Reputation: 6225

All objects in Python are first-class (read great article by Guido). That basically means that you can assign them to variables, compare them, pass them as arguments, etc. For example:

class C(object):
    pass

class_c = C

# they are the same
assert class_c is C

# they are both instance of C
instance1 = class_c()
instance2 = C()

def f():
    pass

function_f = f

# again, they are the same
assert function_f is function

# both results are results from function f
result1 = f()
result2 = function_f()

The same applies also for instance methods (both bound and unbound), static methods and class methods. And because you can consider them as variables, you can put them into a dictionary:

fundict = {'hello' : hello}

And later use them:

function = fundict['hello']
function()

# or less readable:
fundict['hello']()

The weird output you are having is the same thing you would see with the original hello:

>>> fundict['hello']
<function hello at 0x7fa539a87578>
>>> hello
<function hello at 0x7fa539a87578>

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121296

You call the returned object:

fundict['hello']()

You are storing function objects correctly; what is stored is just a reference, just like the original name hello is a reference to the function. Simply call the reference by adding () (with arguments if the function takes it).

Demo:

>>> def hello(name='world'):
...     print 'hello', name
... 
>>> hello
<function hello at 0x10980a320>
>>> fundict = {'hello': hello}
>>> fundict['hello']
<function hello at 0x10980a320>
>>> fundict['hello']()
hello world
>>> fundict['hello']('JFA')
hello JFA

Upvotes: 7

Related Questions