Accessing func_name from inside a function
aleaxit at yahoo.com
Sun Mar 26 02:19:54 EST 2006
Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> "James Thiele" <jamesthiele.usenet at gmail.com> writes:
> > I'd like to access the name of a function from inside the function.
> A function, like most other objects in Python, can have any number of
> names bound to it without the object being informed. Any of those
Yes, but, quite independent of the 0+ names BOUND to the object,
function objects, like class and module objects, have ONE "true" name
(which may or may not coincide with one of those bound to the object, if
any) -- the special attribute __name__ (AKA func_name for function
objects only, but I'll stick with __name__ which applies uniformly).
Code in a module can get the module's name by simply accessing global
variable __name__. I see nothing untowards in a desire to access
__name__ from code within a function or a class body, getting the name
of the function or the class respectively rather than the name of the
module they're in... it's just not implemented that way (and can't be
changed until Python 3.0 for backwards compatibility). But proposals for
3.0 can be entertained.
Personally, I'd rather have a 3.0 keyword referring to "the current
object" (module for module toplevel code, class for classbody toplevel
code, function for code within a function) -- say for the sake of
argument the keyword is 'current'; this would allow current.__name__ to
have the obvious meaning, and would also allow a few more neat things
(such as natural access to current.__doc__).
But if the OP is looking for a Python 2.* solution, then sys._getframe
or module inspect are the only way to go, be they "ugly" as he considers
them, or not.
More information about the Python-list