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

Chris Angelico rosuav at gmail.com
Wed Jan 5 17:00:13 EST 2022


On Thu, Jan 6, 2022 at 8:01 AM Marco Sulla <Marco.Sulla.Python at gmail.com> wrote:
>
> On Wed, 5 Jan 2022 at 14:16, Chris Angelico <rosuav at gmail.com> wrote:
> > That's an entirely invisible optimization, but it's more than just
> > "frozenset is faster than set". It's that a frozenset or tuple can be
> > stored as a function's constants, which is a massive difference.
>
> Can you explain this?

Play around with dis.dis and timeit.

> > Function positional arguments aren't interchangeable, so it makes
> > sense to have them as a tuple.
>
> You are wrong, since kwarg is a dict. Indeed I proposed to use
> frozendict for kwargs, and Guido said that it's a pity that this will
> break a lot of existing Python code :D, since the fact that args is
> _immutable_ and kwargs not always bothered him.

Excuse me? I mentioned kwargs in the part that you removed from the
quote, and the part you're quoting explicitly says "positional
arguments".

> Anyway, I'm starting to think that neither set nor frozenset are good
> for dict items:
>
> (venv_3_10) marco at buzz:~$ python
> Python 3.10.0 (heads/3.10-dirty:f6e8b80d20, Nov 18 2021, 19:16:18)
> [GCC 10.1.1 20200718] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> a = {1: 2}
> >>> b = {3: []}
> >>> a | b
> {1: 2, 3: []}
> >>> a.items() | b.items()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unhashable type: 'list'
> >>>

Well yes. Only dict keys can be considered to be set-like. I don't
know WHAT you think you're trying to do here, but if you ever thought
of set operations on dict values, you may want to completely rethink
what you're doing.

Performance is not an automatic result of immutability. That simply
isn't how it works.

ChrisA


More information about the Python-list mailing list