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 case in python. That's why I asked,

In this case, you
should use getattr().

Right ! I always forget about get/set attr. Thanks !


Here's your simplified example modified to use getattr:
Tried it, and it works if we remove the self from the name of course:

import sys


class dummy(object):
  def __init__(self, arg):
    self.todo = 'print' + arg;

  def printa(self):
    print 'a'

  def printb(self):
    print 'b'

  def doit(self):
    #func = getattr(self, self.todo)
    #func()
    getattr(self, self.todo)()


o = dummy(sys.argv[1])
o.doit()

Thanks again,

--
Yves.
http://www.SollerS.ca
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to