Advertisement
Pandaaaa906

python_check_input_type

May 22nd, 2019
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. from inspect import signature
  2. from functools import wraps
  3.  
  4. def check_input_type(func):
  5.     sig = signature(func)
  6.     parameters = sig.parameters
  7.     @wraps(func)
  8.     def wrapper(*args, **kwargs):
  9.         for position, (arg, (name, arg_sig)) in enumerate(zip(args, parameters.items())):
  10.             if not isinstance(arg, arg_sig.annotation):
  11.                 raise ValueError(f"Type of argument at position {position} is invalid, Type {arg_sig.annotation} expected.")
  12.         for name in kwargs:
  13.             if not name in parameters:
  14.                 raise ValueError(f"Unexpected keyword argument")
  15.             arg_sig = parameters[name]
  16.             if not isinstance(kwargs[name], arg_sig.annotation):
  17.                 raise ValueError(f"The value of {name!r} is invalid, Type {arg_sig.annotation} expected.")
  18.         ret = func(*args, **kwargs)
  19.         return ret
  20.     return wrapper
  21.  
  22. @check_input_type
  23. def func(text: str, n: int):
  24.     print(text, n)
  25.  
  26. func('adsf',12)
  27. func(123,'asdf')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement