[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] vector type: mutable or immutable



On May 1, 2009, at 8:07 AM, Lorenz Quack wrote:

Hi

as a follow up to the "API draft for vector type" I would like to discuss the merits of having a mutable or immutable vector type.


Arguments for an immutable vector type:

Brian Fisher pointed out two advantages of immutable vector types:
1) they prevent bugs in programs like the following (adopted from Brian):
> class Angel(object)
>     def __init__(self, offset):
>         self.offset = offset
>
> t = Angel()
> halo_pos = t.offset
> halo_pos.y -= 5  # BUG: this changes the offset in t

2) if vectors are immutable you can use them as keys in dicts



Arguments for a mutable vector type:

1) operations such as rotate() and scale_to_length() are more elegant when operation in-place. for immutable types you would have to do "v = v.rotate()" or use a module level rotate function "v = pygame.math.rotate_vector(v)" or something similar.

2) a priori I would expect mutable vectors to perform better than immutable ones because you don't have to create new objects for every operation.



So are there anymore arguments?
And where do people stand on this issue?

I think that less memory management overhead and batch operations are strong arguments for mutable vectors.

The predicability of immutable vectors is nice, but IMO the convenience and flexibility of mutable vectors, along with the consistency with existing type like Rect makes them win.

I would argue that it should be possible to treat vectors as immutable if you preferred that, which I think is covered by the features proposed so far.

-Casey