Finding the name of a function while defining it

Abhas Bhattacharya abhasbhattacharya2 at gmail.com
Thu Dec 27 02:26:36 EST 2012


On Wednesday, 26 December 2012 08:41:28 UTC+5:30, Roy Smith  wrote:
> In article <c9548d77-ccc3-4b47-b84b-9a9f0c2852ce at googlegroups.com>,
> 
>  Abhas Bhattacharya <abhasbhattacharya2 at gmail.com> wrote:
> 
> 
> 
> > While I am defining a function, how can I access the name (separately as 
> 
> > string as well as object) of the function without explicitly naming 
> 
> > it(hard-coding the name)?
> 
> > For eg. I am writing like:
> 
> > def abc():
> 
> >     #how do i access the function abc here without hard-coding the name?
> 
> 
> 
> Do you need it at compile-time, or is it good enough to have the name a 
> 
> run-time?  Assuming the latter, then I'm thinking the traceback module 
> 
> is your friend.  Call traceback.extract_stack() and pull off the last 
> 
> frame in the stack.  The function name will be in there.
> 
> 
> 
> There may be a cleaner way, but that's what I've done in the past.
> 
> 
> 
> 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.

I need it compile-time.
During run-time, I can always use: function_name.__name__ (although that's kind of lame because it returns "function_name"). But if the function itself contains print(__name__) and I call the function, it returns __main__ (yes, __main__ itself, not the string "__main__") (which is the calling function).



More information about the Python-list mailing list