Skip to content

Instantly share code, notes, and snippets.

@cruepprich
Last active October 15, 2021 14:55
Show Gist options
  • Save cruepprich/fea548326d472e874fa16ffcb4b5c2cb to your computer and use it in GitHub Desktop.
Save cruepprich/fea548326d472e874fa16ffcb4b5c2cb to your computer and use it in GitHub Desktop.
[Dictionary to Control Function Calling] Use a dictionary instead of if-then
#!/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])
$ 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment