def __call__(self, function):
if not self.shouldCheck:
return function
type_hints = typing.get_type_hints(function)
def precheck(*args, **kwargs):
all_args = kwargs.copy()
all_args.update(dict(zip(function.__code__.co_varnames, args)))
runtime_args = ((n, type(v)) for n, v in all_args.items())
for arg_name, arg_type in runtime_args:
if arg_name not in type_hints:
continue
if not self.is_subtype(arg_type, type_hints[arg_name]):
raise TypeError('In {} type of {} is {} and not {}'.
format(function.__qualname__,
arg_name,
arg_type,
type_hints[arg_name]))
def postcheck(result):
if 'return' in type_hints:
if not self.is_subtype(type(result), type_hints['return']):
raise TypeError('Type of result is {} and not {}'.
format(type(result), type_hints['return']))
return result
if inspect.iscoroutinefunction(function):
async def type_checker(*args, **kwargs):
precheck(*args, **kwargs)
result = await function(*args, **kwargs)
return postcheck(result)
else:
def type_checker(*args, **kwargs):
precheck(*args, **kwargs)
result = function(*args, **kwargs)
return postcheck(result)
return type_checker
评论列表
文章目录