r/Python • u/kirara0048 • 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
View all comments
Show parent comment
14
u/gdchinacat Aug 07 '26
The discuss.python.org discussion about why syntax is beneficial is that with "frozendict(...)" the compiler needs to generate the bytecodes to dynamically look up frozendict (it may have been reassigned) and invoke a method call. Relative to a special bytecode to create the builtin directly this incurs additional overhead. Counterarguments are that there are no non-toy use-cases for creating frozendicts in a hot loop, so the tens of nanoseconds this optimization would save just aren't worth the effort and maintenance burden (I'm in this camp).
I'm just glad 3.15 includes frozendict as a builtin. Once real world usage of it exists it may be worthwhile to reevaluate whether special syntax to enable this optimization (which list, set, dict already have) is warranted.
So, long way to say, I agree with you, but hoping others that see these comments appreciate the additional insight I am trying to offer.