Pythonic way to handle coordinates

andrew cooke andrew at acooke.org
Sat Jan 17 07:20:36 EST 2009


although james's idea is quite neat (especially the idea of heritable
classes), my initial reaction was that it's too over-engineered.  so
here's a different approach.

there are two "tricks" that can help make using tuples easier:

(1) unpacking the return value.
  (x, y) = returns_a_point()
  x += 1

(2) passing a tuple to a function that takes an x and a y value:
  def takes_two_values(x, y):
    ...
  p = (1, 2)
  takes_two_values(*p)

and what I have done in the past is exploit these, so that functions/
methods that only takes a point takes two values while those that take
many points, other arguments, etc, take a tuple.  this sounds messy
but works quite well because you tend to use the first kind of
functions when you are changing coordinates (and then it is useful to
treat a point as separate x and y values) and the second kind of
functions when you are handling collections of points that don't need
modifying.

andrew



More information about the Python-list mailing list