Elegant copy-by-value

Martin Christensen knightsofspamalot-factotum at gvdnet.dk
Sun Jan 12 14:14:40 CET 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>>>>> "Peter" == Peter Hansen <peter at engcorp.com> writes:
>>  Have you looked at the post you replied to? :-)
Peter> If you mean, did I misunderstand you, then no, I believe not.

Oh, my pardons, I thought you were just suggesting that I use the copy
module and had missed the fact that I already did.

Peter> My point was this: if the existing copy.py is that complicated,
Peter> but there were a much simpler way, don't you think it would
Peter> already have been implemented?

I wasn't thinking of simplicity implementation-wise. It just seems
very awkward to me that it should be necessary to import a module just
to be able to copy the value of even a primitive. For more complicated
structures it's more understandable, but copying those by value is
apparently easier. Go figure!

Peter> I'm actually surprised you have a problem with it.  I've had to
Peter> resort to that module only once so far, in two years.  I
Peter> suppose if you really have to use it often, it might become a
Peter> bit of an annoyance having to import the module.

Admittedly it's not an everyday event, but say that we have complex
data structure A from which we make complex data structure B. If
they're implemented as classes the elegant way of doing this is by
passing A to B's constructor. A copy will have to be made, or changes
to B will be reflected on A.

Another example where it's a bit more devious:

def recursive(foo, bar):

    # Code that modifies foo based on bar.

    a = recursive(foo, bar)
    b = recursive(foo + a, bar)
    # ... potentially more stuff.

Here we run into a situation where the first recursive call takes foo
with the value it was meant to have. However, in that recursive call
foo will likely be modified, and so the second recursive call in the
original caller will not take the same value of foo as the first
did. This is very easy to overlook.

Martin

- -- 
Homepage:       http://www.cs.auc.dk/~factotum/
GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Using Mailcrypt+GnuPG <http://www.gnupg.org>

iEYEARECAAYFAj4hakAACgkQYu1fMmOQldWs+gCfY1z2USYZx9d+Hiw0I/qS+P3K
lL8AoLfQ+/z3pmPjAkoRgWKP8GZv+v0w
=eOJ3
-----END PGP SIGNATURE-----




More information about the Python-list mailing list