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

Nick Coghlan ncoghlan at gmail.com
Sat Jul 11 10:40:04 CEST 2015


On 11 July 2015 at 17:25, Michael Hewitt <michael at hewitts.us> wrote:
> Let's compare two versions of a method taken from some code that my 11 year
> old son wrote yesterday:
>
> Current
>
> global height
> def keep_moving_gravity(self):
>     self.y += self.gravity
>     self.y = max(self.y, 0)
>     self.y = min(self.y, height - 1)
>
> Proposed
>
> global height
> def keep_moving_gravity(self):
>     self y, gravity
>     y += gravity
>     y = max(y, 0)
>     y = min(y, height - 1)

Alternative proposal:

    def keep_moving_gravity(self):
        .y += .gravity
        .y = max(.y, 0)
        .y = min(.y, height - 1)

The main objection folks have to the declarative proposal is the fact
that there's nothing obvious at the point of reference to indicate
whether we're manipulating a local variable or an instance variable. I
can speak from experience in saying that there's a reason the "m_*"
prefix notation for C++ member variables is popular: it makes C++
method implementations much easier to read when you can tell at a
glance if a line is working with an instance member or a local
variable. With the language not providing that separation by default,
folks added it by convention.

An "implied attribute reference" proposal would be different: it could
build on the same mechanism that powers zero-argument super to make it
possible to say "if I reference an object attribute in a function
without saying which object I'm referring to, then I mean the first
parameter".

This should work cleanly for standalone functions, class methods,
instance methods, etc, as the compiler already keeps track of the
necessary details in order to implement PEP 3135
(https://www.python.org/dev/peps/pep-3135/#specification)

The main downside is that a leading dot isn't as good a visual
indicator as a dot appearing between two other characters. That could
potentially be alleviated with a double-dot notation:

    def keep_moving_gravity(self):
        ..y += ..gravity
        ..y = max(..y, 0)
        ..y = min(..y, height - 1)

The downside of *that* is it might make people start thinking in terms
stepping up scopes, rather than referring to the first parameter.

Regards,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list