Call variable as a function

Nick Coghlan ncoghlan at iinet.net.au
Fri Mar 4 10:45:59 EST 2005


Steve Holden wrote:
> There's always a way:
> 
>  >>> def test():
> ...   print "hello"
> ...
>  >>> var = "test"
>  >>> eval("%s()" % var)
> hello

I'd go with locals() for the simple case of a name lookup:

Py> def test():
...   print "Hi there!"
...
Py> var = "test"
Py> locals()[var]()
Hi there!

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list