如果你想使用语法
def function(a: int):
pass
@SimeonVisser提到的,你有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 <module>
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 <class 'int'> and not <class 'str'>
虽然我还没有实现一种方法来检查你返回的类型,如果你也想检查它,这个解决方案也不适合你。