[Python] What is the type for functions taking int as a first parameter and then optional...

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    Let's consider that I have functions with these ones :

    def f1(a: int, **other_args):
    ...

    def f2(a: int, b: str, c: dict):
    ...

    def f3(a: int, b: tuple[str], **other_args):
    ...


    All these functions are beginning with a int as argument, and then taking other arguments, that can or not be optional.

    Now I want to store them in a list :

    l: list[?] = [f1, f2, f3]


    I know that I can do something like

    import typing

    param_spec = typing.ParamSpec('param_spec')
    l: list[typing.Callable[typing.Concatenate[int, param_spec], typing.Any]] = [f1, f2, f3]


    but it would mean that all functions can take the same arguments, which is not the case between f2 and f3 for example.

    I also tried

    l: list[typing.Callable[typing.Concatenate[int, ...], typing.Any]] = [f1, f2, f3]


    but I got TypeError: The last parameter to Concatenate should be a ParamSpec variable.

    I also have tried

    l: list[typing.Callable[[int, ...], typing.Any]] = [f1, f2, f3]


    but, in this case, ... is considered as a *args, and not **kwargs.

    Does it exists a type that describes this kind of functions? How can I do it?

    Thanks for your help!

    Continue reading...

Compartilhe esta Página