1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
def require(*types):
"""Return a decorator function that requires specified types.
types -- tuple each element of which is a type or class or a tuple of
several types or classes.
Example to require a string then a numeric argument
@require(str, (int, long, float))
will do the trick"""
def deco(func):
"""Decorator function to be returned from require(). Returns a function
wrapper that validates argument types."""
def wrapper (*args):
"""Function wrapper that checks argument types."""
assert len(args) == len(types), 'Wrong number of arguments.'
for a, t in zip(args, types):
if type(t) == type(()):
# any of these types are ok
msg = """%s is not a valid type. Valid types:\n%s"""
assert sum(isinstance(a, tp) for tp in t) > 0, \
msg % (a, '\n'.join(str(x) for x in t))
assert isinstance(a, t), '%s is not a %s type' % (a, t)
return func(*args)
return wrapper
return deco |
Partager