user2660966
user2660966

Reputation: 975

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 ???

Upvotes: 5

Views: 2900

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295650

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.

Upvotes: 1

Kevin
Kevin

Reputation: 30161

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.

Upvotes: 7

Simeon Visser
Simeon Visser

Reputation: 122456

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.

Upvotes: 5

Related Questions