Created
November 11, 2024 10:02
-
-
Save ktnyt/ccda03bfbf3306e64e4919539ff5e3f5 to your computer and use it in GitHub Desktop.
An override-able Module Set for the Python "Injector"
This file contains 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 __future__ import annotations | |
import contextlib | |
from typing import Callable, Generator, Type | |
from injector import Binder, Module | |
__all__ = ['ModuleSet'] | |
InstallableModuleType = Callable[[Binder], None] | Module | Type[Module] | |
class ModuleSet(Module): | |
modules: list[InstallableModuleType] | |
def __init__(self, *modules: InstallableModuleType) -> None: | |
self.modules = list(modules) | |
def add(self, *modules: InstallableModuleType) -> ModuleSet: | |
self.modules.append(ModuleSet(*modules)) | |
return self | |
@contextlib.contextmanager | |
def use(self, *modules: InstallableModuleType) -> Generator[ModuleSet, None, None]: | |
try: | |
self.add(*modules) | |
yield self | |
finally: | |
self.modules.pop() | |
def configure(self, binder: Binder) -> None: | |
for module in self.modules: | |
binder.install(module) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment