[Python-ideas] Mitigating 'self.' Method Pollution

Steven D'Aprano steve at pearwood.info
Sat Jul 11 03:21:29 CEST 2015


On Fri, Jul 10, 2015 at 03:31:28PM -0700, Michael Hewitt wrote:
> Last night I made a post to the neopythonic blog proposing a Python 3.x
> feature that Guido asked me to forward to this alias.  For the full
> background, see the link to my post below.  For brevity, I will simply
> submit the proposal here.  The specific problem I am addressing is the
> pollution of Python methods by 'self.' to reference fields.  Here is the
> proposal:
> 
> The name of the first parameter to a method can be used to scope subsequent
> variable references similar to the behavior of 'global'.

At first, I was all "not another poorly thought out implicit self 
proposal!", but then I read it and thought, "you know, of all the 
implicit self proposals I've read, this is the first one that I might be 
able to get behind".

It's clever. Possibly too clever. You cleverly avoid needing to 
introduce a new keyword to the language by using the name of the first 
parameter as the pseudo-keyword. I like that, but I think it may be a 
little to radical for the conservatives in the Python community. We tend 
to suffer from a sort of anti-"not invented here" syndrome: unless 
something has been tried and tested in at least one other language, and 
preferably a dozen, we don't want to know about it. It would help your 
case if you can show a language that already has this feature.

Personally, I don't think of "self" as pollution at all. It's nice and 
explicit and helps readability. But if people wanted to avoid using it, 
and I can think of the odd case here and there where I might want to do 
so, I think an explicit declaration is a decent way to go.


> Here are some examples:
> 
> class Foo:
>     def method_a(self)
>         self x # subsequent 'x' references are scoped to 'self'
>         x = 5 # same as self.x = 5

You say "same as", I presume that this is a compile-time transformation 
that you write "x = 5" and the compiler treats it as "self.x = 5". So it 
doesn't matter whether x is a property or other descriptor, it will 
resolve the same as it currently does.

I can see one (horrible) corner case: suppose you have code like this:

    def spam(self):
        self self
        self = self

My guess is that this ought to be banned, as it's not clear when self 
refers to the self local variable and when it refers to the implicit 
self.self.

It might also help your case to convince people that implicit attribute 
references are not as bad as they might seem. Can you give a brief 
survey of languages with implicit attribute references, and how they 
deal with the ambiguity of "attribute or variable"?



-- 
Steve


More information about the Python-ideas mailing list