Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python typing a Callable with *args while enforcing the first argument

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)

like image 577
Tomer Gigi Avatar asked Sep 13 '25 23:09

Tomer Gigi


1 Answers

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)
like image 147
Paweł Rubin Avatar answered Sep 15 '25 13:09

Paweł Rubin