a20c5b03ca082f104215f7878b5cf5dbccc36eb1
[myslice.git] / manifold / manifoldresult.py
1 def enum(*sequential, **named):
2     enums = dict(zip(sequential, range(len(sequential))), **named)
3     return type('Enum', (), enums)
4
5 ManifoldCode = enum (
6     SUCCESS=0,
7     SESSION_EXPIRED=1,
8     NOT_IMPLEMENTED=2,
9     UNKNOWN_ERROR=3,
10 )
11
12 # being a dict this can be used with json.dumps
13 class ManifoldResult (dict):
14     def __init__ (self, code=ManifoldCode.SUCCESS, value=None, output=""):
15         self['code']=code
16         self['value']=value
17         self['output']=output
18         self['description'] = '' # Jordan: needed by javascript code
19
20     def from_json (self, json_string):
21         d=json.dumps(json_string)
22         for k in ['code','value','output']:
23             self[k]=d[k]
24
25     # raw accessors
26     def code (self): return self['code']
27     def output (self): return self['output']
28
29     # this returns None if there's a problem, the value otherwise
30     def ok_value (self):
31         if self['code']==ManifoldCode.SUCCESS:
32             return self['value']
33
34     # both data in a single string
35     def error (self):
36         return "code=%s -- %s"%(self['code'],self['output'])
37     
38
39     def __repr__ (self):
40         result="[[MFresult code=%s"%self['code']
41         if self['code']==0:
42             value=self['value']
43             if isinstance(value,list): result += " [value=list with %d elts]"%len(value)
44             elif isinstance(value,dict): result += " [value=dict with keys %s]"%value.keys()
45             else: result += " [value=%s: %s]"%(type(value).__name__,value)
46         else:
47             result += " [output=%s]"%self['output']
48         result += "]]"
49         return result
50
51 # probably simpler to use a single class and transport the whole result there
52 # instead of a clumsy set of derived classes 
53 class ManifoldException (Exception):
54     def __init__ (self, manifold_result):
55         self.manifold_result=manifold_result
56     def __repr__ (self):
57         return "Manifold Exception %s"%(self.manifold_result.error())