Python prevent copying object as reference
Is it possible to copy an object in Python without copying a reference?
For example, if I define a class
class SomeClass:
def __init__(self):
self.value = 0
and then create an instance
someObject = SomeClass()
someObject.value = 12
and I try to copy it to another instance:
anotherObject = someObject
and try to modify a property,
anotherObject.value = 10
the original property gets modified:
print someObject.value #prints 10
Is there any way to prevent this from happening? To clarify, I want the anotherObject.value
to contain 10
, but I want someObject.value
to still contain the original 12
. Is this possible in python?
Thanks in advance.
python
add a comment |
Is it possible to copy an object in Python without copying a reference?
For example, if I define a class
class SomeClass:
def __init__(self):
self.value = 0
and then create an instance
someObject = SomeClass()
someObject.value = 12
and I try to copy it to another instance:
anotherObject = someObject
and try to modify a property,
anotherObject.value = 10
the original property gets modified:
print someObject.value #prints 10
Is there any way to prevent this from happening? To clarify, I want the anotherObject.value
to contain 10
, but I want someObject.value
to still contain the original 12
. Is this possible in python?
Thanks in advance.
python
add a comment |
Is it possible to copy an object in Python without copying a reference?
For example, if I define a class
class SomeClass:
def __init__(self):
self.value = 0
and then create an instance
someObject = SomeClass()
someObject.value = 12
and I try to copy it to another instance:
anotherObject = someObject
and try to modify a property,
anotherObject.value = 10
the original property gets modified:
print someObject.value #prints 10
Is there any way to prevent this from happening? To clarify, I want the anotherObject.value
to contain 10
, but I want someObject.value
to still contain the original 12
. Is this possible in python?
Thanks in advance.
python
Is it possible to copy an object in Python without copying a reference?
For example, if I define a class
class SomeClass:
def __init__(self):
self.value = 0
and then create an instance
someObject = SomeClass()
someObject.value = 12
and I try to copy it to another instance:
anotherObject = someObject
and try to modify a property,
anotherObject.value = 10
the original property gets modified:
print someObject.value #prints 10
Is there any way to prevent this from happening? To clarify, I want the anotherObject.value
to contain 10
, but I want someObject.value
to still contain the original 12
. Is this possible in python?
Thanks in advance.
python
python
asked Oct 6 '13 at 16:12
Raghav MalikRaghav Malik
158111
158111
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
The problem is, with
anotherObject = someObject
you don't copy the object, but just add another reference to it. To copy an object, try this:
from copy import copy
anotherObject = copy(someObject)
add a comment |
import copy
obj2 = copy.deepcopy(obj2)
add a comment |
As you've noticed, anotherObject = someObject
doesn't make a copy - if you want a copy, try
import copy
otherObject = copy.copy(someObject)
The copy.copy
vs copy.deepcopy
distinction is important here - you can get away with copy.copy
for the simple object you've described, but a more nested object would require copy.deepcopy
.
copy.copy(someObject)
makes a copy only of the object someObject
, but if someObject
contains references to other objects that can be changed ("mutable" objects) as in
someObject.value.this_one_has_values_too = 4
or
someObject.value[0] = 1
or
someObject.value['key'] = 'value'
then references to those objects will be made in the copy. If you use copy.deepcopy
, they'll also be copied over.
A great way to gain an understanding of this is playing with the Online Python Tutor (see linked example) but here's a straightforward demonstration of the behavior without the useful diagraming Online Python Tutor provides.
>>> import copy
>>> class Foo(object):
... pass
...
>>> f = Foo()
>>> f.value = 1
>>> f.nested_value = [2,3,4]
>>> deep = copy.deepcopy(f)
>>> deep.value = 5
>>> f.value
1
>>> deep.nested_value.append(6)
>>> f.nested_value
[2, 3, 4]
>>> shallow = copy.copy(f)
>>> shallow.value = 7
>>> f.value
1
>>> shallow.nested_value.append(8)
>>> f.nested_value
[2, 3, 4, 8]
Edit: But what about the integer in the first example? It's actually being shared between the f
object and the shallow
object, but that's not a problem - it's not editable; we can't change an integer object like 1
to be any different, so we might as well save memory and use that one object anytime any Python object needs a reference to 1.
The thing to read about this is Ned's Facts and Myths about Python names and values.
What is the difference between acopy
and adeepcopy
? Also, what do you mean bynested object
? I'm new to python and I just want to learn as much as possible.
– Raghav Malik
Oct 6 '13 at 16:25
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
Oh, I see what you mean bynested objects
. Just out of curiosity, isn't an integer also an object? Why isn'tdeepcopy
necessary for that? Thank you for the link, btw. It is very useful.
– Raghav Malik
Oct 6 '13 at 16:47
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
add a comment |
You can use copy
for that. Try the following:
someObject = SomeClass()
someObject.value = 12
anotherObject = copy.copy(someObject)
anotherObject.value = 10
Now someObject.value
will still be 12. You will have to place import copy
at the top of your script though.
add a comment |
import copy
In some cases just:
copy_obj = copy.copy(obj)
is enough but in other cases you we have to use:
copy_obj = copy.deepcopy(obj)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19210971%2fpython-prevent-copying-object-as-reference%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
The problem is, with
anotherObject = someObject
you don't copy the object, but just add another reference to it. To copy an object, try this:
from copy import copy
anotherObject = copy(someObject)
add a comment |
The problem is, with
anotherObject = someObject
you don't copy the object, but just add another reference to it. To copy an object, try this:
from copy import copy
anotherObject = copy(someObject)
add a comment |
The problem is, with
anotherObject = someObject
you don't copy the object, but just add another reference to it. To copy an object, try this:
from copy import copy
anotherObject = copy(someObject)
The problem is, with
anotherObject = someObject
you don't copy the object, but just add another reference to it. To copy an object, try this:
from copy import copy
anotherObject = copy(someObject)
answered Oct 6 '13 at 16:17
ConstantiniusConstantinius
23.9k65279
23.9k65279
add a comment |
add a comment |
import copy
obj2 = copy.deepcopy(obj2)
add a comment |
import copy
obj2 = copy.deepcopy(obj2)
add a comment |
import copy
obj2 = copy.deepcopy(obj2)
import copy
obj2 = copy.deepcopy(obj2)
answered Oct 6 '13 at 16:17


