Dictionary functions
python - Using a dictionary to select function to execute - Stack Overflow
syntax - Why store a function inside a python dictionary? - Software Engineering Stack Exchange
functions as values in python dictionaries
Videos
Simplify, simplify, simplify:
def p1(args):
whatever
def p2(more args):
whatever
myDict = {
"P1": p1,
"P2": p2,
...
"Pn": pn
}
def myMain(name):
myDict[name]()
That's all you need.
You might consider the use of dict.get with a callable default if name refers to an invalid functionโ
def myMain(name):
myDict.get(name, lambda: 'Invalid')()
(Picked this neat trick up from Martijn Pieters)
Simplify, simplify, simplify + DRY:
tasks = {}
task = lambda f: tasks.setdefault(f.__name__, f)
@task
def p1():
whatever
@task
def p2():
whatever
def my_main(key):
tasks[key]()
Using a dict let's you translate the key into a callable. The key doesn't need to be hardcoded though, as in your example.
Usually, this is a form of caller dispatch, where you use the value of a variable to connect to a function. Say a network process sends you command codes, a dispatch mapping lets you translate the command codes easily into executable code:
def do_ping(self, arg):
return 'Pong, {0}!'.format(arg)
def do_ls(self, arg):
return '\n'.join(os.listdir(arg))
dispatch = {
'ping': do_ping,
'ls': do_ls,
}
def process_network_command(command, arg):
send(dispatchcommand)
Note that what function we call now depends entirely on what the value is of command. The key doesn't have to match either; it doesn't even have to be a string, you could use anything that can be used as a key, and fits your specific application.
Using a dispatch method is safer than other techniques, such as eval(), as it limits the commands allowable to what you defined beforehand. No attacker is going to sneak a ls)"; DROP TABLE Students; -- injection past a dispatch table, for example.
@Martijn Pieters did a good job explaining the technique, but I wanted to clarify something from your question.
The important thing to know is that you are NOT storing "the name of the function" in the dictionary. You are storing a reference to the function itself. You can see this using a print on the function.
>>> def f():
... print 1
...
>>> print f
<function f at 0xb721c1b4>
f is just a variable that references the function you defined. Using a dictionary allows you to group like things, but it isn't any different from assigning a function to a different variable.
>>> a = f
>>> a
<function f at 0xb721c3ac>
>>> a()
1
Similarly, you can pass a function as an argument.
>>> def c(func):
... func()
...
>>> c(f)
1
I was wondering is there anyway in python that when I create a dictionary in python say
calculations = {"add":add(),"subtract":subtract(),"multiple":multiply()}
that it only calls the functions when I do something like
calculations["add"] instead of calling all the functions initially when the code runs