from inspect import signature
from functools import wraps
def typeassert(*ty_args, **ty_kwargs):
def decorate(func):
# If in optimized mode, disable type checking
if not __debug__:
return func
# Map function argument names to supplied types
sig = signature(func)
bound_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments
@wraps(func)
def wrapper(*args, **kwargs):
bound_values = sig.bind(*args, **kwargs)
# Enforce type assertions across supplied arguments
for name, value in bound_values.arguments.items():
if name in bound_types:
if not isinstance(value, bound_types[name]):
raise TypeError(
'Argument {} must be {}'.format(name, bound_types[name])
)
return func(*args, **kwargs)
return wrapper
return decorate>>> @typeassert(int, int)
... def add(x, y):
... return x + y
...
>>>
>>> add(2, 3)
5
>>> add(2, 'hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "contract.py", line 33, in wrapper
TypeError: Argument y must be <class 'int'>
클래스는 디스크립터 + 그 디스크립터를 수정하는 데코레이터 조합으로 자료형 조절하고
함수는 이런 거 이용하면 괜찮네
이런식으로 타입을 조일거면 왜 파이썬을 쓰냐하는 문제가 생긱지만 쓰다보면 결국 조이게 되던 ㅠㅠ
홀 - dc App
파이썬 쿡북 예제임 ㅋㅋㅋㅋ
솔직히 결국 저거 타입 에러를 런타임 에러로 처리한다는 거잖아;;;; 애미