Reputation: 777
I am creating a python shell script that will allow the user to enter commands that output a string. But also some commands will call a function, like help, or exit I know python does not have a switch case so I am using a dictionary instead, as I do not want to use if and else statements
The problem:
The problem is I cannot use a function call inside the dictionary with the way I have it implemented as it expects to output a string, so when I enter help I get an error
#!/usr/bin/python
x = 0
while x == 0:
def helpCommand():
print "this will help you"
switcher = {
"url": " the url is: ... ",
"email": " my email is: ...",
"help": helpCommand,
"exit": exit,
}
choice = raw_input("enter your command choice: ")
def outputChoice(choice)
return switcher.get(choice)
print outputChoice(choice)
I tried to solve this problem by using function call instead, but now I get an error when trying to call a string
def outputChoice(choice)
return switcher[choice]()
TypeError: 'str' object is not callable
How to fix this problem ?
Upvotes: 1
Views: 7120
Reputation: 236
You can try to call the function, and if it fails, print the string. iirc this is the pythonic way - it is easier to ask for forgiveness then for permission (or in this case, the callable attribute).
def bar():
print 'foo'
gru = { 'dead': 'beef',
'foo' : bar}
for what in [ 'dead', 'foo']:
try:
gru[what]()
except TypeError:
print gru[what]
Upvotes: 1
Reputation: 55469
Djizeus's suggestion of callable()
makes this simple.
Your code organization is a bit odd. You shouldn't normally put function definitions inside a loop, since that causes the function to be redefined on every loop, which is pointless and inefficient.
Here's a modified version of your code, using Djizeus's suggestion.
#!/usr/bin/python
def helpCommand():
print "this will help you"
switcher = {
"url": " the url is: ... ",
"email": " my email is: ...",
"help": helpCommand,
"exit": exit,
}
def process_choice(choice):
item = switcher[choice]
if callable(item):
item()
else:
print item
x = 0
while not x:
choice = raw_input("Enter your command choice: ")
process_choice(choice)
#other stuff that modifies `x`
If nothing in the loop actually modifies x
, you can just get rid of that and make the loop into:
while True:
choice = raw_input("Enter your command choice: ")
process_choice(choice)
Upvotes: 3