Torin M.
Torin M.

Reputation: 533

How to use dictionary to execute multiple functions?

I have a dictionary switcher in this piece of code:

def a():
    print("A")

def b():
    print('B')


def switch(mode):
    switcher = {
        'a': a,
        'b': b,
        'ab': (a, b)
    }
    switcher[mode]()

switch('a')

If I use switch('a') I get the output:

A

So far using switch('ab') returns an error:

TypeError: 'tuple' object is not callable.

How would I be able to execute both a and b using switch('ab')?

Upvotes: 3

Views: 1932

Answers (3)

user9730851
user9730851

Reputation: 86

You could handle the third case (where it is a tuple of functions) separately:

def a():
    print("A")
def b():
    print('B')
def switch(mode):
    switcher = { 'a': a, 'b': b, 'ab': (a, b) }
    if type(switcher[mode]) is tuple:
         for func in switcher[mode]:
            func()
    else:
         switcher[mode]()

switch('ab')

Upvotes: 1

s3cur3
s3cur3

Reputation: 3025

The error here is caused by your dictionary storing two different types of things: the values associated with keys 'a' and 'b' are "just" a function, while the value for 'ab' is a tuple of functions.

Based on the principle of idiomatic Python code asking forgiveness, not permission, I suggest trying to call the element of the dictionary as "just" a function, and if that fails, trying to iterate over each function in the tuple.

def switch(mode):
    switcher = {
        'a': a,
        'b': b,
        'ab': (a, b)
    }
    try:
        switcher[mode]()
    except TypeError:  # must be a tuple of functions
        for fn in switcher[mode]:
            fn()

Upvotes: 2

mad_
mad_

Reputation: 8273

By introducing a for loop for the iterable

def a():
    print("A")

def b():
    print('B')


def switch(mode):
    switcher = {
        'a': a,
        'b': b,
        'ab': (a, b)
    }
    for i in mode:
        switcher[i]()

switch('ab')

Output

A
B

Upvotes: 6

Related Questions