英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论