记录函数参数的最简单方法是使用typing.Callable
. 通过这样做,静态类型检查器将验证传递函数的签名(参数和返回类型)是否与类型提示兼容。
from typing import Callable
class ExampleClassTwo:
"""An example class to demonstrate my question.
Args:
func (Callable[[str], bool]): Description of the parameter.
"""
def __init__(self, func: Callable[[str], bool]):
self.func = func
然而,这有一个潜在的问题。如果您查看 Python 数据模型,在3.2 标准类型层次结构下标题为“可调用类型”的小节中。您会注意到有几种可能的类型是可调用的,任何具有指定签名的可调用都不会导致来自静态类型检查器的警告。例如,实现该__call__()
方法的类实例不会引起警告:
def str_function(param: str) -> bool:
pass
class OneInstance:
def __init__(self, param):
pass
def __call__(self, param: str) -> bool:
pass
one_instance = OneInstance("test instance")
# neither of the below raise a static type check warning
one = ExampleClassTwo(str_function)
two = ExampleClassTwo(one_instance)
您可以键入提示param
签名,如上所示,同时验证param
类型为FunctionType
in,就像在运行时验证其他参数一样,如果参数不是函数__init__
,则引发异常。TypeError
from typing import Callable
from types import FunctionType
class ExampleClassTwo:
"""An example class to demonstrate my question
Args:
func (Callable[[str], bool]): Description of the parameter
Raises:
TypeError: Argument `param` is not of type ``FunctionType``.
"""
def __init__(self, func: Callable[[str], bool]):
if type(func) in (FunctionType,):
self.func = func
else:
raise TypeError("param must be initialized as being of ``FunctionType``.")
可以将这两个需求结合起来,Callable[[str], bool]
并FunctionType
作为一个使用结构子类型的交集,我还没有尝试过这种方法。
最后包含一些示例,这些示例会导致静态类型检查器发出警告:
def int_function(param: int) -> bool:
pass
class ExampleClass:
"""An example class to demonstrate my question
Args:
func (FunctionType): Description of the parameter
"""
def __init__(self, func: FunctionType):
self.func = func
three = ExampleClass(str_function("test string")) # Expected type 'FunctionType', got 'bool' instead
four = ExampleClass(str_function) # Expected type 'FunctionType', got '(param: str) -> bool' instead
five = ExampleClass(type(str_function)) # No warning five.func is {type} <class 'function'>
six = ExampleClassTwo(int_function(2)) # Expected type '(str) -> bool', got 'bool' instead
seven = ExampleClassTwo(str_function("test string")) # Expected type '(str) -> bool', got 'bool' instead
eight = ExampleClassTwo(int_function) # Expected type '(str) -> bool', got '(param: int) -> bool' instead
nine = ExampleClassTwo(str_function) # No warning
![在此处输入图像描述](https://i.stack.imgur.com/Rax8r.jpg)