ytrstu / pyeuclid

Automatically exported from code.google.com/p/pyeuclid
0 stars 0 forks source link

Vector summation suggestion #20

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
a = Vector3(1.0,2.0,3.0)
b = a
a += Vector3(0.1,0.1,0.1)
print b

What is the expected output? What do you see instead?
I would expect the output to be Vector3(1.0,2.0,3.0)
However since b is a shallow copy of a it produces Vector3(1.1,2.1,3.1)

This has introduced some subtle bugs into my code, I would suggest making:
a += Vector3(0.1,0.1,0.1)
Function the same as:
a = a + Vector3(0.1,0.1,0.1)

Not a big deal either way you end up going with it, just a suggestion for 
improving things.

Original issue reported on code.google.com by chris.fl...@gmail.com on 13 Nov 2013 at 7:07

GoogleCodeExporter commented 9 years ago
As I see it, this is not a bug, but the proper behavior: `b = a` simply means 
`b` points to the same object as `a`. Same as lists and dicts, b is never a new 
object or a "copy". Try this:

>>> a = [1]
>>> b = a
>>> a.append(2)
>>> b
[1, 2]

That happens for all *in-place* operations, the ones that modify an object 
without re-assigning the label to a new one. Think of `b` as a reference to `a` 
(more precisely, a reference to the same object that `a` points to)

And `a += x` is an in-place operation, so is not the same as `a = a + x`. The 
latter re-assigns `a` to a new object.

That behavior is clearly stated in python's documentation:

https://docs.python.org/2/reference/datamodel.html#object.__iadd__

"These methods should attempt to do the operation in-place (modifying self) and 
return the result (which could be, but does not have to be, self)"

Original comment by rodrigo....@gmail.com on 6 Aug 2014 at 8:59

GoogleCodeExporter commented 9 years ago
Thanks for the explanation, I have been using the "a = a + x" method to 
re-assign values and things are working as expected.

Original comment by chris.fl...@gmail.com on 6 Aug 2014 at 9:13