Self-identifying functions and macro-ish behavior
Duncan Booth
duncan.booth at invalid.invalid
Wed Feb 15 03:30:58 EST 2006
Michael wrote:
> def func2():
> <do some stuff 2>
> print <self-name>
> return True
>
> I imagine this means things like closures which I'm not familiar with
> (I'm not a CS person). In this case, each function is part of a class,
> so I imagine I can take a dir() of the class if necessary.
Use the inspect module to find out what you need.
>
> This leads into my next related question, which is How do I get some
> sort of macro behavior so I don't have to write the same thing over and
> over again, but which is also not neatly rolled up into a function,
> such as combining the return statements with a printing of <self-name>?
By rolling it up neatly in a function?
>>> def printcaller():
print inspect.stack()[1][3]
return True
>>> def func1():
return printcaller()
>>> func1()
func1
True
But remember this prints the name under which the function was created, not
the name of the variable in which it is stored:
>>> func2 = func1
>>> func2()
func1
More information about the Python-list
mailing list