Finding the name of a function while defining it
alex23
wuwei23 at gmail.com
Thu Dec 27 20:25:12 EST 2012
On Dec 27, 11:31 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> Unfortunately this doesn't help if you actually need the function name
> *inside* the function
Here's an extension of Steven's original decorator that adds a
reference to the function itself into the function's globals, and then
composes a new function from the component parts:
import new
def IdentityAwareFunctionDecorator( fn ):
_globals = fn.__globals__
_globals['selffunc'] = fn
name_aware_func = new.function(
fn.__code__, _globals, fn.__name__, fn.__defaults__,
fn.__closure__ )
return name_aware_func
id = IdentityAwareFunctionDecorator
@id
def foo():
return selffunc.__name__
Unfortunately, it also only knows about the original function name, so
'bar = foo; bar()' will still give you 'foo'.
More information about the Python-list
mailing list