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

Chris Angelico rosuav at gmail.com
Tue Jan 4 18:52:41 EST 2022


On Wed, Jan 5, 2022 at 7:04 AM 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.

That's because a tuple is the correct data type when returning two
distinct items. It's not a list that has two elements in it; it's a
tuple of (key, value). Immutability is irrelevant.

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

Got any examples of variable-length sequences? Usually a tuple is a
structure, not just a sequence. If something is just returning a
sequence, it'll most often return a dedicated sequence type (like
range in Py3) or a list (like lots of things in Py2).

ChrisA


More information about the Python-list mailing list