Why operations between dict views return a set and not a frozenset?

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Tue Jan 4 23:09:42 EST 2022


On 2022-01-05 at 08:30:30 +1100,
Cameron Simpson <cs at cskk.id.au> wrote:

> On 04Jan2022 21:03, Marco Sulla <Marco.Sulla.Python at gmail.com> wrote:
> >On Tue, 4 Jan 2022 at 19:38, Chris Angelico <rosuav at gmail.com> wrote:
> >> [...] should the keys view be considered
> >> frozen or not? Remember the set of keys can change (when the
> >> underlying dict changes).
> >
> >Well, also the items can change, but they are returned as tuples with
> >2 elements.
> >
> >It seems to me that the stdlib, when something should return a
> >sequence, prefers to return a tuple. So I expected the same preference
> >for frozenset over set.
> >
> >> It's not difficult to construct a frozenset from a set.
> >
> >This sentence has the commutative property :)
> 
> Indeed.
> 
> But speaking for myself, I may well want to perform additional work on 
> the object returned. Making a copy of it for tht purpose seems very 
> wasteful (imagine the set is quite large). A modifiable version can be 
> used immediately with no time or space cost. And it can be left alone if 
> it is to be unchanged.  If I got a frozenset back I would inherently 
> have to copy it to do "modifying work".

Unless the additional work is to use it as a dictionary key, or to add
it to an existing [necessarily mutable!] set.  Then again, that's not
work *on* the object returned, that's additional work *with* the object
returned.

We could go around and around on this all day.  :-)

Python began with the premise of mutability.  IIRC, many attempts at
immutable class instances (for use in sets or as dictionary keys) have
run into the same issues Marco Sulla is having.


More information about the Python-list mailing list