Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to inherit argument types from a specific wrapped function #13617

Open
PeterJCLaw opened this issue Sep 7, 2022 · 1 comment
Open

How to inherit argument types from a specific wrapped function #13617

PeterJCLaw opened this issue Sep 7, 2022 · 1 comment
Labels

Comments

@PeterJCLaw
Copy link
Contributor

PeterJCLaw commented Sep 7, 2022

It would be great if there were a way to inherit the (argument) type signatures from one function to another. The use case here is something like:

def foo(
    something: str,
    *args: *requests.get.args,
    **kwargs: **requests.get.kwargs
):
    print(something)
    return requests.get(*args, **kwargs)

I've found #2003, though that was closed a while back. I'm not totally clear why that was closed (from the comments I can't work out what the solution was, nor if agreement was reached on an approach). Additionally a lot has changed since then with regards to argument typing -- notably ParamSpec, TypeVarTuple & Unpack now exist, though I'm not sure if any of them actually help here as the wrapped function is static rather than also being part of the call signature.

Ideally I'd like to be able to do this in cases where the original function is annotated, though without needing to change that function's annotations (e.g: because it's in a library), so using e.g: Unpack[TypedDict] would require me to repeat the definitions of the original function's signature, which is partly what I'm trying to avoid by using passthrough *args, **kwargs in the first place.

Aside: is "inherit" the right term for this? I wasn't sure what to search for.

@sobolevn
Copy link
Member

You can emulate this by:

from typing_extensions import ParamSpec, Concatenate
from typing import Callable, TypeVar

P = ParamSpec('P')
T = TypeVar('T')

def request_get(url: str, https: bool) -> int: ...

def wrapper(func: Callable[P, T]) -> Callable[Concatenate[str, P], T]:
    def inner(arg: str, *args: P.args, **kwargs: P.kwargs) -> T:
        ...
    return inner

wrapped_request_get = wrapper(request_get)
reveal_type(wrapped_request_get) 
# Revealed type is "def (builtins.str, url: builtins.str, https: builtins.bool) -> builtins.int"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants