Can a function access its own name?

Bengt Richter bokr at oz.net
Sun Nov 20 01:43:31 EST 2005


On Sat, 19 Nov 2005 23:30:32 -0500, Mike Meyer <mwm at mired.org> wrote:

>bobueland at yahoo.com writes:
>> Thanks Diez and Peter,
>> Just what I was looking for. In "Library Reference" heading
>> 3.11.1 Types and members
>> Running this yields the result
>>
>>     cap(s, n)
>
>You've now got three solutions. They'll work fine most of the time,
>but can't be trusted in general. Binding a name to a function doesn't
>change the name that these solutions return, and the name they return
>may no longer be bound to said function. Just a warning.
>
But the one buried in co_name seems to persist
(barring byte code munging in the decorator ;-)

 >>> def fren(newname='newname'):
 ...     def fren(f):
 ...         f.__name__ = newname
 ...         return f
 ...     return fren
 ...
 >>> @fren('bar')
 ... def foo():pass
 ...

Could have done that manually, but just playing.
Ok, rebind foo and remove the old name, for grins
 >>> baz = foo
 >>> del foo

See what we've got
 >>> dir()
 ['__builtins__', '__doc__', '__name__', 'baz', 'fren']

Check name(s) ;-)
Local binding to the function object first:
 >>> baz
 <function bar at 0x02EEADF4>

Its outer name:
 >>> baz.func_name
 'bar'

Its def name:
 >>> baz.func_code.co_name
 'foo'

Regards,
Bengt Richter



More information about the Python-list mailing list