dynamic func. call
Duncan Booth
duncan.booth at invalid.invalid
Sun Feb 6 06:26:58 EST 2005
ajikoe at gmail.com wrote:
> 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.
More information about the Python-list
mailing list