executing a function/method from a variable

Carsten Haese carsten.haese at gmail.com
Fri Oct 16 22:35:42 EDT 2009


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):
    self.todo = "print"+arg

  def printa(self):
    print 'a'

  def printb(self):
    print 'b'

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

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

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net




More information about the Python-list mailing list