10

I have several functions such as:

def func1():
    print 'func1'

def func2():
    print 'func2'

def func3():
    print 'func3'

Then I ask the user to input what function they want to run using choice = raw_input() and try to invoke the function they choose using choice(). If the user input func1 rather than invoking that function it gives me an error that says 'str' object is not callable. Is their anyway for me to turn 'choice' into a callable value?

Isaac Scroggins
  • 101
  • 1
  • 1
  • 3

3 Answers3

12

The error is because function names are not string you can't call function like 'func1'() it should be func1(),

You can do like:

{
'func1':  func1,
'func2':  func2,
'func3':  func3, 
}.get(choice)()

its by mapping string to function references

side note: you can write a default function like:

def notAfun():
  print "not a valid function name"

and improve you code like:

{
'func1':  func1,
'func2':  func2,
'func3':  func3, 
}.get(choice, notAfun)()
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • for OP: its would be an example of [**run time polymorphism**](http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29#Subtype_polymorphism_.28or_inclusion_polymorphism.29)!! in Python – Grijesh Chauhan May 18 '13 at 14:48
4

If you make a more complex program it is probably simpler to use the cmd module from the Python Standard Library than to write something.
Your example would then look so:

import cmd

class example(cmd.Cmd):
    prompt  = '<input> '

    def do_func1(self, arg):
        print 'func1 - call'

    def do_func2(self, arg):
        print 'func2 - call'

    def do_func3(self, arg):
        print 'func3 - call'

example().cmdloop()

and an example session would be:

<input> func1
func1 - call
<input> func2
func2 - call
<input> func3
func3 - call
<input> func
*** Unknown syntax: func
<input> help

Undocumented commands:
======================
func1  func2  func3  help

When you use this module every function named do_* will be called when the user inputs the name without the do_. Also a help will be automatically generated and you can pass arguments to the functions.

For more informations about this look into the Python manual (here) or into the Python 3 version of the manual for examples (here).

TobiMarg
  • 3,667
  • 1
  • 20
  • 25
1

You can use locals

>>> def func1():
...     print 'func1 - call'
... 
>>> def func2():
...     print 'func2 - call'
... 
>>> def func3():
...     print 'func3 - call'
... 
>>> choice = raw_input()
func1
>>> locals()[choice]()
func1 - call
Alexey Kachayev
  • 6,106
  • 27
  • 24