executing a function/method from a variable

Jon Clements joncle at googlemail.com
Sat Oct 17 04:43:29 CEST 2009


On Oct 17, 3:02 am, Yves <y... at zioup.com> wrote:
> What is the best way to execute a function which name is stored in a variable ?
>
> Right now I use an eval, but I'm wondering if there isn't a better way:
>
> Here is a simplified example, but what I use this for is to parse a formated
> text file, and execute a different method depending on the pattern:
>
> import sys
>
> class dummy(object):
>    def __init__(self, arg):
>      self.todo = 'self.print' + arg;
>
>    def printa(self):
>      print 'a'
>
>    def printb(self):
>      print 'b'
>
>    def doit(self):
>      #k = eval(self.todo)
>      #k()
>
>      eval(self.todo)()
>
> o = dummy(sys.argv[1])
> o.doit()
>
> Thanks.
>
> --
> Yves.http://www.sollers.ca/

Depending on your exact requirements, take a look at pyparsing.

Has (from my experience) a small learning curve and is a
useful library addition!

It could well be overkill, but not knowing your exact requirements,
it'd be worth looking at anyway.

Jon.



More information about the Python-list mailing list