Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(88)

Side by Side Diff: infra/libs/types/types.py

Issue 355153002: Refactor infra git libs and testing. (Closed) Base URL: https://chromium.googlesource.com/infra/infra@fake_testing_support
Patch Set: Change config ref to have a sandard naming scheme Created 6 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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 if isinstance(obj, dict):
20 return FrozenDict((freeze(k), freeze(v)) for k, v in obj.iteritems())
21 elif isinstance(obj, (list, tuple)):
22 return tuple(freeze(i) for i in obj)
23 elif isinstance(obj, set):
24 return frozenset(freeze(i) for i in obj)
25 else:
26 hash(obj)
27 return obj
28
29
30 def thaw(obj):
31 """Takes an object from freeze() and returns a mutable copy of it."""
32 if isinstance(obj, FrozenDict):
33 return collections.OrderedDict(
34 (thaw(k), thaw(v)) for k, v in obj.iteritems())
35 elif isinstance(obj, tuple):
36 return list(thaw(i) for i in obj)
37 elif isinstance(obj, frozenset):
38 return set(thaw(i) for i in obj)
39 else:
40 return obj
41
42
43 class FrozenDict(collections.Mapping):
44 """An immutable OrderedDict.
45
46 Modified From: http://stackoverflow.com/a/2704866
47 """
48 def __init__(self, *args, **kwargs):
49 self._d = collections.OrderedDict(*args, **kwargs)
50
51 # calculate the hash immediately so that we know all the items are
52 # hashable too.
53 self._hash = reduce(operator.xor,
54 (hash(i) for i in enumerate(self._d.iteritems())), 0)
55
56 def __eq__(self, other):
57 if not isinstance(other, collections.Mapping):
58 return NotImplemented
59 if self is other:
60 return True
61 if len(self) != len(other):
62 return False
63 for k, v in self.iteritems():
64 if k not in other or other[k] != v:
65 return False
66 return True
67
68 def __iter__(self):
69 return iter(self._d)
70
71 def __len__(self):
72 return len(self._d)
73
74 def __getitem__(self, key):
75 return self._d[key]
76
77 def __hash__(self):
78 return self._hash
79
80 def __repr__(self):
81 return 'FrozenDict(%r)' % (self._d.items(),)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698