Skip to content

Instantly share code, notes, and snippets.

@cbguder
Created March 18, 2022 04:57
Show Gist options
  • Save cbguder/51399c0ce81dbfb0e2c90ab34f05db66 to your computer and use it in GitHub Desktop.
Save cbguder/51399c0ce81dbfb0e2c90ab34f05db66 to your computer and use it in GitHub Desktop.
from typing import Protocol, TypeVar, Generic, Any
T = TypeVar('T')
class Proxy(Generic[T]):
def __init__(self, proxied: T) -> None:
self._proxied = proxied
def __getattr__(self, item: str) -> Any:
return getattr(self._proxied, item)
class Client(Protocol):
def do_something(self) -> None:
...
def do_another_thing(self) -> None:
...
class InnerClient:
def do_something(self) -> None:
print("InnerClient.do_something")
def do_another_thing(self) -> None:
print("InnerClient.do_another_thing")
class OuterClient1(Proxy[Client]):
def do_something(self) -> None:
print("OuterClient1.do_something")
self._proxied.do_something()
class OuterClient2(Proxy[Client]):
def __init__(self, client: Client, num: int):
super().__init__(client)
self._num = num
def do_another_thing(self) -> None:
print(f"OuterClient2.do_another_thing {self._num}")
self._proxied.do_another_thing()
def main() -> None:
inner_client: Client = InnerClient()
outer_client_1: Client = OuterClient1(inner_client)
outer_client_2: Client = OuterClient2(outer_client_1, 42)
outer_client_2.do_something()
outer_client_2.do_another_thing()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment