1282dfec5dc7931aa47ac0a2e32ba35cacfda55c
[nepi.git] / src / neco / execution / attribute.py
1
2 ### Attribute Types
3 class Types:
4     String  = "STRING"
5     Bool    = "BOOL"
6     Enum    = "ENUM"
7     Double  = "DOUBLE"
8     Integer = "INTEGER"
9
10 ### Attribute Flags
11 class Flags:
12     # Attribute can be modified by the user 
13     NoFlags         = 0x00
14     # Attribute is not modifiable by the user
15     ReadOnly        = 0x01
16     # Attribute is not modifiable by the user during runtime
17     ExecReadOnly        = 0x02
18     # Attribute is an access credential
19     Credential      = 0x04
20
21 class Attribute(object):
22     def __init__(self, name, help, type = Types.String,
23             flags = Flags.NoFlags, default = None, allowed = None,
24             set_hook = None):
25         self._name = name
26         self._help = help
27         self._type = type
28         self._flags = flags
29         self._allowed = allowed
30         self._default = self._value = default
31         # callback to be invoked upon changing the 
32         # attribute value
33         self.set_hook = set_hook
34
35     @property
36     def name(self):
37         return self._name
38
39     @property
40     def default(self):
41         return self._default
42
43     @property
44     def type(self):
45         return self._type
46
47     @property
48     def help(self):
49         return self._help
50
51     @property
52     def flags(self):
53         return self._flags
54
55     @property
56     def allowed(self):
57         return self._allowed
58
59     def has_flag(self, flag):
60         return (self._flags & flag) == flag
61
62     def get_value(self):
63         return self._value
64
65     def set_value(self, value):
66         valid = True
67
68         if self.type == Types.Enum:
69             valid = value in self._allowed
70         
71         valid = valid and self.is_valid_value(value)
72
73         if valid: 
74             if self.set_hook:
75                 # Hook receives old value, new value
76                 value = self.set_hook(self._value, value)
77
78             self._value = value
79         else:
80             raise ValueError("Invalid value %s for attribute %s" %
81                     (str(value), self.name))
82
83     value = property(get_value, set_value)
84
85     def is_valid_value(self, value):
86         """ Attribute subclasses will override this method to add 
87         adequate validation"""
88         return True
89