Python中使用*args定义一个Callable,同时强制执行第一个参数。

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

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)

huangapple
  • 本文由 发表于 2023年6月27日 20:52:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565063.html
匿名

发表评论

匿名网友

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

确定