[C++-sig] Python Assignment

David Abrahams dave at boost-consulting.com
Sat Aug 17 20:50:17 CEST 2002

From: "Enrico Ng" <enrico at fnal.gov>

> I would like the beable to tell python when to make a copy and when not
> to.
> In python, if I do:
> a=MyMatrix
> b=a
> changes in b will affect a and vice versa because b points to a.
> I would like to tell python to make a copy if I try to change b so a is
> not affected.
> Same if I try to change a.
> Is there a way to do this?

There's no way to control what '=' does in Python. It always rebinds
references to objects, so when you write

    b = a

a and b will always refer to the same object. That's just how Python is.

If you want, you can arrange for b = copy.copy(a) to make a copy of a. I
believe that if you implement pickling for MyMatrix that this just works
automatically (but I don't remember). Take a look at the copy module in the
Python standard library.


           David Abrahams * Boost Consulting
dave at boost-consulting.com * http://www.boost-consulting.com

More information about the Cplusplus-sig mailing list