Today we’ll be talking about jump tables. These are structures containing functions, usually lists or dictionaries. We can choose the function we need using its index or key.
Jump tables can contain both named and anonymous functions. The former are created by means of the def statement. The latter are created by means of lambda expressions.
If you want to learn more about lambda expressions, I have an article about them, so feel free to read it.
OK, let’s see a jump table in action. First let’s create some simple functions and store them in a list, along with some lambda functions:
def sing(title, author):
return f"singing '{title}' by {author}"
def read(title, author):
return f"reading '{title}' by {author}"
def act(title, author):
return f"acting in '{title}' by {author}"
functions = [sing,
read,
act,
lambda title, author: f"doing stuff with '{title}' by {author}"]
print(functions[0]("Unexpected Visitors", "Rose Parker"))
print(functions[1]("Unexpected Visitors", "Rose Parker"))
print(functions[2]("Unexpected Visitors", "Rose Parker"))
print(functions[3]("Unexpected Visitors", "Rose Parker"))
The output is:
singing 'Unexpected Visitors' by Rose Parker
reading 'Unexpected Visitors' by Rose Parker
acting in 'Unexpected Visitors' by Rose Parker
doing stuff with 'Unexpected Visitors' by Rose Parker
We can choose any function from the list. We could also iterate over the functions in a for loop.
Now let’s have an example with a dictionary:
def sing():
return "la la la"
def bark():
return "woof woof"
def speak():
return "blah, blah, blah"
functions = {"morning": sing,
"afternoon": bark,
"evening": speak,
"night": lambda: "zzz"}
time = input("What time of the day is it now?: ")
print(f"This is what I can hear behind the wall: {functions[time]()}")
The output:
What time of the day is it now?: night
This is what I can hear behind the wall: zzz
Here’s the video version of the article: