python 3.5 类型提示:我可以检查函数参数是否匹配类型提示吗?
python 3.5 type hints: can i check if function arguments match type hints?
python3.5 是否提供允许测试给定的函数是否
参数是否符合函数声明中给出的类型提示?
如果我有这个函数:
def f(name: List[str]):
pass
有没有python方法可以检查是否
name = ['a', 'b']
name = [0, 1]
name = []
name = None
...
是否符合类型提示?
我知道 'no type checking happens at runtime' 但我仍然可以查看
在 python?
中手写这些论点的有效性
或者如果 python 本身不提供该功能:我想要的工具是什么
需要用吗?
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 repo,如果有人想使用它的话。
这是一个老问题,但我已经编写了一个工具来根据类型提示进行 运行 时间类型检查:https://pypi.org/project/typeguard/
python3.5 是否提供允许测试给定的函数是否 参数是否符合函数声明中给出的类型提示?
如果我有这个函数:
def f(name: List[str]):
pass
有没有python方法可以检查是否
name = ['a', 'b']
name = [0, 1]
name = []
name = None
...
是否符合类型提示?
我知道 'no type checking happens at runtime' 但我仍然可以查看 在 python?
中手写这些论点的有效性或者如果 python 本身不提供该功能:我想要的工具是什么 需要用吗?
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 repo,如果有人想使用它的话。
这是一个老问题,但我已经编写了一个工具来根据类型提示进行 运行 时间类型检查:https://pypi.org/project/typeguard/