Python Forum

Full Version: frozenset.copy() docs wrong
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i read in doc that frozenset.copy() returns a shallow copy but i got a deep copy. which is wrong? docs or implementation? i believe the docs are wrong.
Quote:i read in doc that frozenset.copy() returns a shallow copy
That is correct.

Quote:but i got a deep copy
What makes you say that? Can you show code in which this happens?
Output:
t2a/forums /home/forums 3> py3 Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = frozenset([frozenset([frozenset(['foo','bar'])])]) >>> x frozenset({frozenset({frozenset({'foo', 'bar'})})}) >>> frozenset.copy(x) frozenset({frozenset({frozenset({'foo', 'bar'})})}) >>> lt2a/forums /home/forums 4>
That just shows you have a copy.
Maybe you're not familiar with the terminology?
There's a definition of shallow vs deep copy at https://docs.python.org/3/library/copy.html
can you be more specific about the Python terminology you think i'm not familiar with, as opposed to the generic terminology for shallow and deep copy?
From the linked docs:
Quote:A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

So, when printed, both a shallow and deep copy will look the same:
>>> import copy
>>> original = [1, [2, 3], 4]
>>> shallow = original.copy()
>>> deep = copy.deepcopy(original)
>>> original
[1, [2, 3], 4]
>>> shallow
[1, [2, 3], 4]
>>> deep
[1, [2, 3], 4]
The difference is whether the objects inside the copy are references to the originals or copies:
>>> original[1] is shallow[1]
True
>>> original[1] is deep[1]
False
so how do we test if the copies are references or reconstructions? id() ??
If you want to check if an object is a copy or a reference to the same object, using the is operator is probably simplest.
It only matters for mutable objects that you plan on modifying, though.
i wasn't wanting to check for an application purpose, but to study that copy method. as far as i can see, for immutable objects like an instance of frozenset, there is no value to know if it is a copy or a reference to a shared instance. ultimately, whether a copy method of an immutable object does a (recursive) full copy or makes a new reference (however the implementation carries that out), it doesn't really matter, at all. so the difference is moot. there is no real point to define the difference besides beginners potentially not understanding why it might be omitted.