Add key word parameter to existing library function with correct type hint

Hello,

I want to write a function which adds a kwarg parameter to an existing library function.
The code part is easy:

def my_func(*args, new_kwarg: bool = True, **kwargs):
    result = library_func(*args, **kwargs)
    if new_kwarg:
        result.do_something()
    return result

However since the library function is very complex I’d like to keep the original type hints of the library function and add only the new key word parameter.

How do need to write the type hint?
Concatenate does only work when passing in a function and then I can’t specify that it’s a kwarg parameter I want to add.

I would have expected this to work, but it does not:

P = ParamSpec('P', bound=library_func)


def my_func(*args: P.args, new_kwarg: bool = True, **kwargs: P.kwargs):
    ...
error: The variance and bound arguments to ParamSpec do not have defined semantics yet  [misc]

Does it work using def my_func(*args, *, new_kwarg: bool = True, **kwargs): ?

No - since this adds no typing information at all.

Be aware that my issue is not with the implementation but with the type hint.
It’s not clear to me how I can “copy” the type hint from the library function to my own function.
Writing the code of the actual function is trivial as I showed above.

OK. Which type checker are you using, do neither pyright nor mypy accept this?

By using the word “yet”, the error message:

hints that maybe this will be implemented in future (perhaps after a definition of the semantics is agreed).

Short story, you cannot. Current typing tools allow extending existing functions only with positional parameters.

2 Likes

That’s a shame.

So I guess the only way to provide the proper type hint is to copy paste the three screens of overrides from the library?
Do you by chance know if there is something planned or do I just have to bite the bullet?