hir*_*ist 8 python python-internals python-3.5
python 3.5是否提供了允许测试给定参数是否适合函数声明中给出的类型提示的函数?
如果我有这样的功能:
def f(name: List[str]):
pass
Run Code Online (Sandbox Code Playgroud)
有没有python方法可以检查是否
name = ['a', 'b']
name = [0, 1]
name = []
name = None
...
Run Code Online (Sandbox Code Playgroud)
适合类型提示?
我知道'在运行时没有进行类型检查'但是我仍然可以在python中手动检查这些参数的有效性吗?
或者如果python本身不提供该功能:我需要使用什么工具?
Ily*_*rov 10
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
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
@strict_types
def repeat_str(mystr: str, times: int):
return mystr * times
Run Code Online (Sandbox Code Playgroud)
虽然限制你的函数只接受一种类型并不是非常pythonic.虽然您可以使用像(或自定义abc )这样的abc(抽象基类)number作为类型提示,并限制您的函数不仅接受一种类型,而且接受您想要的任何类型组合.
如果有人想使用它,为它添加了一个github repo.