Given a string - execute a function by the same name

python at bdurham.com python at bdurham.com
Tue Apr 29 11:35:30 EDT 2008


Arnaud,

Just when I thought my solution couldn't get any better :)

Thanks for that great tip and for an excellent demonstration of using a
decorator.

Regards,
Malcolm

<snip>
You could avoid #5 from the start using a decorator:

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>



More information about the Python-list mailing list