-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvar_type.py
executable file
·74 lines (62 loc) · 2.72 KB
/
var_type.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
"""
A class that holds a global variable type
This is essentially a dictionary that can have its fields accessed like this:
gvars.VLOG.FIELD_NAME
Here, VLOG is the instance of VarType in the gvars module, and FIELD_NAME is the entry in this
class's dictionary.
"""
__VALUE__, __TYPES__, __HELP__ = range(3)
Log = None
class VarType(object):
def __init__(self, v_dict, v_type):
self.myvars = v_dict.copy()
self.v_type = v_type
#--------------------------------------------
def __setattr__(self, name, value):
if name in ('myvars', 'v_type'):
object.__setattr__(self, name, value)
return
try:
if type(value) not in self.myvars[name][__TYPES__]:
raise AttributeError("%s is not permitted for %s" % (type(value), name))
self.myvars[name][__VALUE__] = value
except KeyError:
Log.critical("The variable %s.%s does not exist. Perhaps one of these instead?\n\t%s" % (self.v_type, name, self.myvars.keys()))
#--------------------------------------------
def __getattr__(self, name):
return self.myvars[name][__VALUE__]
#--------------------------------------------
def __repr__(self):
d = dict([(key,self.myvars[key][__VALUE__]) for key in self.myvars.keys()])
return d.__repr__()
#--------------------------------------------
def set_value(self, name, value):
# value will be a string
# cast for correct type if necessary
my_value = self.cast_for_types(name, value)
Log.debug("Setting %s to %s" % (name, my_value))
self.__setattr__(name, my_value)
#--------------------------------------------
def incr_value(self, name, value):
my_value = self.cast_for_types(name, value)
curr_val = self.__getattr__(name)
Log.debug("Setting %s to %s + %s = %s" % (name, curr_val, my_value, (curr_val + my_value)))
self.__setattr__(name, (curr_val + my_value))
#--------------------------------------------
def help(self, name):
return self.myvars[name][__HELP__]
#--------------------------------------------
def cast_for_types(self, name, value):
my_value = value if isinstance(value, self.myvars[name][__TYPES__]) else None
if not my_value:
# try casting to each of the possible types until one is found
for my_type in self.myvars[name][__TYPES__]:
try:
t = my_type(value)
except TypeError:
continue
else:
my_value = t
if my_value is None:
Log.critical("%s cannot go into %s.%s" % (value, self.v_type, name))
return my_value