[Python-ideas] Mitigating 'self.' Method Pollution
Chris Angelico
rosuav at gmail.com
Sat Jul 11 09:36:32 CEST 2015
On Sat, Jul 11, 2015 at 5:25 PM, 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)
Alternate proposal:
# You could in-line this if you want to.
def limit(low, n, high):
"""Limit a number to be within certain bounds"""
return min(low, max(n, high))
def keep_moving_gravity(self):
self.y = limit(0, self.y + self.gravity, height - 1)
There are precisely two references to self.y (one reading, one
writing), and one reference to self.gravity. The global identifier
height needs no declaration, because it's not being assigned to.
Instead of doing three operations (increment, then check against zero,
then check against height), it simply does one: a bounded increment by
gravity.
Bad code is not itself an argument for a language change. Sometimes
there's an even better alternative :)
ChrisA
More information about the Python-ideas
mailing list