r/Python • • Aug 07 '26

News PEP 841 – Adding Frozen Syntax to Optimize Immutable Types

PEP 841 – Adding Frozen Syntax to Optimize Immutable Types

https://peps.python.org/pep-0841/

Discussions-To: Discourse thread

Abstract

This PEP proposes frozen display syntax: f{1, 2, 3} evaluates to a frozenset, and f{'a': 1} evaluates to a frozendict. Because immutability is guaranteed by the syntax itself rather than inferred from usage, the compiler can treat frozen displays as first-class citizens of its optimization pipeline: constant displays are folded into a single LOAD_CONST with an exact result type at compile time and cached in .pyc files.

139 Upvotes

99 comments sorted by

View all comments

Show parent comments

1

u/Wonderful-Habit-139 Aug 07 '26

>>> a = 2
>>> b = a
>>> a += 1
>>> b
2

There's no footgun with += compared to |= with sets. a += 1 behaves exactly like a = a + 1, while s |= {1} does not behave like s = s | {1}.

1

u/HommeMusical Aug 07 '26

there's no footgun with += compared to |= with sets

It seems exactly the same footgun with list, too?

>>> a = [1]
>>> b = a
>>> a += [1]
>>> b
[1, 1]

Heck, it even works on numpy or pytorch scalars.

>>> a = np.array(1)
>>> b = a
>>> a += 1
>>> b
array(2)

On the other hand, if a and b are int, then |= is fine:

>>> a = 1
>>> b = a
>>> a |= 2
>>> a, b
(3, 1)

Whether it's a footgun depends entirely on the type of the operands, and not on the operator.

1

u/Wonderful-Habit-139 Aug 07 '26

Yeah it has to do with the operands, realized it the moment I sent the message.

But yeah for me that is the footgun, not whatever is specific to frozendict.

2

u/HommeMusical Aug 07 '26

All the "i-operators", <something>= operators do this! If you don't like this behavior, there's no need to use them at all.

You only use them because you specifically want this "mutate in place" behavior.

1

u/Wonderful-Habit-139 Aug 07 '26

Yeah, that was a good discovery. I prefer to do things the functional way, so I now know to steer clear from those operators. Thanks!

→ More replies (0)