python: enforcing type check on function using decorator
def typeassert(*ty_args, **ty_kwargs): """ 利用装饰器对函数参数强制性类型检查 enforcing type check on function using decorator :param ty_args: :param ty_kwargs: :return: """ 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, z=int) def spam(x, y, z=42): """ :param y: :param z: :return: """ print(x, y, z) #https://github.com/yidao620c/python3-cookbook/blob/master/source/c09/p07_enforcing_type_check_on_function_using_decorator.rst
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)