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

Nick Coghlan ncoghlan at gmail.com
Sun Jul 12 02:04:47 CEST 2015

On 12 July 2015 at 05:41, David Mertz <mertz at gnosis.cx> wrote:
> As someone else points out, if you WANT local variables in a method, you are
> welcome to use them.  E.g.:
>     def times_matrix(self, matrix):
>         x, y, z = self.x, self.y, self.z
>         # Many more than one line of implementation
>         # ... stuff with matrix indexing and referencing x
>         # etc.
>         return result_matrix

Perhaps that's an answer that could be pushed more heavily?

Q: My method is drowning in self references, how can I make it more readable?
A: Bind referenced attributes to local names at the beginning of the
method, and write them back to instance attributes at the end of the
method. For example, rather than writing:

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

We can write:

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

This approach is then conveniently amenable to factoring out helper
functions that are independent of the original class definition:

    def calculate_next_location(current, gravity, height):
        next_location = current + gravity
        next_location = max(next_location, 0)
        next_location = min(next_location, height - 1)
        return next_location

    class ObjectInMotion:
        def keep_moving_gravity(self):
            self.y = calculate_next_location(self.y, self.gravity, height)

I like this angle, as it encourages thinking about mutating operations
on instances as a "read, transform, write" cycle, rather than multiple
in-place mutations (although the latter may of course still happen
when the attributes being manipulated are themselves mutable objects).


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

More information about the Python-ideas mailing list