Created
April 8, 2021 20:13
-
-
Save habibutsu/ab5cf9bca2ba15ca20544cd1ddb87b90 to your computer and use it in GitHub Desktop.
type hints
This file contains hidden or 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 typing import Callable, TypeVar, cast, Generic | |
class SomeRequest: | |
pass | |
class SomeResponse: | |
pass | |
T = TypeVar('T') | |
class Result(Generic[T]): | |
def __inti__(self): | |
self._result = None | |
def set(self, result): | |
self._result = result | |
def get(self) -> T: | |
return self._result | |
Req = TypeVar('Req') | |
Resp = TypeVar('Resp') | |
def lazy_result(fn: Callable[..., Resp]) -> Callable[..., Result[Resp]]: | |
def wrapper(self, request) -> Result[Resp]: | |
r = Result() | |
resp = fn(self, request) | |
r.set(resp) | |
return r | |
return wrapper | |
class SomeService: | |
@lazy_result | |
def foo(self, request: SomeRequest) -> SomeResponse: | |
return SomeResponse() | |
service = SomeService() | |
req = service.foo(SomeRequest()) | |
response = req.get() # type inference does not work in PyCharm | |
assert type(response) is SomeResponse, response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment