如果要使用语法def function(a: int):
pass
@simeonviser提到,你有python3.5,你可以使用我写的装饰器from typing import get_type_hints
def strict_types(f):
def type_checker(*args, **kwargs):
hints = get_type_hints(f)
all_args = kwargs.copy()
all_args.update(dict(zip(f.__code__.co_varnames, args)))
for key in all_args:
if key in hints:
if type(all_args[key]) != hints[key]:
raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))
return f(*args, **kwargs)
return type_checker
在定义这样的函数时@strict_types
def concatenate_with_spam(text: str) -> str:
return text + 'spam'
如果传递给函数的参数类型错误,则会引发异常。Traceback (most recent call last):
File "strict_types.py", line 23, in
concatenate_with_spam(1)
File "strict_types.py", line 13, in type_checker
raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))
Exception: Type of text is and not
虽然我还没有实现一种方法来检查您返回的内容的类型,而且如果您也想检查,这个解决方案也不适合您。