| OLD | NEW |
| (Empty) |
| 1 # Copyright 2014 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 import collections | |
| 6 import operator | |
| 7 | |
| 8 | |
| 9 def freeze(obj): | |
| 10 """Takes a generic object ``obj``, and returns an immutable version of it. | |
| 11 | |
| 12 Supported types: | |
| 13 * dict / OrderedDict -> FrozenDict | |
| 14 * list -> tuple | |
| 15 * set -> frozenset | |
| 16 * any object with a working __hash__ implementation (assumes that hashable | |
| 17 means immutable) | |
| 18 | |
| 19 Will raise TypeError if you pass an object which is not hashable. | |
| 20 """ | |
| 21 if isinstance(obj, dict): | |
| 22 return FrozenDict((freeze(k), freeze(v)) for k, v in obj.iteritems()) | |
| 23 elif isinstance(obj, (list, tuple)): | |
| 24 return tuple(freeze(i) for i in obj) | |
| 25 elif isinstance(obj, set): | |
| 26 return frozenset(freeze(i) for i in obj) | |
| 27 else: | |
| 28 hash(obj) | |
| 29 return obj | |
| 30 | |
| 31 | |
| 32 def thaw(obj): | |
| 33 """Takes an object from freeze() and returns a mutable copy of it.""" | |
| 34 if isinstance(obj, FrozenDict): | |
| 35 return collections.OrderedDict( | |
| 36 (thaw(k), thaw(v)) for k, v in obj.iteritems()) | |
| 37 elif isinstance(obj, tuple): | |
| 38 return list(thaw(i) for i in obj) | |
| 39 elif isinstance(obj, frozenset): | |
| 40 return set(thaw(i) for i in obj) | |
| 41 else: | |
| 42 return obj | |
| 43 | |
| 44 | |
| 45 class FrozenDict(collections.Mapping): | |
| 46 """An immutable OrderedDict. | |
| 47 | |
| 48 Modified From: http://stackoverflow.com/a/2704866 | |
| 49 """ | |
| 50 def __init__(self, *args, **kwargs): | |
| 51 self._d = collections.OrderedDict(*args, **kwargs) | |
| 52 | |
| 53 # Calculate the hash immediately so that we know all the items are | |
| 54 # hashable too. | |
| 55 self._hash = reduce(operator.xor, | |
| 56 (hash(i) for i in enumerate(self._d.iteritems())), 0) | |
| 57 | |
| 58 def __eq__(self, other): | |
| 59 if not isinstance(other, collections.Mapping): | |
| 60 return NotImplemented | |
| 61 if self is other: | |
| 62 return True | |
| 63 if len(self) != len(other): | |
| 64 return False | |
| 65 for k, v in self.iteritems(): | |
| 66 if k not in other or other[k] != v: | |
| 67 return False | |
| 68 return True | |
| 69 | |
| 70 def __iter__(self): | |
| 71 return iter(self._d) | |
| 72 | |
| 73 def __len__(self): | |
| 74 return len(self._d) | |
| 75 | |
| 76 def __getitem__(self, key): | |
| 77 return self._d[key] | |
| 78 | |
| 79 def __hash__(self): | |
| 80 return self._hash | |
| 81 | |
| 82 def __repr__(self): | |
| 83 return 'FrozenDict(%r)' % (self._d.items(),) | |
| OLD | NEW |