pythoncopydeep-copy

How do the copy and deepcopy functions work for a bytearray argument?


The docs say:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances)

It seems that the bytearray object is not a compound object (I think so because, unlike the list object, bytearray object doesn't contain references to other objects). Therefore, copy.copy and copy.deepcopy will produce the same result for such an object. But the docs don't describe the details for this particular data type. I know that for immutable numeric and str objects (they are obviously not compound too) copy.copy and copy.deepcopy simply return their argument (they don't create a new object here).

I did some tests with a bytearray object obj and came to the conclusion that for such an object functions copy.copy(obj) and copy.deepcopy(obj) will create a new object with the same value as the original object obj have:

>>> import copy
>>> obj = bytearray(b'hello')
>>> obj2 = copy.copy(obj)
>>> obj3 = copy.deepcopy(obj)
>>> obj2 is obj; obj3 is obj
False
False
>>> obj2 == obj; obj3 == obj
True
True

So, can you say that my conclusion is correct (in particular, there is no need to make a deep copy of a bytearray object – it is enough to make a shallow copy)? Maybe there are some other important details in this process (making a shallow or deep copy of a bytearray object) that I should be aware of?


Solution

  • The line you quoted is not precise. The distinction is relevant when the elements in the object have nested contents and are mutable. This makes it necessary for deepcopy() to process them recursively, making a deep copy of each of the elements.

    Since the elements of a byte array can only be integers, which don't have any nested contents, there's no need to recurse into them. So copy and deepcopy of a byte array are equivalent.

    copy and deepcopy don't copy immutable types because there's no need to. The purpose of making a copy is so that changes to one copy don't affect the other. But since you can't make changes to immutable objects, that's not a concern.

    But deepcopy() still has to recurse into immutable container types, because the contents might be mutable. In that case the container has to be copied as well. It can only avoid the copy if it's immutable all the way down.