Python 本身不提供此类功能,您可以在此处阅读更多信息:
我为此写了一个装饰器。这是我的装饰器的代码:
from typing import get_type_hints
def strict_types(function):
def type_checker(*args, **kwargs):
hints = get_type_hints(function)
all_args = kwargs.copy()
all_args.update(dict(zip(function.__code__.co_varnames, args)))
for argument, argument_type in ((i, type(j)) for i, j in all_args.items()):
if argument in hints:
if not issubclass(argument_type, hints[argument]):
raise TypeError('Type of {} is {} and not {}'.format(argument, argument_type, hints[argument]))
result = function(*args, **kwargs)
if 'return' in hints:
if type(result) != hints['return']:
raise TypeError('Type of result is {} and not {}'.format(type(result), hints['return']))
return result
return type_checker
你可以这样使用它:
@strict_types
def repeat_str(mystr: str, times: int):
return mystr * times
虽然限制你的函数只接受一种类型并不是很pythonic。尽管您可以使用abc(抽象基类)number
(或自定义 abc)作为类型提示,并限制您的函数不仅接受一种类型,而且接受您想要的任何类型组合。
如果有人想使用它,请为其添加一个 github 存储库。