英文:
Python typing a Callable with *args while enforcing the first argument
问题
在以下代码中(在PyCharm上工作),我在可调用函数内部self
后面的参数中得到了一个意外的参数markup
。
from __future__ import annotations
from typing import *
class G:
def __init__(self, callback: Callable[[G, ...], None]):
self.callback_ = callback
def f(self):
self.callback_(self, 1, 2, 3)
我已经尝试了很多方法,但仍然没有成功。在上面的代码中,我该如何避免输入错误?我的目标是回调函数的第一个参数应该是类型为G,其余的参数应该是从其他地方输入的(类似于*args)。
英文:
In the following code (working on PyCharm), I get an unexpected argument markup at the arguments following self
inside the callable function.
from __future__ import annotations
from typing import *
class G:
def __init__(self,callback: Callable[[G, ...], None]):
self.callback_ = callback
def f(self):
self.callback_(self,1,2,3)
I have tried many things, but still to no avail. What can I do to avoid typing errors in code above?
my objective is that the callback functions first argument will be of type G and the rest of the arguments will be anything inputted elsewhere (something like *args)
答案1
得分: 2
The ellipsis (...
) cannot be used in the context of typing.Callable[[G, ...], None]
to express that one cares only about the first argument.
Use typing.Protocol
instead:
from __future__ import annotations
from typing import Any, Protocol
class CallbackOnG(Protocol):
def __call__(self, g: G, *args: Any, **kwds: Any) -> None:
...
class G:
def __init__(self, callback: CallbackOnG):
self.callback_ = callback
def f(self):
self.callback_(self, 1, 2, 3)
英文:
The ellipsis (...
) cannot be used in the context of typing.Callable[[G, ...], None]
to express that one cares only about the first argument.
Use typing.Protocol
instead:
from __future__ import annotations
from typing import Any, Protocol
class CallbackOnG(Protocol):
def __call__(self, g: G, *args: Any, **kwds: Any) -> None:
...
class G:
def __init__(self, callback: CallbackOnG):
self.callback_ = callback
def f(self):
self.callback_(self, 1, 2, 3)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论