Python 008 - Help From My Friends
Some advice for a better way sends me scurrying to read about list comprehensions.
One of the nice things about a new language is that there are usually interesting special aspects to learn about, and one of the nice things about writing from the viewpoint of someone with lots of experience but not necessarily in the language at hand is that I get a lot of help from my friends.
My new friend Luigi Ballabio suggested that I look into “list comprehensions”. I think the best way to describe them would be to use them. We’ll replace this:
def get_ship_points(self):
ship_points = [vector2(-3.0, -2.0), vector2(-3.0, 2.0), vector2(-5.0, 4.0),
vector2(7.0, 0.0), vector2(-5.0, -4.0), vector2(-3.0, -2.0)]
return list(map(self.adjust, ship_points, repeat(vector2(7, 4)), repeat(4)))
With this:
def get_ship_points(self):
ship_points = [vector2(-3.0, -2.0), vector2(-3.0, 2.0), vector2(-5.0, 4.0),
vector2(7.0, 0.0), vector2(-5.0, -4.0), vector2(-3.0, -2.0)]
return [self.adjust(point, vector2(7, 4), 4) for point in ship_points]
That’s definitely nicer. Thanks, Luigi! There are at least two other places where I can do this:
def get_flare_points(self):
flare_points = [vector2(-3.0, -2.0), vector2(-7.0, 0.0), vector2(-3.0, 2.0)]
return [self.adjust(point, vector2(7, 4), 4) for point in flare_points]
def prepare_surface(self):
surface = pygame.Surface((128, 128))
surface.set_colorkey((0, 0, 0))
adjusted = [self.adjust(point, vector2(4, 4), 16) for point in raw_rocks[0]]
pygame.draw.lines(surface, "white", False, adjusted, 3)
return surface
I think there’s another call to map in here somewhere. Yes, in a test:
def test_map_lambda(self):
points = [vector2(-3.0, -2.0), vector2(-3.0, 2.0), vector2(-5.0, 4.0),
vector2(7.0, 0.0), vector2(-5.0, -4.0), vector2(-3.0, -2.0)]
new_points = map(lambda point: point + vector2(7, 4), points)
for point in new_points:
assert point.x >= 0
assert point.x <= 14
assert point.y >= 0
assert point.y <= 9
We’ll just fix that right up. I decided to keep that test and show the alternative:
def test_map_lambda(self):
points = [vector2(-3.0, -2.0), vector2(-3.0, 2.0), vector2(-5.0, 4.0),
vector2(7.0, 0.0), vector2(-5.0, -4.0), vector2(-3.0, -2.0)]
new_points = map(lambda pt: pt + vector2(7, 4), points)
for point in new_points:
assert point.x >= 0
assert point.x <= 14
assert point.y >= 0
assert point.y <= 9
def test_map_comprehension(self):
points = [vector2(-3.0, -2.0), vector2(-3.0, 2.0), vector2(-5.0, 4.0),
vector2(7.0, 0.0), vector2(-5.0, -4.0), vector2(-3.0, -2.0)]
new_points = [point + vector2(7, 4) for point in points]
for point in new_points:
assert point.x >= 0
assert point.x <= 14
assert point.y >= 0
assert point.y <= 9
Super. Commit: Use list comprehension instead of map.
So that’s nice.
Summary
Not much to add. Learn your language is the lesson, and of course that takes time. And, ideally, a bit of help from your friends. Thanks again, Luigi!
See you next time!