python Python PEPs ·

Python PEP 841: Frozen syntax for immutable types

engineer
feature announcement

This PEP proposes new syntax, f{...}, for creating immutable sets and dictionaries in Python, aiming to improve compiler optimizations and encourage the use of immutable containers. By providing guaranteed immutability at compile time, this feature allows for constant folding and caching in .pyc files, reducing runtime overhead. This change is particularly relevant for future concurrent programming models in Python and will affect developers working with data structures.

  • Introduce frozen display syntax for frozensets and frozendicts
  • Add new AST nodes and bytecode instructions
  • Improve compiler optimization for immutable types
  • Encourage use of immutable containers for concurrency
  • Ensure backward compatibility and tooling integration
Features (2)
  • Introduce frozen display syntax for frozensets and frozendicts

    The proposed PEP 841 introduces a new frozen display syntax, f{...}, to create frozensets and frozendicts directly. This syntax offers an alternative to current methods like frozenset({...}) which involve creating mutable collections and then converting them, thereby reducing runtime lookups and allowing for compiler optimizations.

  • Add new AST nodes and bytecode instructions

    Four new AST nodes (FrozenSet, FrozenDict, FrozenSetComp, FrozenDictComp) and two new bytecode instructions, BUILD_FROZENSET and BUILD_FROZENMAP, are proposed to handle the new syntax. These changes are designed to be structurally identical to their mutable counterparts but explicitly signal immutability.

Enhancements (2)
  • Improve compiler optimization for immutable types

    The frozen display syntax guarantees immutability at compile time, enabling the compiler to treat these constructs as first-class citizens for optimization. This includes constant folding, caching in .pyc files, and potentially zero per-execution construction cost for constant displays.

  • Encourage use of immutable containers for concurrency

    The PEP aims to increase the adoption of immutable containers like frozendict and frozenset in CPython, which is beneficial for future concurrent programming models involving free-threading and subinterpreters. This can help reduce bugs from accidental mutation and improve performance.

Notes (1)
  • Ensure backward compatibility and tooling integration

    The proposed syntax f{ is backward compatible as it is a syntax error in current Python versions. Tooling integration is considered, with potential for linters and formatters to automatically rewrite existing frozenset and frozendict calls to the new syntax.

Read the original announcement →

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

Related releases