tuples and cartesian coordinates

Peter Otten __peter__ at web.de
Wed Dec 17 17:14:29 EST 2003


Gerrit Holl wrote:

> the FAQ says:
> 
>> For example, a Cartesian coordinate is appropriately represented as a
>> tuple of two or three numbers.
> 
> I find it strange to use tuples for a coordinate. After all, a
> coordinate represents a position of an object. Suppose I have a game
> where the player has a position: isn't it stupid to use tuples rather
> than lists or another type (maybe complex numbers?), because I want to
> be able to change the position?
> 
> Shouldn't coordinates be mutable?

One benefit of immutable coordinates: you can safely assign one coordinate
to multiple positions:

class Shape: pass
s1 = Shape()
s2 = Shape()

origin = ImmutableCoord(0, 0)
s1.position = origin
s2.position = origin

Whereas with mutable coordinates you would need

class Shape:
    def __init__(self, pos):
        self.pos = MutableCoord(pos)
    def setPosition(self, pos)
        self.pos.x = pos.x
        self.pos.y = pos.y
s1.setPosition(origin)
s2.setPosition(origin)

There are several variants of this scheme, but I think they all tend to
complicate the design, because not only rebinding of pos needs to be
tracked, but also the changing of pos.x and pos.y.

By the way, complex numbers are immutable:

>>> z = 1 + 3j
>>> z.imag = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: readonly attribute

Peter




More information about the Python-list mailing list