Christoph's 2 Cents

A Backup for My Brain!

Python

Python: Use a Dictionary to Control Function Calling

Rather than using a long list of if-then or case statments, you can use a Python dictionary to control which function is called depending on an argument:

#!/usr/bin/env python3
from sys import argv

"""Example for using a dictionary to map function calls from
argument variables.

    Usage:
        fn_map.py this foo 
        fn_map.py that '{"one":"foo","two":"bar"}'
        fn_map.py other baz 
"""



# Three functions to do stuff
def do_this(thing):
    print(f"Hello from this {thing}")

def do_that(things):
    # In case some functions use different amounts of arguments, use keyword arguments
    dict_things = eval(things)
    print(f"Hello from that thing {dict_things['one']} and thing {dict_things['two']}")

def do_other(thing):
    print(f"Hello from other {thing}")

# Dictionary to define which argument calls which function.
# The dictionary key maps the command line argument to the 
# associated function.
functions_map = {
    "this" : do_this,
    "that" : do_that,
    "other": do_other,
}

# First argument is the function name
# Second argument is the function's argument
def main(fn,op):
    functions_map[fn](op)

if __name__ == "__main__":
    main(argv[1],argv[2])

Test:

$ fn_map.py this foo
Hello from this foo
$ fn_map.py that '{"one":"foo","two":"bar"}'
Hello from that thing foo and thing bar
$ fn_map.py other baz
Hello from other baz