Given a string - execute a function by the same name

python at bdurham.com python at bdurham.com
Thu May 8 12:47:47 EDT 2008


Andrew,

> > I'm parsing a simple file and given a line's keyword, would like to call the equivalently named function.

> No, actually, you wouldn't :-)  Doing so means that if your programs input specification ever changes, you have to rename all of the relevant functions. Moreover, it leaves open the possibility that you might wind up calling a function you didn't intend.

I'm using Arnaud Delobelle's technique (see below) to insure that only
the appropriate methods are called. A great, practical example of a
decorator.

<snip>
functions = {}

def register(func):
    functions[func.__name__] = func
    return func

@register
def foo(): print "Foo!"

@register
def bar(): print "Bar!"

>>> functions
{'foo': <function foo at 0x6f2f0>, 'bar': <function bar at 0x6f330>}
>>> functions['bar']()
Bar!
</snip>

Thanks for your feedback,

Malcolm



More information about the Python-list mailing list