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

Marco Sulla Marco.Sulla.Python at gmail.com
Wed Jan 5 16:00:34 EST 2022


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?

> In fact, the two data types are virtually identical in performance once created [...]

This is really strange, since in theory frozenset should not have to
check if itself is mutated during the iteration, on each cycle. So the
speed should be noticeable faster. Maybe frozenset was not optimised,
because the use case is really little and will add potentially useless
C code? Furthermore, more the code, more the memory consumption and
less the speed. I have to check setobject.c.

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

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


More information about the Python-list mailing list