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

huangapple go评论66阅读模式
英文:

how to type a custom callable type in Python

问题

我有一个名为Foo的类:

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

    def __call__(self, *args, **kwargs):
         # 调用包装的函数
         return self.callable(*args, **kwargs)

我想为它的实例(__call__方法和my_attr属性)进行类型注释。

谢谢你的帮助。

英文:

I have a class called 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)

I would like to type its instances (the __call__ method and the my_attr attribute).

Thank you for your help,

答案1

得分: 1

我使用泛型解决了这个问题:

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:
         # 调用包装的函数
         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") # 对于对象调用的有效类型标注
ss: str = func.my_attr # 对于属性访问的有效类型标注
英文:

I used Generics to solve the problem:

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)

Now these typing is valid:

@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

huangapple
  • 本文由 发表于 2023年2月24日 02:57:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定