Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/dependenci injection contaianer #67

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion fastcrawler/utils/injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@
from typing import Any, Callable


class Container:
def __init__(self):
self.dependencies = {}

def __getitem__(self, dependency: Callable):
return self.dependencies[dependency]

def __setitem__(self, key: Callable, value: Callable):
self.dependencies[key] = value


container = Container()


class _Depends:
"""Dependency injection to run callable as a dependency"""

Expand All @@ -14,12 +28,18 @@ def __init__(
*args,
**kwargs,
):
self.dependency = dependency
self._dependency = dependency
container.dependencies[dependency] = dependency
self.use_cache = use_cache
self.result = ...
self.args = args
self.kwargs = kwargs

def get_dependency(self):
return container[self._dependency]

dependency = property(get_dependency)

async def async_eval(self):
"""Run async callable dependency and store it as cache entry"""
if self.result is ...:
Expand Down
18 changes: 18 additions & 0 deletions test/test_injections.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest

from fastcrawler.utils import Depends, _Depends, dependency_injector
from fastcrawler.utils.injection import container


def test_sync_dependency_injection():
Expand Down Expand Up @@ -194,3 +195,20 @@ def func(

assert result1 == "sync_dependency1"
assert result2 == "sync_dependency2"


def test_override_dependency():
def dependency_1():
return "sync_dependency1"

def dependency_2():
return "sync_dependency2"

@dependency_injector
def func(
dep1=Depends(dependency_1, use_cache=True),
):
return dep1

container[dependency_1] = dependency_2
assert func() == "sync_dependency2"