Skip to content

Instantly share code, notes, and snippets.

@habibutsu
Created April 8, 2021 20:13
Show Gist options
  • Save habibutsu/ab5cf9bca2ba15ca20544cd1ddb87b90 to your computer and use it in GitHub Desktop.
Save habibutsu/ab5cf9bca2ba15ca20544cd1ddb87b90 to your computer and use it in GitHub Desktop.
type hints
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