Varibles -- copies and references

Ferdinand Sousa ferdinandsousa at
Tue Feb 3 03:57:30 EST 2009

 People get a confused because if you pass a  mutable object inside a def
function and mutate that object the changes /are/ propagated outside--
because now you have a name inside the function and a name outside the
object both pointing to the same object.

Since tuples  are immutable, I guess passing tuples to functions would
achieve the result desired by me:
result = func ( (anobject) )

If you want a function to work on a copy of a mutable object passed to it,
and not the real object itself, you must explicitly make a copy of it.

Or using deepcopy within the function definition. This would be better as I
could simply pass an object to the function. I don't think there is another
way to make an object mutable by something in the class definition. Is

>>>class AA:

>>> x=AA()
>>> x.a
>>> y=x
>>> y.a
>>> y.a=222
>>> x.a
222                         # undesirable?
>>> z=copy.deepcopy(x)
>>> z.a
>>> z.a=444
>>> x.a
>>> y.a

The reason you see the "undesirable" behavior of a change to y.a showing the
same result of x.a... is because those are the *exact* same instance. You
didn't make a copy of the instance, you just made a new name and bound it to
the same instance. If you want to copy in Python you have to explicitly do
so, via the 'copy' module or any copy methods an object provides.

Could someone please give me an example of how to implement this copy method
for the AA class.

Going the other way:

>>> a=555
>>> d=copy.copy(a)             # Supposed to be a shallow copy
>>> d
>>> d=444
>>> a                                  # But, it doesn't change the original

Is there any way to get ints/strings to refer to the same object?

Thanks and Regards,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list