executing a function/method from a variable

Carsten Haese carsten.haese at gmail.com
Sat Oct 17 04:35:42 CEST 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)

o = dummy(sys.argv[1])


Carsten Haese

More information about the Python-list mailing list