Retrofitting Dependency Injection System With Pyright: Force Non-Data Protocol Check #11357
-
|
I have a protocol setup sort of working as below for dependency injection. The scanning and registration is done via A manual check, So in more plain-speak I'm looking for something that does this: Here is a rough example of what I have now: Define Service# ./services/bundle.py
from ..protocols import BundleProtocol, JsonProtocol
@register_service(BundleProtocol)
class BundleService:
json_api: JsonProtocol
def get_bundle_config_json(self) -> dict[str, dict[str, str]]:
return self.json_api.to_json({})
def check_service(api, proto):
if not issubclass(api, proto):
raise AssertionError(f"The service {api} should implement {proto}.")
check_service(BundleHelperService, BundleHelperProtocol)Define Protocols# ./protocols.py
from typing import Protocol, runtime_checkable, Any
@runtime_checkable
class BundleProtocol:
def get_bundle_config_json(self) -> dict[str, dict[str, str]]:
...
@runtime_checkable
class JsonProtocol:
def to_json(self, obj: dict[str, Any]) -> str:
...Use service#./handlers.py
@handle_get()
def handle_request(request: RequestProtocol) -> dict[str, str]:
# statically this will essentially be an implicit or explicit "cast"
bundle_api = request.find_service(BundleProtocol)
return {"bundle_config_json": bundle_api.get_bundle_config_json()} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Why can't you just subclass the protocol |
Beta Was this translation helpful? Give feedback.
Why can't you just subclass the protocol
class BundleService(BundleProtocol):