Created
November 30, 2017 11:32
-
-
Save stephanh42/d277170dd8a3a2f026c272a4fda15396 to your computer and use it in GitHub Desktop.
Convert object into a read-only (frozen) variant. Well, to the extent possible.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import singledispatch | |
from types import MappingProxyType | |
@singledispatch | |
def freeze(obj): | |
"""Convert obj into a read-only (frozen) variant. Well, to the extent possible.""" | |
""" Example: foo = freeze({"x": [1,2,{3,4}]}) | |
""" | |
return obj # not much frost today | |
@freeze.register(tuple) | |
@freeze.register(list) | |
def freeze_list(obj): | |
return tuple(freeze(x) for x in obj) | |
@freeze.register(set) | |
@freeze.register(frozenset) | |
def freeze_set(obj): | |
return frozenset(freeze(x) for x in obj) | |
@freeze.register(dict) | |
@freeze.register(MappingProxyType) | |
def freeze_dict(obj): | |
return MappingProxyType({k: freeze(v) for k, v in obj.items()}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment