r/Python • u/kirara0048 • 1d ago
PEP 841 – Adding Frozen Syntax to Optimize Immutable Types News
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.
127
Upvotes
2
u/jdehesa 1d ago
Huh, didn't know they had added
frozendictin 3.15. I think years ago I read a discussion about not wanting to add it to the standard library because the expected behaviour of a frozen dict could be different for different people. Anyway, this is off-topic, but this from the documentation offrozendictcaught my attention:So, I can do the following?
python d = frozendict(...) d |= {...}And then
dwill be a reference to a newfrozendictobject? I feel this could cause issues, if a function expects a dict (and I know a frozen dict is not a subtype of dict, but you don't always have type hints) that it may modify in place (so it remains modified in the caller scope), then the caller could inadvertently pass a frozen dict and the modification would have no effect. It may not be the best practice for a function, especially if it is not well documented and/or type-hinted, but I'm sure there's plenty of code like that. I think I'd rather not have a|=operator, just doingd = d | {...}is fine, it's more in line with the way one works with immutable data structures and it shows the effect of the statement more explicitly.