f | import types | f | import types |
| | | |
| | | |
| def TypeCheck(argtypes, res): | | def TypeCheck(argtypes, res): |
| if isinstance(argtypes, types.GeneratorType): | | if isinstance(argtypes, types.GeneratorType): |
| argtypes = list(argtypes) | | argtypes = list(argtypes) |
| | | |
| def decorator(fun): | | def decorator(fun): |
| def newfun(*args, **kwargs): | | def newfun(*args, **kwargs): |
n | if len(args) + len(kwargs) != len(argtypes): | n | if len(kwargs) + len(args) != len(argtypes): |
| if not fun.__defaults__ or len( | | if not fun.__defaults__ or len( |
t | fun.__defaults__) + len(args) + len(kwargs) != len(argtypes): | t | fun.__defaults__) + len(kwargs) + len(args) != len(argtypes): |
| raise TypeError('Function ' + | | raise TypeError('Function ' + |
| fun.__code__.co_name + | | fun.__code__.co_name + |
| ' must have ' + | | ' must have ' + |
| str(len(argtypes)) + | | str(len(argtypes)) + |
| ' arguments') | | ' arguments') |
| | | |
| for index, arg in enumerate(args): | | for index, arg in enumerate(args): |
| if not isinstance(arg, argtypes[index]): | | if not isinstance(arg, argtypes[index]): |
| raise TypeError( | | raise TypeError( |
| 'Type of argument ' + str(index + 1) + ' is not ' + str(argtypes[index])) | | 'Type of argument ' + str(index + 1) + ' is not ' + str(argtypes[index])) |
| | | |
| named = 0 | | named = 0 |
| for kw, val in kwargs.items(): | | for kw, val in kwargs.items(): |
| if kw in fun.__code__.co_varnames and not isinstance( | | if kw in fun.__code__.co_varnames and not isinstance( |
| val, argtypes[fun.__code__.co_varnames.index(kw)]): | | val, argtypes[fun.__code__.co_varnames.index(kw)]): |
| named += 1 | | named += 1 |
| raise TypeError('Type of argument \'' + | | raise TypeError('Type of argument \'' + |
| kw + | | kw + |
| '\' is not ' + | | '\' is not ' + |
| str(argtypes[fun.__code__.co_varnames.index(kw)])) | | str(argtypes[fun.__code__.co_varnames.index(kw)])) |
| | | |
| result = fun(*args, **kwargs) | | result = fun(*args, **kwargs) |
| if not isinstance(result, res): | | if not isinstance(result, res): |
| raise TypeError('Type of result is not ' + str(res)) | | raise TypeError('Type of result is not ' + str(res)) |
| return result | | return result |
| | | |
| return newfun | | return newfun |
| | | |
| return decorator | | return decorator |
| | | |