Dictionaries are ubiquitous in Python code; they are the data structure of choice for a wide variety of tasks. But dictionaries are mutable, which makes them problematic for sharing data in concurrent code. Python has added various concurrency features to the language over the last decade or so-async,free threading without the global interpreter lock (GIL),and self-reliant subinterpreters-but users must work out their own solution for an immutable dictionary that can be safely shared by concurrent code.There are existing modules that could be used, but a recent proposal, PEP 814 (“Add frozendict built-in type”), looks to bring the feature to the language itself.
Victor stinner announced the PEP that he and Donghee Na have authored in a post to the PEPs category of the Python discussion forum on November 13. The idea has come up before, including in PEP 416 which has essentially the same title as 814 and was authored by Stinner back in 2012. It was rejected by Guido van Rossum at the time, in part due to its target: a Python sandbox that never really panned out.
frozendict
Table of Contents
The idea is fairly straightforward: add frozendict as a new immutable type to the language’s builtins module.As Stinner put it:
> We expect frozendict to be safe by design, as it prevents any unintended modifications. This addition benefits not only CPython’s standard libary, but also third-party maintainers who can take advantage of a reliable, immutable dictionary type.
While frozendict has a lot in common with the
Python Gets a New Immutable Dictionary Type
Python 3.12, released in October 2023, added a new built-in type called frozendict. This type is similar to a regular dictionary (dict), but it’s immutable – meaning you can’t change it after it’s created. This can definitely help prevent accidental changes to your data and make your code more reliable.
What is a frozendict?
A frozendict acts like a dict, but it can’t be changed. The specific differences between the two are listed in the PEP. The Python documentation also includes a list of places in python’s core code were a regular dict could be replaced with a frozendict to improve safety.
Discussion
The response to adding frozendict was mostly positive. Developers offered suggestions for improvements. One concern was that converting a dict to a frozendict takes time – specifically,it creates a copy of the dictionary. Daniel F Moisset suggested a faster way: a .freeze() method that would simply change the existing dictionary into a frozendict without copying.
However, Brett Cannon explained that changing an object’s type after it’s created can cause unexpected problems:
But now you have made that dictionary frozen for everyone who holds a reference to it, which means side-effects at a distance in a way that could be unexpected (e.g.context switch in a thread and now suddenly you’re going to get an exception trying to mutate what was a dict a microsecond ago but is now frozen).
Worth a look