14
14
import pychart_types
17
def _check_attr_types(obj, keys):
18
for attr in obj.__dict__.keys():
19
if not keys.has_key(attr):
20
raise Exception, "%s: unknown attribute '%s'" % (obj, attr)
22
typeval, default_value, docstring = keys[attr][0:3]
23
val = getattr(obj, attr)
24
if val == None or typeval == pychart_types.AnyType:
26
elif isinstance(typeval, types.FunctionType):
27
# user-defined check procedure
28
error = apply(typeval, (val,))
30
raise Exception, "%s: %s for attribute '%s', but got '%s'" % (obj, error, attr, val)
33
if isinstance(val, typeval):
36
raise Exception, "%s: Expecting type %s, but got %s (attr=%s, %s)" % (obj, typeval, val, attr, keys[attr])
39
raise Exception, "%s: attribute '%s' expects type %s but found %s" % (obj, attr, typeval, val)
41
17
def set_defaults(cls, **dict):
42
18
validAttrs = getattr(cls, "keys")
43
19
for attr, val in dict.items():
61
37
# as the default value
62
38
defaultVal = apply(defaultVal, ())
63
39
setattr(self, attr, defaultVal)
65
41
for key, val in args.items():
66
setattr(self, key, val)
67
_check_attr_types(self, keys)
42
self.__setattr__(key, val)
44
def __check_type(self, item, value):
45
if item.startswith("_"):
48
if not self.keys.has_key(item):
49
raise Exception, "%s: unknown attribute '%s'" % (self, item)
51
typeval, default_value, docstring = self.keys[item][0:3]
52
if value == None or typeval == pychart_types.AnyType:
55
# In 2.3, bool is a full-fledged type, whereas
56
# in 2.2, it's just a function that returns an integer.
57
# To mask this difference, we handle the bool type specially.
58
if value not in (True, False):
59
raise TypeError, "%s: Expecting bool, but got %s" % (self, value)
61
if not isinstance(value, str) and not isinstance(value, unicode):
62
raise TypeError, "%s: Expecting a string, but got %s" % (self, value)
63
elif isinstance(typeval, types.FunctionType):
64
# user-defined check procedure
65
error = apply(typeval, (value,))
67
raise TypeError, "%s: %s for attribute '%s', but got '%s'" % (self, error, item, value)
68
elif isinstance(value, typeval):
71
raise TypeError, "%s: Expecting type %s, but got %s (attr=%s, %s)" % (self, typeval, value, item, self.keys[item])
69
72
def __init__(self, **args):
73
_check_attr_types(self, self.keys)
75
def __setattr__(self, item, value):
76
self.__check_type(item, value)
77
self.__dict__[item] = value
79
def check_integrity(self):
80
for attr, value in self.__dict__.items():
81
self.__check_type(attr, value)