Finding the name of a function while defining it
Roy Smith
roy at panix.com
Tue Dec 25 22:11:28 EST 2012
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.
More information about the Python-list
mailing list