Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 call func from dict
#1
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>
Quote
#2
foobar[command]()
mcmxl22 likes this post
Quote
#3
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.
Quote
#4
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'
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  compare output with dict anna 0 78 Aug-16-2019, 09:16 AM
Last Post: anna
  What is the use of call method and when to use it? everyday1 1 104 Jul-14-2019, 01:02 PM
Last Post: ichabod801
  I'm trying to figure out whether this is a method or function call 357mag 2 247 Jul-04-2019, 01:43 AM
Last Post: ichabod801
  API Call Gets 404 Error jimbone30 0 145 Jun-28-2019, 04:06 AM
Last Post: jimbone30
  API call returning list value of 'None' jimbone30 5 293 Jun-14-2019, 07:42 PM
Last Post: jimbone30
  Call a Function contained in a Tuple SamGer 7 347 Jun-14-2019, 05:00 PM
Last Post: ThomasL
  variable call back into an array yamifm0f 3 252 Jun-07-2019, 02:44 PM
Last Post: heiner55
  Why call import twice? Winfried 5 575 May-24-2019, 09:05 AM
Last Post: Winfried
  call dict object result key error lateublegende 2 235 May-15-2019, 01:08 PM
Last Post: lateublegende
  How can I change value of dict in list? Mike Ru 1 152 May-13-2019, 09:06 PM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)