Steve BarnesSteve Barnes
20.5k43750
20.5k43750
add a comment |
add a comment |
As you've noticed, anotherObject = someObject
doesn't make a copy - if you want a copy, try
import copy
otherObject = copy.copy(someObject)
The copy.copy
vs copy.deepcopy
distinction is important here - you can get away with copy.copy
for the simple object you've described, but a more nested object would require copy.deepcopy
.
copy.copy(someObject)
makes a copy only of the object someObject
, but if someObject
contains references to other objects that can be changed ("mutable" objects) as in
someObject.value.this_one_has_values_too = 4
or
someObject.value[0] = 1
or
someObject.value['key'] = 'value'
then references to those objects will be made in the copy. If you use copy.deepcopy
, they'll also be copied over.
A great way to gain an understanding of this is playing with the Online Python Tutor (see linked example) but here's a straightforward demonstration of the behavior without the useful diagraming Online Python Tutor provides.
>>> import copy
>>> class Foo(object):
... pass
...
>>> f = Foo()
>>> f.value = 1
>>> f.nested_value = [2,3,4]
>>> deep = copy.deepcopy(f)
>>> deep.value = 5
>>> f.value
1
>>> deep.nested_value.append(6)
>>> f.nested_value
[2, 3, 4]
>>> shallow = copy.copy(f)
>>> shallow.value = 7
>>> f.value
1
>>> shallow.nested_value.append(8)
>>> f.nested_value
[2, 3, 4, 8]
Edit: But what about the integer in the first example? It's actually being shared between the f
object and the shallow
object, but that's not a problem - it's not editable; we can't change an integer object like 1
to be any different, so we might as well save memory and use that one object anytime any Python object needs a reference to 1.
The thing to read about this is Ned's Facts and Myths about Python names and values.
What is the difference between acopy
and adeepcopy
? Also, what do you mean bynested object
? I'm new to python and I just want to learn as much as possible.
– Raghav Malik
Oct 6 '13 at 16:25
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
Oh, I see what you mean bynested objects
. Just out of curiosity, isn't an integer also an object? Why isn'tdeepcopy
necessary for that? Thank you for the link, btw. It is very useful.
– Raghav Malik
Oct 6 '13 at 16:47
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
add a comment |
As you've noticed, anotherObject = someObject
doesn't make a copy - if you want a copy, try
import copy
otherObject = copy.copy(someObject)
The copy.copy
vs copy.deepcopy
distinction is important here - you can get away with copy.copy
for the simple object you've described, but a more nested object would require copy.deepcopy
.
copy.copy(someObject)
makes a copy only of the object someObject
, but if someObject
contains references to other objects that can be changed ("mutable" objects) as in
someObject.value.this_one_has_values_too = 4
or
someObject.value[0] = 1
or
someObject.value['key'] = 'value'
then references to those objects will be made in the copy. If you use copy.deepcopy
, they'll also be copied over.
A great way to gain an understanding of this is playing with the Online Python Tutor (see linked example) but here's a straightforward demonstration of the behavior without the useful diagraming Online Python Tutor provides.
>>> import copy
>>> class Foo(object):
... pass
...
>>> f = Foo()
>>> f.value = 1
>>> f.nested_value = [2,3,4]
>>> deep = copy.deepcopy(f)
>>> deep.value = 5
>>> f.value
1
>>> deep.nested_value.append(6)
>>> f.nested_value
[2, 3, 4]
>>> shallow = copy.copy(f)
>>> shallow.value = 7
>>> f.value
1
>>> shallow.nested_value.append(8)
>>> f.nested_value
[2, 3, 4, 8]
Edit: But what about the integer in the first example? It's actually being shared between the f
object and the shallow
object, but that's not a problem - it's not editable; we can't change an integer object like 1
to be any different, so we might as well save memory and use that one object anytime any Python object needs a reference to 1.
The thing to read about this is Ned's Facts and Myths about Python names and values.
What is the difference between acopy
and adeepcopy
? Also, what do you mean bynested object
? I'm new to python and I just want to learn as much as possible.
– Raghav Malik
Oct 6 '13 at 16:25
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
Oh, I see what you mean bynested objects
. Just out of curiosity, isn't an integer also an object? Why isn'tdeepcopy
necessary for that? Thank you for the link, btw. It is very useful.
– Raghav Malik
Oct 6 '13 at 16:47
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
add a comment |
As you've noticed, anotherObject = someObject
doesn't make a copy - if you want a copy, try
import copy
otherObject = copy.copy(someObject)
The copy.copy
vs copy.deepcopy
distinction is important here - you can get away with copy.copy
for the simple object you've described, but a more nested object would require copy.deepcopy
.
copy.copy(someObject)
makes a copy only of the object someObject
, but if someObject
contains references to other objects that can be changed ("mutable" objects) as in
someObject.value.this_one_has_values_too = 4
or
someObject.value[0] = 1
or
someObject.value['key'] = 'value'
then references to those objects will be made in the copy. If you use copy.deepcopy
, they'll also be copied over.
A great way to gain an understanding of this is playing with the Online Python Tutor (see linked example) but here's a straightforward demonstration of the behavior without the useful diagraming Online Python Tutor provides.
>>> import copy
>>> class Foo(object):
... pass
...
>>> f = Foo()
>>> f.value = 1
>>> f.nested_value = [2,3,4]
>>> deep = copy.deepcopy(f)
>>> deep.value = 5
>>> f.value
1
>>> deep.nested_value.append(6)
>>> f.nested_value
[2, 3, 4]
>>> shallow = copy.copy(f)
>>> shallow.value = 7
>>> f.value
1
>>> shallow.nested_value.append(8)
>>> f.nested_value
[2, 3, 4, 8]
Edit: But what about the integer in the first example? It's actually being shared between the f
object and the shallow
object, but that's not a problem - it's not editable; we can't change an integer object like 1
to be any different, so we might as well save memory and use that one object anytime any Python object needs a reference to 1.
The thing to read about this is Ned's Facts and Myths about Python names and values.
As you've noticed, anotherObject = someObject
doesn't make a copy - if you want a copy, try
import copy
otherObject = copy.copy(someObject)
The copy.copy
vs copy.deepcopy
distinction is important here - you can get away with copy.copy
for the simple object you've described, but a more nested object would require copy.deepcopy
.
copy.copy(someObject)
makes a copy only of the object someObject
, but if someObject
contains references to other objects that can be changed ("mutable" objects) as in
someObject.value.this_one_has_values_too = 4
or
someObject.value[0] = 1
or
someObject.value['key'] = 'value'
then references to those objects will be made in the copy. If you use copy.deepcopy
, they'll also be copied over.
A great way to gain an understanding of this is playing with the Online Python Tutor (see linked example) but here's a straightforward demonstration of the behavior without the useful diagraming Online Python Tutor provides.
>>> import copy
>>> class Foo(object):
... pass
...
>>> f = Foo()
>>> f.value = 1
>>> f.nested_value = [2,3,4]
>>> deep = copy.deepcopy(f)
>>> deep.value = 5
>>> f.value
1
>>> deep.nested_value.append(6)
>>> f.nested_value
[2, 3, 4]
>>> shallow = copy.copy(f)
>>> shallow.value = 7
>>> f.value
1
>>> shallow.nested_value.append(8)
>>> f.nested_value
[2, 3, 4, 8]
Edit: But what about the integer in the first example? It's actually being shared between the f
object and the shallow
object, but that's not a problem - it's not editable; we can't change an integer object like 1
to be any different, so we might as well save memory and use that one object anytime any Python object needs a reference to 1.
The thing to read about this is Ned's Facts and Myths about Python names and values.
edited Oct 7 '13 at 3:09
answered Oct 6 '13 at 16:18
ThomasThomas
4,77412340
4,77412340
What is the difference between acopy
and adeepcopy
? Also, what do you mean bynested object
? I'm new to python and I just want to learn as much as possible.
– Raghav Malik
Oct 6 '13 at 16:25
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
Oh, I see what you mean bynested objects
. Just out of curiosity, isn't an integer also an object? Why isn'tdeepcopy
necessary for that? Thank you for the link, btw. It is very useful.
– Raghav Malik
Oct 6 '13 at 16:47
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
add a comment |
What is the difference between acopy
and adeepcopy
? Also, what do you mean bynested object
? I'm new to python and I just want to learn as much as possible.
– Raghav Malik
Oct 6 '13 at 16:25
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
Oh, I see what you mean bynested objects
. Just out of curiosity, isn't an integer also an object? Why isn'tdeepcopy
necessary for that? Thank you for the link, btw. It is very useful.
– Raghav Malik
Oct 6 '13 at 16:47
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
What is the difference between a
copy
and a deepcopy
? Also, what do you mean by nested object
? I'm new to python and I just want to learn as much as possible.– Raghav Malik
Oct 6 '13 at 16:25
What is the difference between a
copy
and a deepcopy
? Also, what do you mean by nested object
? I'm new to python and I just want to learn as much as possible.– Raghav Malik
Oct 6 '13 at 16:25
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
@coder108 does this make sense? If not, please let me know what doesn't so I can improve the answer.
– Thomas
Oct 6 '13 at 16:33
Oh, I see what you mean by
nested objects
. Just out of curiosity, isn't an integer also an object? Why isn't deepcopy
necessary for that? Thank you for the link, btw. It is very useful.– Raghav Malik
Oct 6 '13 at 16:47
Oh, I see what you mean by
nested objects
. Just out of curiosity, isn't an integer also an object? Why isn't deepcopy
necessary for that? Thank you for the link, btw. It is very useful.– Raghav Malik
Oct 6 '13 at 16:47
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
@coder108 terrific question - both objects actually use the same integer. Why isn't this a problem? Because it's an immutable object; there's no way to take an integer object 1 and change it.
– Thomas
Oct 6 '13 at 16:53
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
That makes sense. Thank you so much!
– Raghav Malik
Oct 6 '13 at 20:19
add a comment |
You can use copy
for that. Try the following:
someObject = SomeClass()
someObject.value = 12
anotherObject = copy.copy(someObject)
anotherObject.value = 10
Now someObject.value
will still be 12. You will have to place import copy
at the top of your script though.
add a comment |
You can use copy
for that. Try the following:
someObject = SomeClass()
someObject.value = 12
anotherObject = copy.copy(someObject)
anotherObject.value = 10
Now someObject.value
will still be 12. You will have to place import copy
at the top of your script though.
add a comment |
You can use copy
for that. Try the following:
someObject = SomeClass()
someObject.value = 12
anotherObject = copy.copy(someObject)
anotherObject.value = 10
Now someObject.value
will still be 12. You will have to place import copy
at the top of your script though.
You can use copy
for that. Try the following:
someObject = SomeClass()
someObject.value = 12
anotherObject = copy.copy(someObject)
anotherObject.value = 10
Now someObject.value
will still be 12. You will have to place import copy
at the top of your script though.
answered Oct 6 '13 at 16:18
Patrick KostjensPatrick Kostjens
4,24462237
4,24462237
add a comment |
add a comment |
import copy
In some cases just:
copy_obj = copy.copy(obj)
is enough but in other cases you we have to use:
copy_obj = copy.deepcopy(obj)
add a comment |
import copy
In some cases just:
copy_obj = copy.copy(obj)
is enough but in other cases you we have to use:
copy_obj = copy.deepcopy(obj)
add a comment |
import copy
In some cases just:
copy_obj = copy.copy(obj)
is enough but in other cases you we have to use:
copy_obj = copy.deepcopy(obj)
import copy
In some cases just:
copy_obj = copy.copy(obj)
is enough but in other cases you we have to use:
copy_obj = copy.deepcopy(obj)
edited Nov 20 '18 at 14:56
answered Nov 20 '18 at 14:21


Juba FOURALIJuba FOURALI
193
193
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f19210971%2fpython-prevent-copying-object-as-reference%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown