Last active
August 29, 2015 14:01
-
-
Save yuitest/2c4aed0cc48bebae9361 to your computer and use it in GitHub Desktop.
イミュータブルにしたり戻したり。 dict やら list やら bytearray やらを tuple や byte やらに。
This file contains hidden or 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
# coding: utf8 | |
def immutable(o): | |
recursion = immutable | |
if isinstance(o, dict): | |
return tuple((k, recursion(v)) for k, v in o.iteritems()) | |
elif isinstance(o, list): | |
return tuple(recursion(v) for v in o) | |
elif isinstance(o, bytearray): | |
return bytes(o) | |
else: | |
return o | |
def mutable(o, *args): | |
recursion = mutable | |
if not args: | |
return o | |
first, rest = args[0], args[1:] | |
if issubclass(first, dict): | |
return first((k, recursion(v, *rest)) for k, v in o) | |
elif issubclass(first, list): | |
return first(recursion(v, *rest) for v in o) | |
else: | |
return first(o) | |
if __name__ == '__main__': | |
assert immutable( | |
{'a': ['b', {'c': 'd'}]}) == (('a', ('b', (('c', 'd'),))),) | |
k = [{'point': {'x': 1, 'y': 2}}, {'point': {'x': 2, 'y': 1}}] | |
assert mutable(immutable(k), list, dict, dict) == k | |
assert mutable(immutable(k), list, dict, dict, float) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
乾燥ワカメみたいだ。