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

Chris Angelico rosuav at gmail.com
Tue Jan 11 14:44:11 EST 2022


On Wed, Jan 12, 2022 at 5:49 AM Marco Sulla
<Marco.Sulla.Python at gmail.com> wrote:
>
> Ok... so I suppose, since you're inviting me to use dis and look at the bytecode, that are you talking about constants in assembly, so const in C? Sorry for the confusion, I'm not so skilled in C and I know nearly nothing about assembly. Furthermore I never look at the bytecode of any language before, so I simply didn't understand you.
>

No, I'm talking about constants in Python.

> I think this is what you mean:
>
> >>> dis.dis("for _ in {1, 2}: pass")
>   1           0 SETUP_LOOP              12 (to 14)
>               2 LOAD_CONST               3 (frozenset({1, 2}))

This is a constant.

>               4 GET_ITER
>         >>    6 FOR_ITER                 4 (to 12)
>               8 STORE_NAME               0 (_)
>              10 JUMP_ABSOLUTE            6
>         >>   12 POP_BLOCK
>         >>   14 LOAD_CONST               2 (None)

This is a constant.

>              16 RETURN_VALUE
> >>> a = {1, 2}
> >>> dis.dis("for _ in a: pass")
>   1           0 SETUP_LOOP              12 (to 14)
>               2 LOAD_NAME                0 (a)
>               4 GET_ITER
>         >>    6 FOR_ITER                 4 (to 12)
>               8 STORE_NAME               1 (_)
>              10 JUMP_ABSOLUTE            6
>         >>   12 POP_BLOCK
>         >>   14 LOAD_CONST               0 (None)

This is a constant.

>              16 RETURN_VALUE
>

Try the same thing with other code and see whether you can see a
difference. In other words, *play around with dis.dis*.

If you're trying to hack on the internals of the CPython dictionary
implementation and do not understand how Python bytecode is executed,
you are doomed to make many MANY errors of judgment about performance.

ChrisA


More information about the Python-list mailing list