Self function

Chris Rebert clp2 at rebertia.com
Tue May 5 02:46:58 EDT 2009


On Mon, May 4, 2009 at 11:08 PM, Steven D'Aprano
<steven at remove.this.cybersource.com.au> wrote:
> On Mon, 04 May 2009 17:54:50 -0400, Terry Reedy wrote:
>
>> bearophileHUGS at lycos.com wrote:
>>
>>> Another possible syntax:
>>>
>>> def fact(n):
>>>     return 1 if n <= 1 else n * return(n - 1)
>>>
>>> But I guess most people don't see this problem as important&common
>>> enough to justify changing the language.
>>
>> Actually, I would like a way to refer to the current function from
>> inside a function.  but I would like support in the language, so that
>> the compiler patched the code after the function object is created to
>> directly refer to the function object (or can the code object call the
>> code object?) without any name lookup at all.
>
> I don't know about avoiding name lookup, that smacks of deepest black
> magic, and Python doesn't usually do that. It does however do parlour
> tricks like `__name__` and `self`, suggests a solution.
>
> 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.

<snip entire excellent proposal text>

While I'm +0 on the proto-PEP, it doesn't currently address (or at
least rebut hard enough) the inevitable obvious naysayer argument
which will go along the lines of:

<devils_advocate>
Adding syntax is EVIL(tm) for it angers the Gods of Backwards
Compatibility, and this proposal is completely unnecessary because you
could instead just write:

def recursive(func):
    """We caved enough to allow this into functools."""
    def wrapper(*args, **kwds):
        return func(func, *args, **kwds)
    return wrapper
#####
from functools import recursive
@recursive
def spam(this, number_of_thy_counting):
    print " ".join([this.__name__.capitalize() + "!"]*number_of_thy_counting)

Which is not significantly more complex/longer/painful than learning
about __this__'s existence or typing the extra underscores and it
doesn't require any new syntax.

And the performance penalty for the proposed feature would actually be horrible!
And there would be much clashing with existing variable names, for
keywords are the Devil's work!
And your mother wears combat boots!
(etc...)
</devils_advocate>

You touch on this in "Is this really necessary?", but I think you're
going to prove more persuasively how drastically sweeter this syntax
sugar would be.

Cheers,
Chris
-- 
The Devil's Advocate-General
http://blog.rebertia.com



More information about the Python-list mailing list