Python Forum

Full Version: call func from dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how do I call functions from a dictionary?
def foo():
    print('foo')

def bar():
    print('bar')

foobar = {
    'foo': foo,
    'bar': bar
}

command = input('foo or bar, Choose one. ')

foobar[command] # returns nothing.
print(foobar[command]) # prints memory location.
Output:
PS C:\Users\User\Desktop> python test.py foo or bar, Choose one. foo <function foo at 0x0380C030> PS C:\Users\User\Desktop>
foobar[command]()
I'm still not getting this. It works when I call functions from within the same program but if I import the functions then store them in a dict they get ran even without being called. Why?
I am trying to modify this program to get rid of all the if\elif\else statements.
Use if __name__ == '__main__':
# my_nodule
def foo():
    print('foo')

def bar():
    print('bar')

foobar = {
    'foo': foo,
    'bar': bar
}

if __name__ == '__main__':
    command = input('foo or bar, Choose one. ')
    foobar[command]()
No do not get run on import.
>>> import my_module

>>> command = input('foo or bar, Choose one. ')
foo or bar, Choose one. bar

>>> my_module.foobar[command]()
bar
Another way that i think is cleaner as avoid the the somewhat strange call [something]() and do error checking with get().
# my_module1.py
def spam():
    return 'spam'

def eggs():
    return 'eggs'

def switch_case(user_choice):
    return {
        'foo': spam(),
        'bar': eggs(),
    }.get(user_choice, f'<{user_choice}> Not in Record')
>>> import my_module1

>>> command = input('foo or bar, Choose one. ')
foo or bar, Choose one. bar
>>> my_module1.switch_case(command)
'eggs'

>>> command = input('foo or bar, Choose one. ')
foo or bar, Choose one. car
>>> my_module1.switch_case(command)
'<car> Not in Record'