-
Notifications
You must be signed in to change notification settings - Fork 0
/
recorder.py
99 lines (80 loc) · 3.09 KB
/
recorder.py
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
class Recorder(object):
suffixes = ['all']
def _splitNameSuffix(name):
if '_' in name:
last_ = -name[::-1].find('_')
first = name[:last_-1]
last = name[last_:]
return first,last
else:
return name,""
def __init__(self):
self.recorded = {}
def addVariable(self,name,value=None):
name_,suffix = Recorder._splitNameSuffix(name)
if name in self.recorded:
raise AttributeError('{} already in Recorder'.format(name))
elif suffix in Recorder.suffixes:
raise AttributeError(
'\"{}\" conflicts with the reserved suffixes: {}'.format(
name,Recorder.suffixes))
else:
if value is None:
self.recorded[name] = []
else:
self.recorded[name] = [value]
def addVariables(self,names,values=None):
# values can be either a single value for all or a list or None
if not isinstance(values,list):
for name in names:
self.addVariable(name,values)
elif len(values) == len(names):
for name,value in zip(names,values):
self.addVariable(name,value)
elif values is None:
for name,value in names:
self.addVariable(name)
else:
raise AttributeError('list of values not compatible')
def historyOf(self,name):
if name in self.recorded:
return self.recorded[name]
else:
raise AttributeError('{} not in Recorder'.format(name))
def resetHistoryOf(self,name,value=None):
if value is None:
value = []
elif not isinstance(value,list):
value = [value]
if name in self.recorded:
self.recorded[name] = value
else:
raise AttributeError('{} not in Recorder'.format(name))
def __getattribute__(self, name):
if name == 'recorded':
return super().__getattribute__(name)
else:
name_,suffix = Recorder._splitNameSuffix(name)
if name_ in self.recorded and name not in self.recorded:
if len(self.recorded[name_]) > 0 and not suffix:
return self.recorded[name_][-1]
elif suffix == "all":
return self.recorded[name_]
else:
return None
elif name in self.recorded:
if len(self.recorded[name]) > 0:
return self.recorded[name][-1]
else:
return None
else:
return super().__getattribute__(name)
def __setattr__(self, name, value):
if name == 'recorded':
super().__setattr__(name,value)
else:
if name in self.recorded:
self.recorded[name].append(value)
else:
super().__setattr__(name,value)
# raise AttributeError('{} not found in Recorder'.format(name))