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

David Mertz mertz at gnosis.cx
Sat Jul 11 21:41:46 CEST 2015


On Sat, Jul 11, 2015 at 12:10 PM, Nikolaus Rath <Nikolaus at rath.org> wrote:

> > class Vector:
> >     def abs(self):
> >         return sqrt(x**2 + y**2 + z**2)
> >         # versus
> >         return sqrt(self.x**2 + self.y**2 + self.z**2)
> >
> >
> > I expect that most people, with any
> > knowledge of vectors, would have understood that the x, y, z in the
> > first return must refer to coordinates of the vector.



> Thanks for that excellent post. I hope it'll cause some people to
> reconsider. Although there seems to be a flood of objection mails, most
> of them seem more instintive than rational to me.
>

This is a great example of why the proposal is a bad one.  Yes, not using
magic makes a one-line function slightly longer (and even slightly less
readable).

But I also don't want to have to guess about WHICH 'x' or 'y' or 'z' is the
one being used in calculation of Cartesian distance.  Sure, an obvious
implementation of a Vector class probably has x, y, z attributes of self.
The example was rigged to make that seem obvious.  But even then, I don't
really know.  Maybe the z direction of the vector is stored as a class
attribute.  Maybe the class expects to find a global definition of the z
direction.

Sure, keeping the z direction somewhere other than in self is probably
foolish if you assume "Vector" means "generic vector".  What if the class
was called "RestrictedVector"? Would you know without reading the full
class and docstring exactly in what respect it is "restricted"?  E.g. are
you sure it's not "restricted in the z dimension"?

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

No one stops you now from giving local names to values stored in the
instance within a method body.  But when you do so, you KNOW 30 lines later
that they are local names, even after the "local-looking name is actually
an attribute" declaration has scrolled away.

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150711/ae088be1/attachment.html>


More information about the Python-ideas mailing list