Re: executing a function/method from a variable

2009-10-17 Thread Terry Reedy
Yves wrote: What is the best way to execute a function which name is stored in a variable ? One standard way is a dict mapping names to function objects. >>> numfuncs = {'int':int, 'float':float} >>> f='int' >>> numfuncs[f]('33') 33 Since attributes gets mapped to a dict, this is similar to p

Re: executing a function/method from a variable

2009-10-17 Thread Yves
Carsten Haese wrote: Right now I use an eval, but I'm wondering if there isn't a better way: There's (almost) always a better way than using eval. Yes I agree, every time I use eval, I feel like the language is missing something, fair enough to shell type languages, but usually not the cas

Re: executing a function/method from a variable

2009-10-16 Thread Jon Clements
On Oct 17, 3:02 am, Yves 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

Re: executing a function/method from a variable

2009-10-16 Thread Carsten Haese
Yves wrote: > Right now I use an eval, but I'm wondering if there isn't a better way: There's (almost) always a better way than using eval. In this case, you should use getattr(). Here's your simplified example modified to use getattr: import sys class dummy(object): def __init__(self, arg):

executing a function/method from a variable

2009-10-16 Thread Yves
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 patte