Repository navigation
Add support for frozendict as AST Constant #150045
Description
Activity
Can you clarify what you need? This already works:
>>> import ast >>> ast.Constant(frozendict({"a": 1, "b": 1})) ... Constant(value=frozendict({'a': 1, 'b': 1}), kind=None) >>> ast.unparse(_) "frozendict({'a': 1, 'b': 1})"And I see no special casing for
frozensetin the AST module.Reacted by Lukas GeigerReacted by Lukas Geiger@JelleZijlstra sorry for the incomplete issue. I hit cmd-enter accidentally but you where faster than I could fix it 🚀.
Indeed defining a frozendict constant works. However it fails when compiling:
import ast node = ast.Expression(body=ast.Constant(value=frozendict({"a": 1}))) compile(ast.fix_missing_locations(node), "<string>", "eval")
I updated the issue comment. I am happy to submit a PR to fix this. I think I have it mostly working.
- addedtype-featureA feature request or enhancementA feature request or enhancement
on May 19, 2026 - addedinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)
on May 19, 2026 In the case of frozenset, we use frozenset to optimize code like
if x in {"spam", "ham", "egg"}.But would this kind of optimization really be useful for frozendict?
Or is there some other reason for frozendict to be supported by the AST?I am opposed to adding features that are not used just for the sake of symmetry with frozenset.
Reacted by Jelle Zijlstra, Peter Bierma, Bénédikt Tran, Kirill Podoprigora and Bartosz Sławecki- addedpendingThe issue will be closed if no feedback is providedThe issue will be closed if no feedback is provided
on May 19, 2026 I had another look at this, and indeed the additional optimisations are not really useful. I didn't realise that CPython itself won't actually create frozendicts as ast constants on its own which indeed doesn't make this a very useful optimisation. 37d8189 might still be useful in the future if having the ability to compile a frozendict ast constant similar to frozenset is desired. Closing this issue for now. Sorry about the noise.
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsDone
Currently the AST doesn't allow
frozendictas constants when compiled:This is implemented for
frozensetso it makes sense to do the same for
frozendict.Linked PRs
frozendictsupport to the compiler and AST constants #150050