Created
May 24, 2024 19:43
-
-
Save mypy-play/8ce7d57cb7f9a080d7d5f29ddffdcaa6 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
from typing import TypeVar, Concatenate, ParamSpec, Any | |
from collections.abc import Callable | |
F = TypeVar("F", bound = Callable[..., Any]) | |
P = ParamSpec("P") | |
R = TypeVar("R") | |
S = TypeVar("S") | |
def copy_args(f: Callable[P, Any], /) -> Callable[[Callable[Concatenate[S, P], R]], Callable[Concatenate[S, P], R]]: | |
""" | |
Capture the parameters type of `f`, then pretend that the decorated function's | |
parameters are of this type. | |
`f`'s return type is ignored, and the decorated function's return type is preserved. | |
""" | |
return lambda _: _ | |
def method(a: int, b: int) -> float: | |
return a * b + 1.0 | |
class Bar: | |
def __init__(self, value: float) -> None: | |
self.value = value | |
class Foo: | |
@copy_args(method) | |
def method(self, *args: Any, **kwargs: Any) -> Bar: | |
return Bar(method(*args, **kwargs)) | |
x = Foo().method(1, 2) | |
reveal_type(Foo().method) | |
reveal_type(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment