4

I have some predefined functions with me, like : addhost, edithost, deletehost.

Now based on some param received, I have to call one of the above functions. Now the value of param is same as one of the above functions.The type of param is str.

For Example: If param is 'addhost', then I should be able to call addhost(). But when I do it directly, It gives me the error as 'str' object is not callable How should I call the appropriate function based on param received ??

P.S. I dont want to use conditionals, I only want to go with something like lambda functions.

dotslash
  • 2,041
  • 2
  • 16
  • 15
  • 4
    possible duplicate of [Calling a function from a string with the function's name in Python](http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python) – Korem Jun 20 '14 at 19:16
  • 3
    This is a bad idea; put your functions in a dictionary keyed with the strings you want to use to access them. – jonrsharpe Jun 20 '14 at 19:19
  • *Where/how* is this function defined? In a module? A function within the current scope? A method? (The linked question seems to cover most cases..) – user2864740 Jun 20 '14 at 19:32
  • str='os.unlink("this program")' – stark Jun 20 '14 at 20:46

3 Answers3

1

Simple call eval:

>>> def addhost():
...  print "Add host"
... 
>>> def edithost():
...  print "Edit host"
... 
>>> def callstr(str):
...  f = eval(str)
...  f()
... 
>>> callstr("addhost")
Add host
>>> callstr("edithost")
Edit host
>>> 

If you want to use lambda:

>>> callstr2 = lambda x:eval(x)()
>>> callstr2("edithost")
Edit host
>>> callstr2("addhost")
Add host
Magnun Leno
  • 2,728
  • 20
  • 29
  • eval doesn't allow to use the return value of the function. – Korem Jun 20 '14 at 19:20
  • I'm assuming he doesn't need to return anything. – Magnun Leno Jun 20 '14 at 19:21
  • 1
    If using eval [yech], it would be more clear to - `f = eval("addhost"); f()`. That is, rely on the fact that the function *is* a value. This observation also allows for approaches *without* eval - i.e. lookup-tables like dictionaries [yay] including globals/locals [yech], and other container objects (even modules) via attributes/properties [yay] – user2864740 Jun 20 '14 at 19:30
  • 1
    Thanks user2864740, I'm using your suggestion to improve my answer. – Magnun Leno Jun 20 '14 at 19:45
0

I like jonrsharpe's idea and have used it before. It's simple to code:

If you want to optimize things about, create the function dictionary outside of callit.

def fun1():
    return 1

def fun2():
    return 2

def nofun():
    raise ValueError('Unknown function')

def callit(funname):
    d = dict(fun1=fun1, fun2=fun2)
    fun = d.get(funname, nofun)
    return fun()

callit('fun1')
callit('badbadbad')
jaime
  • 2,234
  • 1
  • 19
  • 22
-1

I would lean towards the getattr method as described here: https://stackoverflow.com/a/3071/3757019

Community
  • 1
  • 1
Robert Ekendahl
  • 277
  • 2
  • 11