Finding the name of a function while defining it

Steven D'Aprano steve+comp.lang.python at
Thu Dec 27 13:59:09 CET 2012

On Tue, 25 Dec 2012 22:11:28 -0500, Roy Smith wrote:

> I've only ever wanted the name.  If you need the actual function object,
> I suppose you might eval() the name, or something like that.

Oh look, I found a peanut! Let me get a 50lb sledgehammer to crack it 


Please do not use eval to retrieve the function object. It's slow, 
overkill, a bad habit to get into, and a security risk if the name you 
are eval'ing comes from an untrusted source.

Instead, look the name up in globals() or locals():

py> def spam():
...     return "NOBODY expects the Spanish Inquisition!"
py> name = "spam"
py> func = globals()[name]
py> func()
'NOBODY expects the Spanish Inquisition!'


More information about the Python-list mailing list