slice page working. added temporarily core and util classes from manifold core
[myslice.git] / manifold / util / type.py
1 # http://wiki.python.org/moin/PythonDecoratorLibrary#Type_Enforcement_.28accepts.2Freturns.29
2 '''
3 One of three degrees of enforcement may be specified by passing
4 the 'debug' keyword argument to the decorator:
5     0 -- NONE:   No type-checking. Decorators disabled.
6     1 -- MEDIUM: Print warning message to stderr. (Default)
7     2 -- STRONG: Raise TypeError with message.
8 If 'debug' is not passed to the decorator, the default level is used.
9
10 Example usage:
11     >>> NONE, MEDIUM, STRONG = 0, 1, 2
12     >>>
13     >>> @accepts(int, int, int)
14     ... @returns(float)
15     ... def average(x, y, z):
16     ...     return (x + y + z) / 2
17     ...
18     >>> average(5.5, 10, 15.0)
19     TypeWarning:  'average' method accepts (int, int, int), but was given
20     (float, int, float)
21     15.25
22     >>> average(5, 10, 15)
23     TypeWarning:  'average' method returns (float), but result is (int)
24     15
25
26 Needed to cast params as floats in function def (or simply divide by 2.0).
27
28     >>> TYPE_CHECK = STRONG
29     >>> @accepts(int, debug=TYPE_CHECK)
30     ... @returns(int, debug=TYPE_CHECK)
31     ... def fib(n):
32     ...     if n in (0, 1): return n
33     ...     return fib(n-1) + fib(n-2)
34     ...
35     >>> fib(5.3)
36     Traceback (most recent call last):
37       ...
38     TypeError: 'fib' method accepts (int), but was given (float)
39
40 '''
41 import sys
42 from itertools import izip
43
44 def accepts(*types, **kw):
45     '''Function decorator. Checks decorated function's arguments are
46     of the expected types.
47
48     Parameters:
49     types -- The expected types of the inputs to the decorated function.
50              Must specify type for each parameter.
51     kw    -- Optional specification of 'debug' level (this is the only valid
52              keyword argument, no other should be given).
53              debug = ( 0 | 1 | 2 )
54
55     '''
56     if not kw:
57         # default level: MEDIUM
58         debug = 2
59     else:
60         debug = kw['debug']
61     try:
62         def decorator(f):
63             def newf(*args):
64                 if debug is 0:
65                     return f(*args)
66                 assert len(args) == len(types)
67                 argtypes = tuple(map(type, args))
68                 if not compare_types(types, argtypes):
69                 # if argtypes != types:
70                     msg = info(f.__name__, types, argtypes, 0)
71                     if debug is 1:
72                         print >> sys.stderr, 'TypeWarning: ', msg
73                     elif debug is 2:
74                         raise TypeError, msg
75                 return f(*args)
76             newf.__name__ = f.__name__
77             return newf
78         return decorator
79     except KeyError, key:
80         raise KeyError, key + "is not a valid keyword argument"
81     except TypeError, msg:
82         raise TypeError, msg
83
84 def compare_types(expected, actual):
85     if isinstance(expected, tuple):
86         if isinstance(actual, tuple):
87             for x, y in izip(expected, actual):
88                 if not compare_types(x ,y):
89                     return False
90             return True
91         else:
92             return actual == type(None) or actual in expected
93     else:
94         return actual == type(None) or actual == expected or issubclass(actual, expected)
95
96 def returns(ret_type, **kw):
97     '''Function decorator. Checks decorated function's return value
98     is of the expected type.
99
100     Parameters:
101     ret_type -- The expected type of the decorated function's return value.
102                 Must specify type for each parameter.
103     kw       -- Optional specification of 'debug' level (this is the only valid
104                 keyword argument, no other should be given).
105                 debug=(0 | 1 | 2)
106     '''
107     try:
108         if not kw:
109             # default level: MEDIUM
110             debug = 1
111         else:
112             debug = kw['debug']
113         def decorator(f):
114             def newf(*args):
115                 result = f(*args)
116                 if debug is 0:
117                     return result
118                 res_type = type(result)
119                 if not compare_types(ret_type, res_type): 
120                 # if res_type != ret_type: # JORDAN: fix to allow for # StringTypes = (str, unicode)
121                 # XXX note that this check should be recursive
122                     msg = info(f.__name__, (ret_type,), (res_type,), 1)
123                     if debug is 1:
124                         print >> sys.stderr, 'TypeWarning: ', msg
125                     elif debug is 2:
126                         raise TypeError, msg
127                 return result
128             newf.__name__ = f.__name__
129             return newf
130         return decorator
131     except KeyError, key:
132         raise KeyError, key + "is not a valid keyword argument"
133     except TypeError, msg:
134         raise TypeError, msg
135
136 def info(fname, expected, actual, flag):
137     '''Convenience function returns nicely formatted error/warning msg.'''
138     format = lambda types: ', '.join([str(t).split("'")[1] for t in types])
139     msg = "'{}' method ".format( fname )\
140           + ("accepts", "returns")[flag] + " ({}), but ".format(expected)\
141           + ("was given", "result is")[flag] + " ({})".format(actual)
142     return msg
143