Skip to content

Instantly share code, notes, and snippets.

@hannal
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hannal/12597a1466307f4290a4 to your computer and use it in GitHub Desktop.
Save hannal/12597a1466307f4290a4 to your computer and use it in GitHub Desktop.
# works on Python 3
def check_argument_type(func):
def wrapper(*args):
if (
not hasattr(func, '__annotations__') or
len(func.__annotations__) == 0
):
return func(*args)
try:
check_index = \
func.__annotations__['args'].index(Ellipsis)
except ValueError:
check_index = \
len(func.__annotations__['args']) - 1
for _i, _v in enumerate(args[:check_index]):
_arg_type = func.__annotations__['args'][_i]
if isinstance(_v, _arg_type):
continue
raise TypeError(
"The type of '{}' does not match '{}' type".format(
_v, _arg_type.__name__
)
)
return func(*args)
return wrapper
@check_argument_type
def hello_func(*args: (int, int, ...)):
print(*args)
hello_func(1, 2, '3', 'a')
# works on Python 3
def args2_func(arg1, *, arg2, arg3):
print(arg1, arg2, arg3)
args2_func('hello', 'world', '!')
args2_func('!', arg3='hello', arg2='world')
args2_func('world', arg3='!', arg2='hello')
args2_func('hello', '!', arg3='world')
def kwargs_func(*, arg1, arg2, arg3):
print(arg1, arg2, arg3)
kwargs_func(arg1='hello', arg2='world', arg3='!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment