dynamic func. call

  • Thread starter Aljosa Mohorovic
  • Start date
A

Aljosa Mohorovic

can i do something like this:

s = "myFunction"
a = s() # equals to: a = myFunction()
 
O

Ola Natvig

Aljosa said:
can i do something like this:

s = "myFunction"
a = s() # equals to: a = myFunction()

a = locals()[x]()

locals() returns a dictionary with string keys that you can use
 
T

Tim Jarman

Aljosa said:
can i do something like this:

s = "myFunction"
a = s() # equals to: a = myFunction()

Functions are first-class objects in Python, so you can do:

def myFunction():
# whatever

which creates a function object and binds the name myFunction to it. Then:

s = myFunction

just binds the name s to your function object, and therefore:

a = s()

is the same as:

a = myFunction()
 
D

Duncan Booth

Try this:

def myfunc():
print "helo"

s = "myfunc()"
a = eval(s)

No, please don't try that. Good uses for eval are *very* rare, and this
isn't one of them.

Use the 'a = locals()[x]()' suggestion (or vars() instead of locals()), or
even better put all the functions callable by this method into a class and
use getattr() on an instance of the class.

A Pythonic way to do this sort of thing is to put all the functions that
are callable indirectly into a class and give them names which contain a
prefix to make it obvious that they are callable in this way and then add
the prefix onto the string:

class C:
def command_myfunc(self):
return 42

def default_command(self):
raise NotImplementedError('Unknown command')

def execute(self, s):
return getattr(self, 'command_'+s, self.default_command)()

commands = C()
print commands.execute('myfunc')

That way you can be quickly tell which functions can be called indirectly
and which can't; you can control what happens when no suitable function
exists; and you can easily extend the functionality by subclassing your
base class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,219
Messages
2,571,117
Members
47,730
Latest member
scavoli

Latest Threads

Top