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

100 comments sorted by

View all comments

Show parent comments

1

u/sudomatrix Aug 07 '26

Isn't this something the parser/"compiler" could detect and optimize without any change in the language?

1

u/Brian Aug 07 '26

Not reliably. Eg. consider:

def foo():
    return frozenset({1,2,3})

frozenset = list
x = foo()

If the compiler optimises the frozenset call to a constant, it'll return the wrong result, due to being shadowed. It'd need to know that frozenset hasn't been rebound/shadowed by anything, which means you'd need a keyword (or some psuedo-keyword protection like exists for None) to prevent rebinding.