mlk
By: a guest | Jul 23rd, 2008 | Syntax:
Python | Size: 0.89 KB | Hits: 60 | Expires: Never
class accepts_wrap(object):
def __init__(self, func, argtypes):
self.func = func
self.__doc__ = func.__doc__
self.argtypes = argtypes
def __call__(self, *args):
for i, (arg, cls) in enumerate(zip(args, self.argtypes)):
if not isinstance(arg, cls):
raise TypeError("Expected %r for argument #%d got %r" % (cls, i+1, type(arg)))
return self.func(*args)
def accepts(*argtypes):
return lambda func: accepts_wrap(func, argtypes)
@accepts(float, float)
def float_div(a, b):
"""
A function that divides floats.
Any other types of arguments will throw an exception
>>> float_div(1.0, 2.0)
0.5
>>> float_div(1, 1.0)
Traceback (most recent call last):
...
TypeError: Expected <type 'float'> for argument #1 got <type 'int'>
"""
return a / b