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

Re: [pygame] immutable vectors in math package



Hi,

I implemented something similar in pure python if you're interested:
https://github.com/vxgmichel/pygame-mvctools/blob/master/mvctools/common.py

It is called "xytuple" and subclasses namedtuple("xytuple",("x","y")).
It overrides base operation methods (such as __add__) to make it
term-to-term. 

Also, the absolute value operation is supported (abs).
It returned a float corresponding to the norm of the coordinates.
A map method is available to apply a function on both coordinates.

It is minimalistic, but it's simple and works fine for most cases:

>>> vect = xytuple(1,2)
>>> vect = vect.map(float)
>>> vect
xytuple(x=1.0, y=2.0)
>>> vect = vect.map(float)
>>> vect /= 2,2
>>> vect
xytuple(x=0.5, y=1.0)
>>> vect += 4,2
>>> vect
xytuple(x=4.5, y=3.0)
>>> abs(vect)
5.408326913195984
>>> -vect
xytuple(x=-4.5, y=-3.0)

Vincent


On Thu, 2014-10-30 at 12:53 +0000, Lorenz Quack wrote:
> Hi Christopher,
> 
> good question.
> Currently the Vector types are implemented in a C-extension and I'm not sure how to subclass from a pure python object 
> in C. I'm sure it's possible just that I've never done it before.
> But I am afraid that you would have to go through the Python API to access any attributes from the C side which would 
> have a negative impact on performance.
> Another alternative would be to implement the whole thing in pure python, which certainly is a possibility. Just one 
> that I didn't pursue.
> 
> Cheers,
> Lorenz
> 
> 
> On 30/10/14 01:14, Christopher Night wrote:
> > I have not used either the original API nor yours, so this suggestion may be off base, but if they're going to be
> > immutable, why not subclass collections.namedtuple("Vector2", "x y"), and get a few handy methods defined for free?
> >
> > -Christopher
> >
> > On Wed Oct 29 2014 at 7:41:54 PM Greg Ewing <greg.ewing@xxxxxxxxxxxxxxxx <mailto:greg.ewing@xxxxxxxxxxxxxxxx>> wrote:
> >
> >     Lorenz Quack wrote:
> >
> >      >  * you cannot access the components x/y/z directly...
> >       > use ... new accessor methods x()/y()/z()
> >
> >     Is this change really necessary? It will be a big backward
> >     step for code readability.
> >
> >     There shouldn't be any reason you can't provide read-only
> >     access using attribute notation.
> >
> >     --
> >     Greg
> >
>