Inspired by Add zero-copy conversion of `bytearray` to `bytes` by providing `__bytes__()` - #18 by storchaka, what I would love to have is a zero-copy dict.freeze method that constructs in O(1) time a frozendict instance, a hashable, picklable and immutable object that shares the same hash table with the original dict. This allows a dict to be efficiently made “gold” after it’s iteratively built.
And then one of the following two things can happen after dict.freeze:
- The original
dictgets cleared by getting a new allocation of an empty hash table if its reference count is 1. Make a copy if the reference count isn’t 1. - The original
dictkeeps a pointer to thefrozendictsuch that if thedictever gets mutated (via either Python or C API), thefrozendictwould then make a copy of the hash table and detaches.
To me option 1 would be good enough for my use cases, while option 2 offers more flexibility at the cost of an extra pointer per dict.