-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathabc.py
More file actions
269 lines (206 loc) · 7.37 KB
/
Copy pathabc.py
File metadata and controls
269 lines (206 loc) · 7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
from hashlib import sha1
__all__ = ['Pickable', 'Reconstructable', 'Signer', 'Singleton', 'Stamp', 'Tag']
class Tag:
"""
An abstract class to define categories of object decorators.
Notes
-----
This class must be subclassed for each new category.
"""
def __init__(self, name, val=None):
self.name = name
self.val = val
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.name == other.name and self.val == other.val
def __lt__(self, other):
return self.val < other.val
def __le__(self, other):
return self.val <= other.val
def __gt__(self, other):
return self.val > other.val
def __ge__(self, other):
return self.val >= other.val
def __hash__(self):
return hash((self.name, self.val))
def __str__(self):
ret = self.name if self.val is None else f"{self.name}[{str(self.val)}]"
return ret
__repr__ = __str__
class Signer:
"""
A base class for types that can emit a unique, deterministic
string representing their internal state. Subclasses may be mutable or
immutable.
Notes
-----
Subclasses must implement the method :meth:`__signature_items___`.
Regardless of whether an object is mutable or immutable, the returned
signature must be immutable, and thus hashable.
"""
@classmethod
def _digest(cls, *signers):
"""Produce a unique, deterministic signature out of one or more
``signers`` objects."""
items = []
for i in signers:
try:
items.extend(list(i._signature_items()))
except AttributeError:
items.append(str(i))
return cls._sign(items)
@classmethod
def _sign(cls, items):
return sha1(''.join(items).encode()).hexdigest()
def _signature_items(self):
"""Return a tuple of items from which the signature is computed. The
items must be string. This method must be deterministic (i.e., the items
must always be returned in the same order, even across different runs)."""
return ()
def _signature(self):
return Signer._sign(self._signature_items())
class Reconstructable:
__rargs__ = ()
"""
The positional arguments to reconstruct the object.
"""
__rkwargs__ = ()
"""
The keyword arguments to reconstruct the object.
"""
def _rebuild(self, *args, **kwargs):
"""
Reconstruct `self` via `self.__class__(*args, **kwargs)` using
`self`'s `__rargs__` and `__rkwargs__` if and where `*args` and
`**kwargs` lack entries.
Examples
--------
Given
class Foo:
__rargs__ = ('a', 'b')
__rkwargs__ = ('c',)
def __init__(self, a, b, c=4):
self.a = a
self.b = b
self.c = c
a = foo(3, 5)`
Then:
* `a._rebuild() -> x(3, 5, 4)` (i.e., copy of `a`).
* `a._rebuild(4) -> x(4, 5, 4)`
* `a._rebuild(4, 7) -> x(4, 7, 4)`
* `a._rebuild(c=5) -> x(3, 5, 5)`
* `a._rebuild(1, c=7) -> x(1, 5, 7)`
"""
for i in self.__rargs__[len(args):]:
if i.startswith('*'):
args += tuple(getattr(self, i[1:]))
else:
args += (getattr(self, i),)
args = list(args)
for k in list(kwargs):
if k in self.__rargs__:
args[self.__rargs__.index(k)] = kwargs.pop(k)
kwargs.update({i: getattr(self, i) for i in self.__rkwargs__ if i not in kwargs})
# If this object has SymPy assumptions associated with it, which were not
# in the kwargs, then include them
try:
assumptions = self._assumptions_orig
kwargs.update({k: v for k, v in assumptions.items() if k not in kwargs})
except AttributeError:
pass
return self.__class__(*args, **kwargs)
class Pickable(Reconstructable):
"""
A base class for types that require pickling. There are several complications
that this class tries to handle: ::
* Packages such as SymPy have their own way of handling pickling -- though
still based upon Python's pickle module. This may get in conflict with
other packages, or simply with Devito itself. For example, most of Devito
symbolic objects are created via ``def __new__(..., **kwargs)``; SymPy1.1
pickling does not cope nicely with ``new`` and ``kwargs``, since it is
based on the low-level copy protocol (__reduce__, __reduce_ex__) and
simply end up ignoring ``__getnewargs_ex__``, the function responsible
for processing __new__'s kwargs.
Notes
-----
All sub-classes using multiple inheritance may have to explicitly set
``__reduce_ex__ = Pickable.__reduce_ex__`` depending on the MRO.
"""
@property
def _pickle_rargs(self):
"""
The positional arguments that need to be passed to __new__ upon unpickling.
"""
# NOTE: Backward compatibility
try:
return self._pickle_args
except AttributeError:
pass
return self.__rargs__
@property
def _pickle_rkwargs(self):
"""
The keyword arguments that need to be passed to __new__ upon unpickling.
"""
# NOTE: Backward compatibility
try:
return self._pickle_kwargs
except AttributeError:
pass
return self.__rkwargs__
@staticmethod
def _pickle_wrapper(cls, args, kwargs):
return cls.__new__(cls, *args, **kwargs)
@property
def _pickle_reconstructor(self):
"""
Return the callable that should be used to reconstruct ``self`` upon
unpickling. If None, default to whatever Python's pickle uses.
"""
# NOTE: Backward compatibility
try:
return self._pickle_reconstruct
except AttributeError:
pass
return None
def __reduce_ex__(self, proto):
ret = object.__reduce_ex__(self, proto)
reconstructor = self._pickle_reconstructor
if reconstructor is None:
return ret
else:
# Instead of the following wrapper function, we could use Python's copyreg
_, (_, args, kwargs), state, iter0, iter1 = ret
return (
Pickable._pickle_wrapper,
(reconstructor, args, kwargs),
state,
iter0,
iter1,
)
def __getnewargs_ex__(self):
args = []
for i in self._pickle_rargs:
if i.startswith('*'):
args.extend(getattr(self, i[1:]))
else:
args.append(getattr(self, i))
kwargs = {i: getattr(self, i) for i in self._pickle_rkwargs}
return (tuple(args), kwargs)
class Singleton(type):
"""
Metaclass for singleton classes.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Stamp:
"""
Uniquely identify objects.
"""
def __repr__(self):
return f"<{str(id(self))[-3:]}>"
__str__ = __repr__