Getting a function name from string

Steven D'Aprano steve at REMOVEMEcyber.com.au
Thu Nov 3 01:31:39 EST 2005


David Rasmussen wrote:

> If I have a string that contains the name of a function, can I call it? 
> As in:
> 
> def someFunction():
>     print "Hello"
> 
> s = "someFunction"
> s() # I know this is wrong, but you get the idea...

py> eval("someFunction()")
'Hello'
py> eval(s)()  # note the second pair of brackets
'Hello'

See also exec -- but before you use either eval or 
exec, make sure you are fully aware of the security 
implications. Whatever a user could do to your system 
by sitting down in front of it with a Python 
interactive session open and typing commands at the 
keyboard, they can also do remotely if you call exec on 
input they provide.

So you probably don't want to be calling exec on 
strings that you get from random users via a website.

It has been my experience that, more often than not, 
any time you think you want to evaluate strings, you 
don't need to.

For instance, instead of passing around the name of the 
function as a string:

s = "someFunction"
eval(s)()

you can pass around the function as an object:

s = someFunction  # note the lack of brackets
s()



-- 
Steven.




More information about the Python-list mailing list