python 3.5 是否提供允许测试给定的函数是否 参数是否符合函数声明中给出的类型提示?
如果我有这个函数:
def f(name: List[str]):
pass
有没有python方法可以检查是否
name = ['a', 'b']
name = [0, 1]
name = []
name = None
...
符合类型提示?
我知道“运行时不会发生类型检查”,但我仍然可以检查 在 python 中手动验证这些参数的有效性?
或者如果 python 本身不提供该功能:我会使用什么工具 需要用吗?
最佳答案
Python 本身不提供此类函数,您可以阅读更多相关信息here :
我为此写了一个装饰器。这是我的装饰器的代码:
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 repo对于它,如果有人想使用它的话。
关于python 3.5 类型提示 : can i check if function arguments match type hints?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32844556/