Last active
August 29, 2015 14:17
-
-
Save hannal/12597a1466307f4290a4 to your computer and use it in GitHub Desktop.
Python 3에서 함수의 위치 인자와 주석문 http://blog.hannal.com/2015/03/positioning_argument_and_annotations_for_python3_function/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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