Skip to content

Instantly share code, notes, and snippets.

@yuitest
Last active August 29, 2015 14:01
Show Gist options
  • Save yuitest/2c4aed0cc48bebae9361 to your computer and use it in GitHub Desktop.
Save yuitest/2c4aed0cc48bebae9361 to your computer and use it in GitHub Desktop.
イミュータブルにしたり戻したり。 dict やら list やら bytearray やらを tuple や byte やらに。
# 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)
@yuitest
Copy link
Author

yuitest commented May 12, 2014

乾燥ワカメみたいだ。

@yuitest
Copy link
Author

yuitest commented May 12, 2014

再帰つかいすぎなので、効率は悪いかもなー。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment