I think immutable types like frozenset and tuple are not actually copied. How it's called? Does this make any difference?

I was busy trying to understand shallow and deep copying in Python and noticed that although the identifiers of the copied set, list, or seemingly any mutable type did not match:

In[2]: x1 = {1,2,3}
In[3]: x2 = x1.copy()
In[4]: x1 is x2
Out[4]: False

For immutable types, this is not the case - it looks like the copy points to the same address in memory.

In[6]: f1 = frozenset({1,2,3})
In[7]: f2 = f1.copy()
In[8]: f1 is f2
Out[8]: True

This type intuitively makes sense to me - why do you need two identical immutable objects in memory anyway. But I have never seen this before - is there a name for this process? Is this done for speed?

, - " "? , , - , , - , - , , , .

In[11]: t1 = tuple((1, ['a', 'b']))
In[12]: t2 = tuple(t1) # I would expect an actual copy, but it is not
In[13]: t1[1].append('c')
In[14]: t2
Out[14]: (1, ['a', 'b', 'c'])
+4
1

polymorphism.

__copy__() __deepcopy__() - , . copy ( set.copy()). self, .

self __copy__() .

, . . list(some_list_object) dict(some_dict_object). , , ; :

>>> import copy
>>> t1 = (1, ['a', 'b'])
>>> t2 = copy.deepcopy(t1)
>>> t1 is t2
False
>>> t1[0].append('c')
>>> t2
(1, ['a', 'b'])
+5

All Articles