在 mypy 中,我为接受一个类型和该类型的东西作为参数的函数编写什么类型签名?
In mypy, what type signature do I write for a function that accepts a type and something of that type as an argument?
我知道了:
def gradient_descent(
...
model_class: Type[Model],
J: Callable[[np.ndarray, model_class], float],
...
):
我希望此函数接受一个 class,以及一个接受该 class 实例的函数。但是,这给了我错误 Name "model_class" is not defined.
。我假设这是因为 mypy 在类型检查时无法访问 model_class
。
有什么办法可以实现吗?
我认为您要查找的是 generic type,例如:
T = TypeVar('T', bound=Model)
def gradient_descent(
...
model_class: Type[T],
J: Callable[[np.ndarray, T], float],
...
):
我知道了:
def gradient_descent(
...
model_class: Type[Model],
J: Callable[[np.ndarray, model_class], float],
...
):
我希望此函数接受一个 class,以及一个接受该 class 实例的函数。但是,这给了我错误 Name "model_class" is not defined.
。我假设这是因为 mypy 在类型检查时无法访问 model_class
。
有什么办法可以实现吗?
我认为您要查找的是 generic type,例如:
T = TypeVar('T', bound=Model)
def gradient_descent(
...
model_class: Type[T],
J: Callable[[np.ndarray, T], float],
...
):