Skip to content

Instantly share code, notes, and snippets.

@mrmamongo
Created January 14, 2024 00:13
Show Gist options
  • Save mrmamongo/c1e6feb80dc69af7779381e96c35e617 to your computer and use it in GitHub Desktop.
Save mrmamongo/c1e6feb80dc69af7779381e96c35e617 to your computer and use it in GitHub Desktop.
DI Container with FastDepends built by https://github.com/Lancetnik
from typing import TypeVar, ParamSpec, Callable
from fast_depends import inject
from fast_depends.dependencies.provider import Provider
T = TypeVar("T")
P = ParamSpec("P")
class Container(Provider):
def execute(
self,
func: Callable[P, T],
*args: P.args,
**kwargs: P.kwargs,
) -> T:
return inject(dependency_overrides_provider=self)(func)(*args, **kwargs)
from typing import Protocol, runtime_checkable, Annotated, Any
from fast_depends import Depends
from container import Container
@runtime_checkable
class SomeClass(Protocol):
def __init__(self):
...
def request(self) -> Any:
...
class RealClass:
def __init__(self) -> None:
self.url = "outer-url"
def request(self) -> Any:
return {"status": 200}
def func(client: Annotated[SomeClass, Depends(SomeClass)]) -> Any:
return client.request()
container = Container()
with container.scope(SomeClass, RealClass):
assert container.execute(func) == {"status": 200}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment