如何在 Python 中键入自定义可调用类型

问题描述 投票:0回答:1

我有一个名为 Foo 的课程:

class Foo:
    def __init__(self, callable):
        self.my_attr = "hi"
        self.callable = callable

    def __call__(self, *args, **kwargs):
         # call the wrapped in function
         return self.callable(*args, **kwargs)

我想输入它的实例(

__call__
方法和
my_attr
属性)。

谢谢你的帮助,

python generics mypy typing callable
1个回答
0
投票

我用泛型来解决问题:

from typing import ParamSpec, TypeVar, Generic, Callable
P = ParamSpec("P")
RV = TypeVar("RV")

class Foo(Generic[P, RV]):
    def __init__(self, callable: Callable[P, RV]):
        self.my_attr = "hi"
        self.callable = callable

    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> RV:
         # call the wrapped in function
         return self.callable(*args, **kwargs)

def my_decorator(func: Callable[P, RV]) ->  Foo[P, RV]:
    return Foo(func)

现在这些打字是有效的:

@my_decorator
def func(a: int, b: str) -> str:
    raise NotImplementedError

s: str = func(1, "2") # valid typing for object cal
ss: str = func.my_attr # valid typing for attribute access
© www.soinside.com 2019 - 2024. All rights reserved.