Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why copy.deepcopy doesn't modify the id of an object?

I don't understand why copy.deepcopy does not modify the id of an object:

import copy
a = 'hello world'
print a is copy.deepcopy(a)  # => True ???
like image 620
user2660966 Avatar asked Jan 27 '15 18:01

user2660966


People also ask

What does copy Deepcopy do?

Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child 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.

How do you copy an object from a class in Python?

Copy an Object in Python In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

Is Deepcopy fast?

deepcopy() is extremely slow.


3 Answers

Simeon's answer is perfectly correct, but I wanted to provide a more general perspective.

The copy module is primarily intended for use with mutable objects. The idea is to make a copy of an object so you can modify it without affecting the original. Since there's no point in making copies of immutable objects, the module declines to do so. Strings are immutable in Python, so this optimization can never affect real-world code.

like image 151
Kevin Avatar answered Nov 04 '22 14:11

Kevin


Python interns the strings so they're the same object (and thus the same when compared with is). This means Python only stores one copy of the same string object (behind the scenes).

The result of copy.deepcopy(a) is not truly a new object and as such it isn't meaningful to perform this call on a string object.

like image 44
Simeon Visser Avatar answered Nov 04 '22 14:11

Simeon Visser


Look again:

import copy
a = ['hello world']
print a is copy.deepcopy(a)  # => False

Since the value of an immutible object (such as a string) is incapable of changing without also changing its identity, there's would be no point to creating additional instances. It's only in the case of a mutable object (such as a list) where there's any point to creating a second identity with the same value.

For a thorough introduction to separating the concepts of value, identity and state, I suggest Rich Hickey's talk on the subject.

like image 39
Charles Duffy Avatar answered Nov 04 '22 12:11

Charles Duffy