Created
November 15, 2025 18:09
-
-
Save DomWeldon/3112d0d0650454c7c05604e42eb26524 to your computer and use it in GitHub Desktop.
Basic dependency injection system in python
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
| import inspect | |
| import typing | |
| class Ref: | |
| max_age: int = 5 | |
| def __init__(self, name: str): | |
| self.name = name | |
| class ParamRef(Ref): ... | |
| class OutputRef(Ref): ... | |
| # def calculate_area( | |
| # x: float, | |
| # y: float, | |
| # safety: float = 1, | |
| # ) -> float: | |
| # return x * y * safety | |
| def calculate_area( | |
| x: typing.Annotated[int, ParamRef(name="width")], | |
| y: typing.Annotated[int, ParamRef(name="height")], | |
| safety: typing.Annotated[int, ParamRef(name="safety")] = 1, | |
| ) -> typing.Annotated[float, OutputRef(name="area")]: | |
| return x * y * safety | |
| def call_with_params(params: dict, func: typing.Callable) -> dict: | |
| annos = inspect.get_annotations(func) | |
| call_with_params = {} | |
| for name, anno in annos.items(): | |
| # skip non-annotated params | |
| if name == "return" or not hasattr(anno, "__metadata__"): | |
| continue | |
| # find ParamRef in metadata | |
| for md in anno.__metadata__: | |
| if isinstance(md, ParamRef): | |
| call_with_params[name] = params[md.name] | |
| # max one ParamRef per param | |
| break | |
| result = func(**call_with_params) | |
| if "return" in annos and hasattr(annos["return"], "__metadata__"): | |
| ret_anno = annos["return"] | |
| output = { | |
| md.name: result | |
| for md in ret_anno.__metadata__ | |
| if isinstance(md, OutputRef) | |
| } | |
| return output | |
| return result | |
| def main(params: dict, func: typing.Callable) -> dict: | |
| output = call_with_params(params, func) | |
| return output | |
| if __name__ == "__main__": | |
| params = { | |
| "width": 20, | |
| "height": 3, | |
| "safety": 1.1, | |
| } | |
| output = call_with_params(params, calculate_area) | |
| print(output) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From talk at PyCon Ireland 2025
https://docs.google.com/presentation/d/1IOIyYZoVRqvmtEMMAhuIk9Pv6HugSwjrr9_8gzyKdyk/edit?usp=sharing