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 ???
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.
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.
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.
deepcopy() is extremely slow.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With