1def type_check(mode):
2 """Check the types of input arguments or the output of a function."""
3
4 def decorator(*expected):
5 """Accept the expected types."""
6
7 def wrapper(func):
8 """Perform the type checking."""
9
10 def validation(*args, **kwargs):
11 """Validate the types of input arguments and the return the result if possible."""
12
13 def expected_args_message():
14 """Generate a message listing the expected argument types."""
15 return "expected " + ", ".join([str(valid) for valid in expected]) + "!"
16
17 if mode == 'in':
18
19 all_args = list(args) + list(kwargs.values())
20
21 # Check if non-valid type is found
22 for arg in all_args:
23 if not isinstance(arg, expected):
24 print("Invalid input arguments, " + expected_args_message())
25 return func(*args, **kwargs)
26
27 res = func(*args, **kwargs)
28
29 # Check if return of function is non-valid type
30 if mode == 'out' and not isinstance(res, expected):
31 print("Invalid output value, " + expected_args_message())
32
33 return res
34 return validation
35 return wrapper
36 return decorator
....
----------------------------------------------------------------------
Ran 4 tests in 0.002s
OK