Call variable as a function

Steve Holden steve at holdenweb.com
Thu Mar 3 17:06:18 EST 2005


Chmouel Boudjnah wrote:
> Hey,
> 
> It's look simple for most of the people here but i can't figure out to 
> that.
> 
> If i have :
> 
> def test():
>     print "foo"
> 
> and:
> 
> var = "test"
> 
> how do i call function test from var, kind of ${$var} in some others 
> languages (or eval())
> 
There's always a way:

 >>> def test():
...   print "hello"
...
 >>> var = "test"
 >>> eval("%s()" % var)
hello

But it depends how you are creating the reference to the function. The 
above is required if all you have is a string, but it would also be 
possible to set the variable to the function rather than the function's 
name:

 >>> var = test
 >>> var()
hello
 >>>

Hope this helps.

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005                      http://www.pycon.org/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list