Elegant copy-by-value
Carl Banks
imbosol at vt.edu
Sat Jan 11 22:51:20 EST 2003
Martin Christensen wrote:
> Python usually uses copy-by-reference. This is all good and well, but
> sometimes we want copy-by-value. For a long time now I've been using
> copy() or deepcopy(), depending on the circumstances, from the copy
> module. Is there no more simple and elegant way of doing this? It
> seems strange that one should have to import a module to so something
> as simple as a copy-by-value. I should, of course, have researched
> this a long, long time ago, but deadlines have a way of defering such
> luxuries. :-)
For the types where it is most useful to do copy-by-value, there are
built-in ways to do shallow copies. For example, lists (and Numeric
arrays) can do this:
a = b[:]
Dicts have a copy method:
a = b.copy()
Class instances don't have such a method by default, seeing that they
can have more complicated state that might not work with a simple
copy. However, it's easy to define a class that does, if you need it.
For example, extending the Bunch class from Python Cookbook:
class Bunch:
def __init__(self,**kwargs): self.__dict__.update(kwargs)
def copy(self): return Bunch(self.__dict__)
Deep copying is *not* something simple. It is best left up to the
module, or done by hand.
--
CARL BANKS
More information about the Python-list
mailing list