OLD | NEW |
(Empty) | |
| 1 # Copyright 2015 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 class FrozenDict(collections.Mapping): |
| 33 """An immutable OrderedDict. |
| 34 |
| 35 Modified From: http://stackoverflow.com/a/2704866 |
| 36 """ |
| 37 def __init__(self, *args, **kwargs): |
| 38 self._d = collections.OrderedDict(*args, **kwargs) |
| 39 |
| 40 # Calculate the hash immediately so that we know all the items are |
| 41 # hashable too. |
| 42 self._hash = reduce(operator.xor, |
| 43 (hash(i) for i in enumerate(self._d.iteritems())), 0) |
| 44 |
| 45 def __eq__(self, other): |
| 46 if not isinstance(other, collections.Mapping): |
| 47 return NotImplemented |
| 48 if self is other: |
| 49 return True |
| 50 if len(self) != len(other): |
| 51 return False |
| 52 for k, v in self.iteritems(): |
| 53 if k not in other or other[k] != v: |
| 54 return False |
| 55 return True |
| 56 |
| 57 def __iter__(self): |
| 58 return iter(self._d) |
| 59 |
| 60 def __len__(self): |
| 61 return len(self._d) |
| 62 |
| 63 def __getitem__(self, key): |
| 64 return self._d[key] |
| 65 |
| 66 def __hash__(self): |
| 67 return self._hash |
| 68 |
| 69 def __repr__(self): |
| 70 return 'FrozenDict(%r)' % (self._d.items(),) |
OLD | NEW |