python-frozendict
python-frozendict copied to clipboard
Recursive freeze and unfreeze functions
Theses are two symmetrical functions to make entire structures immutable and mutable respectively. Converting dict and OrderedDict will behave as expected. All lists are turned into tuples and vice versa.
I have based on #15 to integrate with the testing. If this is of interest I will consider adding hypothesis tests to show that freeze(unfreeze(x)) == x and unfreeze(freeze(x)) == x hold true given completely frozen or unfrozen data structures respectively.
Not sure what to do about generators; i.e. should freeze(x for x in [1,2,3]) == freeze([1,2,3]) ?
What is the use case for those functions?
It's a uniform way to create completely immutable complex data structures (freeze) and to make any immutable data structure as mutable as possible (unfreeze). These have parallels in Immutable.js as fromJS and toJS where I have gotten used using them mostly for dealing with immutable state trees when using Redux.
In Python, personally I am using them while working on an application that uses Pydux, with these utility functions I can easily define a complex immutable structure using the more compact Python native notation and unfreeze and refreeze it if I need to make a lot of edits.
Hopping in; even though I like the idea since it does seem very nice mathematically (like an inverse function), I have to strongly disagree with putting this in the frozendict library. The basis being that, this is a library for frozen dictionaries, nothing less, nothing more. Placing such a function in this library would mean that we have to now think about other types which is not in the scope of this library.
TLDR: This functionality deserves its own library. Perhaps call it libfreeze or something.
@kasbah Have you ever released this as libfreeze? It would be great to have a function to give an immutable Python object.
No, not yet. I am still using them in my own project though. Feel free to copy them from here and use under the MIT license.
Nice. You could also add support for set -> frozenset.