[Tutor] tricky eval() problem

Kent Johnson kent37 at tds.net
Fri Jul 22 21:56:04 CEST 2005

Marcus Goldfish wrote:
> Here's a noodler I could use some help on: I need a class that can
> call a user-specified function with arbitrary (unknown) parameter
> lists.  The trick, here, is that the user will dynamically specify the
> funciton to invoke, and each function may differ in the number of
> parameters passed during the call.  For instance, suppose I define two
> dummy functions with different calling signatures:
> def foo1(a1, a2, a3):
>    ...
> def foo2(a1):
>   ...
> Then I seek a class, Caller
> class Caller(object):
>    def execute(self, method, *parms):
>       # some way to execute method
> That can be used in the following manner:
>>>c = Caller();
>>>c.execute("foo1", 8, 9, 10)
>>>c.execute("foo2", "me")
> Any tips on tackling this?

Something like this:
def execute(self, method, *parms):
  fn = locals().get(method) or globals.get(method)
  if fn:

Seems like there should be a better way of looking up method but I can't think of it right now...if method is an instance method of Caller then you could use
  fn = getattr(self, method)
(which will raise AttributeError if there is no such method)


More information about the Tutor mailing list