Mr Fruit
Mr Fruit

Reputation: 13

Is it correct to call multiple functions using a dictionary?

In an attempt to reduce excess conditions to call functions, I thought of calling them through a dictionary

Code with excess conditions

command = input()

def do1():
    print('do nothing')

def do2():
    print('do nothing')

def do3():
    print('do nothing')

if command == '1':
    do1()

elif command == '2':
    do2()

elif command == '3':
    do3()

else:
    pass

Now in dictionary form

command = input()

def do1():
    print('do nothing')

def do2():
    print('do nothing')

def do3():
    print('do nothing')

functions = {
    '1':do1,
    '2':do2,
    '3':do3
}

functions[command]()

This reduces the number of lines and makes the code cleaner, but is this the correct way?

Upvotes: 0

Views: 220

Answers (3)

Oliver Richardson
Oliver Richardson

Reputation: 281

In addition to being cleaner, this is not uncommon, and is fast (faster than the sequence of if's because only one test is required), for the same reason network switches are fast.

This is also the closest you can get to using a case or switch statement in python. If you plan on writing a lot of code that uses the function table, you will probably want to also write a thin interface layer on top; it will allow you to later tweak the implementation, and you get to use things like default arguments. For instance, if you write the following code:

def do():
    print('do nothing')

functions = dict('1'=do, '2'=do, '3'=do)

def execute(*args, command=0):
    return functions[command](*args)

then you could later replace execute with a different function table that looks things up with a more specialized data structure, like:

# def do():
#    print('do nothing')
# functions = dict('1'=do, '2'=do, '3'=do)

_crazy_datastructure = ParallelizedFibonacciaHeapTreeGraphThing()

def execute(*args, command='1'):
    return _crazy_datastructure.perform_command(command, preprocess(*args))

If the number of functions in the table is very large or has some interesting substructure, an alternate implementation may be more efficient. Moreover, because you call the function with execute(command='1') it is more legible also.

Upvotes: 0

Javad Rezaei
Javad Rezaei

Reputation: 1110

yes, this is ok. This is a type of caller dispatch which you can connect command option to functions and translate command code into executable code.

some example

reference to other caller dispatch methods

Upvotes: 0

Jab
Jab

Reputation: 27515

There is no reason you can't just use an if statement here. Although your code will run do() no matter what as your else statement also runs do.

My assumption though is you want to run do() only if command is 1-5 otherwise do something else. In this case you could just employ a simple if statement:

command = input()

def do():
    print('do nothing')

if command in set('1234'):
    do()
else:
    do_something_else()

Upvotes: 1

Related Questions