Given a string - execute a function by the same name

Arnaud Delobelle arnodel at googlemail.com
Tue Apr 29 08:47:57 EDT 2008


On 29 Apr, 13:10, pyt... at bdurham.com wrote:
> Bruno,
>
> Thank you for your detailed analysis. I learned a lot about Python
> reading everyone's responses.
>
> For development I'm using #5: "globals().get("func")" because its
> seamless to add additional functionality.
>
> But when I release into production I'm going to shift to #3: "Place all
> my functions in dictionary and lookup the function to be called". This
> technique will allow me to precisely control the dynamic nature of my
> application.
>
> Thanks again to everyone who contributed on this thread.
>
> Regards,
> Malcolm

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!

--
Arnaud



More information about the Python-list mailing list