Self function

Aaron Brady castironpi at
Tue May 5 22:02:47 CEST 2009

On May 5, 2:50 pm, Steve Howell <showel... at> wrote:
> On May 4, 11:08 pm, Steven D'Aprano
> <ste... at> wrote:
> > I propose a small piece of sugar. When a function is entered, Python
> > creates an ordinary local name in the function's local namespace, and
> > binds the function itself to that name. Two possibilities for the name
> > are `this` or `__this__`, analogous to `self` in methods and `__name__`
> > in modules.
> > If there is any support for this, I propose to send the following (long)
> > post to python-ideas. Feedback, corrections and suggestions welcome.
> I totally support this proposal.   I've definitely wasted time in the
> past trying to invent my own workarounds for the use cases you
> describe.
> Obviously, there will be some bikeshed debates on __this__ vs.
> __name__ vs. __func__, etc.  I don't have an opinion there, just want
> *something* handy for introspection, DRYness, etc.
> A more interesting question is whether __this__ would just always be
> there (that's my vote), or if you should have to apply a special
> decorator to get it (which I oppose, but I can see some merits).

Here is how to get the function into the function as an argument, and
still permit recursive calls onto it.

>>> def auto( f ):
...     def _inner( *ar, **kw ):
...             return f( g, *ar, **kw )
...     g= _inner
...     return g
>>> @auto
... def f( self, n ):
...     print( self, n )
...     return 1 if n== 1 else n* self( n- 1 )
>>> f(7)
<function _inner at 0x00BA0D68> 7
<function _inner at 0x00BA0D68> 6
<function _inner at 0x00BA0D68> 5
<function _inner at 0x00BA0D68> 4
<function _inner at 0x00BA0D68> 3
<function _inner at 0x00BA0D68> 2
<function _inner at 0x00BA0D68> 1

The function that is passed into the function is the decorated
function, not the original.  The decorator function is also returned
from the decorator calls, so both the external caller and the internal
caller are calling the same function, '_inner' in the sample, which
then back-calls the original.

Please stay tuned for the post-graduate lecture.  There will be time
for questions at the cookies-and-creme seminar afterward.

More information about the Python-list mailing list