Home > OS >  python using default values for callback protocol arguments
python using default values for callback protocol arguments

Time:05-03

I'm trying to set default values for a specific callback protocol (I'd like any callback of the Callback type to require passing in argument a but optionally pass in argument b). With the following code:

from typing import Protocol
from dataclasses import dataclass


class Callback(Protocol):
    def __call__(self, a: str, b: str = "") -> None:
        ...


def foo(a: str, b: str) -> None:
    print(a, b)


def bar(a: str, b: str = "") -> None:
    print(a, b)


@dataclass(frozen=True)
class Foobar:
    Foo: Callback
    Bar: Callback


config = Foobar(Foo=foo, Bar=bar)

mypy is complaining with:

(function) foo: (a: str, b: str) -> None
Argument of type "(a: str, b: str) -> None" cannot be assigned to parameter "Foo" of type "Callback" in function "__init__"
  Type "(a: str, b: str) -> None" cannot be assigned to type "(a: str, b: str = "") -> None"
    Parameter "b" is missing default argument PylancereportGeneralTypeIssues
Argument "Foo" to "Foobar" has incompatible type "Callable[[str, str], None]"; expected "Callback"mypy(error)

Is there a way to make this work? Searching up this particular error gives me nothing to work off of

CodePudding user response:

if I have a fb = Foobar(...), I should be able to do fb.Foo(""), but that wouldn't work if fb.Foo is foo, hence the type error

CodePudding user response:

You defined the type of "b" in __init__, so there is a contradiction in redefining it below.

According to your meaning, I think you could make "b" an optional parameter.

  • Related