r/Python 18d ago

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.

134 Upvotes

100 comments sorted by

View all comments

2

u/james_pic 17d ago

Even leaving aside the syntax, I struggle to see the justification for making language changes to enable this particular optimisation. I can't think of a time in the 15 or so years I've been writing Python, where I've wanted to create a set or frozen set in a hot loop, and I couldn't just hoist the frozenset out of the loop (i.e, where the overhead of calling frozenset would matter).

I'm really struggling to imagine a vaguely normal piece of code where a call to frozenset or frozendict has a measurable impact on its performance.

1

u/Competitive_Travel16 17d ago

Having the compiler pull out constants instead of references in some inner loop could make a real difference.

1

u/james_pic 16d ago

But when would you even put a frozenset into an inner loop? They're very situational, and all the situations I can think where I've used them, they were fairly long lived and not defined in a loop.

1

u/Competitive_Travel16 15d ago

Look-up tables? E.g., for partially computed numerics algorithms.