Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python prevent copying object as reference

Tags:

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.

like image 756
Raghav Malik Avatar asked Oct 06 '13 16:10

Raghav Malik


People also ask

Does Python copy object by reference?

Assignment statements in Python do not create copies of objects, they only bind names to an object. For immutable objects, that usually doesn't make a difference. But for working with mutable objects or collections of mutable objects, you might be looking for a way to create “real copies” or “clones” of these objects.

How do you copy without references in Python?

b = a. copy() , this way it will work.

What is reference copy Python?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

How do you Deepcopy an object in Python?

Deep copy: copy. To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.


1 Answers

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) 
like image 60
Constantinius Avatar answered Sep 20 '22 03:09

Constantinius