473,671 Members | 2,475 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Legitimacy of deepcopy

There is a list of custom objects. I want do duplicate this list to modify
objects in new list and then compare old and new. I could do it with
deepcopy

class foo:
def __init__(self, str):
self.str = str
old = [foo('str1'), foo('str2')]

import copy
new = copy.deepcopy(o ld)

But I've found very few deepcopy uses in Python library and other programs,
so I wonder it's possible to do it other, more elegant way.

Jul 18 '05 #1
2 1500
Eugeni Doljenko wrote:
There is a list of custom objects. I want do duplicate this list to modify
objects in new list and then compare old and new. I could do it with
deepcopy

class foo:
def __init__(self, str):
self.str = str
old = [foo('str1'), foo('str2')]

import copy
new = copy.deepcopy(o ld)

But I've found very few deepcopy uses in Python library and other programs,
so I wonder it's possible to do it other, more elegant way.


The problem with deepcopy is that it is impossible to do "correctly, "
since "correctly" depends on where your data structure abstractions are.
A simple example:

steve = People('Steve')
joe = People(steve)
mystruct = [(steve, joe, Dollars(5)), steve]

Now, should a deepcopy have two distinct steves, or one? Is the $5.00
in the new structure "the same as" another $5.00 or not? Sometime you
mean the identity of an object, and sometimes you mean it as a value,
and no general purpose function named deepcopy can guess where to stop
copying.

--
-Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #2
Scott David Daniels <Sc***********@ Acm.Org> writes:
The problem with deepcopy is that it is impossible to do "correctly, "
since "correctly" depends on where your data structure abstractions are.
Well, just because there's more than one way to do it, need not mean
that a particular solution isn't a correct one. The semantics of
deepcopy are well-defined and I think perfectly valid. Now, if they
don't fit a particular need then it doesn't fit the need, but that's
up to the user to decide on a case by case basis.

To the original poster, we used deepcopy in a number of interface
points where we need to ensure isolation of internal data structures
versus copies of that information returned to callers. For example,
we can't just return a reference to an internal list or dictionary
which would let the caller later mutate our internal object without
our knowledge. For that, deepcopy works just the way we need, since
our primary goal is to avoid mutation of our original objects.

In most of our use cases, the objects in question are providing data
storage (either in-memory or as a simulation for a database) and need
strict isolation between their internal storage and what callers see
as the objects being returned.

In such cases, I really don't see any good solution in lieu of
deepcopy, and in fact deepcopy (as covered below) is probably already
a pretty good minimal solution in terms of actual work it does. It's
certainly a legitimate need and deepcopy is certainly a legitimate
implementation in my eyes. (I'll grant you that sometimes it feels
strange forcing object copies when you don't normally find yourself
needing to, but when yoiu want copies, you want copies :-))
A simple example:

steve = People('Steve')
joe = People(steve)
mystruct = [(steve, joe, Dollars(5)), steve]

Now, should a deepcopy have two distinct steves, or one? Is the $5.00
in the new structure "the same as" another $5.00 or not? Sometime you
mean the identity of an object, and sometimes you mean it as a value,
and no general purpose function named deepcopy can guess where to stop
copying.


Valid questions, but just because they can have different answers need
not mean that deepcopy can't pick its own set of answers and stick to
them. In the deepcopy case, it will have one distinct steve
(referenced twice from the new list, and once from within the new joe
within the list) because deepcopy keeps a memo list of objects it has
already copied (to avoid problems with recursion). By doing so it
achieves the primary goal of ensuring that the steve references in the
copy point to a distinct steve from the original (since it is the
original container object you are deep copying), but they remain
internally consistent with how they were used in the original object.

Likewise, the Dollars() instance in the copy will be distinct from
that in the original.

A subtlety (which I'm guessing you are referring to by your identity
comment) is that a deepcopy (IMHO) is aimed at ensuring that the new
copy does not have the ability to mutate objects in the original.
Towards that end, there's no real need to create copies of immutable
objects since they can't be mutated in the first place. So immutable
objects such as numbers, tuples, etc.. will simply have references to
the same object placed in the copy (unless overridden by
__deepcopy__). This is no different to how a copy.copy() of an
immutable object will return a reference to the same object (barring
an override of __copy__).

You could probably view the general deepcopy guideline as making the
minimum number of actual copies to ensure that no references to
mutable objects from the original object remain in the copy, but that
the internal reference structure from the original is maintained. In
general, I find that to be a very practical approach.

Of course, if that's not what you wanted, then deepcopy isn't going to
fit the bill. If you have control of the objects involved, the
__copy__ and __deepcopy__ hooks are provided to let you make some
changes, but it certainly may not fit all cases. But that hardly
makes it "incorrect" or less useful for cases where it does fit (which
to be honest, I'd guess is the majority of them).

-- David
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3966
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2 arguments, got 0". Tested with Python 2.3.4 on OpenBSD and Python 2.4 on Win98; same results. Is this a bug in deepcopy, how I dynamically assign the instance method or something else? (See example code for how I did it.) If you're curious as...
6
2226
by: Alexander Zatvornitskiy | last post by:
Hello! I have trouble with copy/deepcopy. It seems, I just don't understand something. Please explain where things goes wrong and how to do it the right way. I have one class: class Distribution: __gr_on_transp=dict() __ostatok_m=dict()
0
1346
by: phil | last post by:
I wrote the following to prove to myself that deepcopy would copy an entire dictionary which contains an instance of a class to one key of another dictionary. Note that after copying adict to ndict I delete adict. Then ndict contains a good copy of adict. works great.
6
3104
by: phil | last post by:
I posted the following yesterday and got no response and did some testing simplifying the circumstances and it appears that deepcopy fails when the object to be copied contains a reference to a Canvas Object. Perhaps any Tkinter object, didn't get that far. The problem arises because I have a geometry tutorial with a progression of drawings and want the students to be able to go "back". Creating "snapshots" of points in time in the...
0
1695
by: Joshua Ginsberg | last post by:
Howdy -- I have a class that has an attribute that is a dictionary that contains an object that has a kword argument that is a lambda. Confused yet? Simplified example: import copy class Foo: def __init__(self, fn=None):
7
2207
by: Alexandre Guimond | last post by:
Hi all, i'm trying to deepcopy a slice object but i get the following error. Does anyone know a workaround? ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) on win32 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last):
4
3675
by: Emin | last post by:
Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical with getattr. Comments would be appreciated. Thanks, -Emin
0
1384
by: Robin Becker | last post by:
I'm using deepcopy in some code which eventually ends up by crash witht he following rather long winded error. I'm not directly using _hashlib.HASH, but I suppose something else along the way could be. Is there some nice way to make copy/deepcopy give more information when this error happens? I know what the top level object is, but presumably it's something further down that's causing the problem. .......... File...
1
2101
by: Wouter DW | last post by:
I read the article on http://www.python.org/download/releases/2.2/descrintro/#metaclasses and started using autoprop. But now I have a problem I can't seem to solve myself. class autoprop(type): def __init__(cls, name, bases, dict): super(autoprop, cls).__init__(name, bases, dict) props = {} for name in dict.keys(): if name.startswith("_get_") or name.startswith("_set_"):
0
8400
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8823
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8602
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8672
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7441
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2817
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.