modern-di 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of modern-di might be problematic. Click here for more details.

Files changed (48) hide show
  1. modern_di-0.2.0/.github/workflows/ci.yml → modern_di-0.3.0/.github/workflows/core-ci.yml +13 -12
  2. modern_di-0.3.0/.github/workflows/fastapi-ci.yml +54 -0
  3. modern_di-0.3.0/.github/workflows/publish.yml +41 -0
  4. modern_di-0.3.0/Justfile +23 -0
  5. {modern_di-0.2.0 → modern_di-0.3.0}/PKG-INFO +2 -3
  6. {modern_di-0.2.0 → modern_di-0.3.0}/README.md +1 -2
  7. {modern_di-0.2.0 → modern_di-0.3.0}/docs/dev/development-notes.md +2 -2
  8. modern_di-0.3.0/integrations/fastapi/README.md +6 -0
  9. modern_di-0.3.0/integrations/fastapi/modern_di_fastapi/__init__.py +9 -0
  10. modern_di-0.3.0/integrations/fastapi/modern_di_fastapi/depends.py +24 -0
  11. modern_di-0.3.0/integrations/fastapi/modern_di_fastapi/middleware.py +27 -0
  12. modern_di-0.3.0/integrations/fastapi/pyproject.toml +90 -0
  13. modern_di-0.3.0/integrations/fastapi/tests/test_fastapi_di.py +69 -0
  14. {modern_di-0.2.0 → modern_di-0.3.0}/modern_di/__init__.py +1 -1
  15. {modern_di-0.2.0 → modern_di-0.3.0}/modern_di/container.py +32 -24
  16. modern_di-0.3.0/modern_di/graph.py +39 -0
  17. modern_di-0.2.0/modern_di/resolver_state.py → modern_di-0.3.0/modern_di/provider_state.py +3 -3
  18. modern_di-0.3.0/modern_di/providers/__init__.py +15 -0
  19. {modern_di-0.2.0/modern_di/resolvers → modern_di-0.3.0/modern_di/providers}/base.py +12 -12
  20. modern_di-0.3.0/modern_di/providers/context_adapter.py +31 -0
  21. {modern_di-0.2.0/modern_di/resolvers → modern_di-0.3.0/modern_di/providers}/factory.py +5 -5
  22. {modern_di-0.2.0/modern_di/resolvers → modern_di-0.3.0/modern_di/providers}/resource.py +25 -25
  23. modern_di-0.3.0/modern_di/providers/singleton.py +56 -0
  24. {modern_di-0.2.0 → modern_di-0.3.0}/pyproject.toml +5 -0
  25. modern_di-0.3.0/tests/resolvers/__init__.py +0 -0
  26. modern_di-0.3.0/tests/resolvers/test_context_adapter.py +40 -0
  27. {modern_di-0.2.0 → modern_di-0.3.0}/tests/resolvers/test_factory.py +5 -5
  28. {modern_di-0.2.0 → modern_di-0.3.0}/tests/resolvers/test_resource.py +5 -5
  29. {modern_di-0.2.0 → modern_di-0.3.0}/tests/resolvers/test_singleton.py +7 -7
  30. {modern_di-0.2.0 → modern_di-0.3.0}/tests/test_container.py +1 -1
  31. {modern_di-0.2.0 → modern_di-0.3.0}/tests/test_graph.py +7 -7
  32. modern_di-0.2.0/.github/workflows/publish.yml +0 -20
  33. modern_di-0.2.0/modern_di/graph.py +0 -39
  34. modern_di-0.2.0/modern_di/resolvers/__init__.py +0 -13
  35. modern_di-0.2.0/modern_di/resolvers/singleton.py +0 -56
  36. {modern_di-0.2.0 → modern_di-0.3.0}/.gitignore +0 -0
  37. {modern_di-0.2.0 → modern_di-0.3.0}/.readthedocs.yaml +0 -0
  38. {modern_di-0.2.0 → modern_di-0.3.0}/LICENSE +0 -0
  39. {modern_di-0.2.0 → modern_di-0.3.0}/docs/conf.py +0 -0
  40. {modern_di-0.2.0 → modern_di-0.3.0}/docs/dev/contributing.md +0 -0
  41. {modern_di-0.2.0 → modern_di-0.3.0}/docs/index.md +0 -0
  42. {modern_di-0.2.0 → modern_di-0.3.0}/docs/requirements.txt +0 -0
  43. {modern_di-0.2.0 → modern_di-0.3.0/integrations/fastapi}/Justfile +0 -0
  44. {modern_di-0.2.0 → modern_di-0.3.0/integrations/fastapi}/tests/__init__.py +0 -0
  45. {modern_di-0.2.0 → modern_di-0.3.0}/modern_di/py.typed +0 -0
  46. {modern_di-0.2.0 → modern_di-0.3.0}/modern_di/scope.py +0 -0
  47. {modern_di-0.2.0/tests/resolvers → modern_di-0.3.0/tests}/__init__.py +0 -0
  48. {modern_di-0.2.0 → modern_di-0.3.0}/tests/creators.py +0 -0
@@ -1,13 +1,21 @@
1
- name: main
1
+ name: core ci
2
2
 
3
3
  on:
4
4
  push:
5
5
  branches:
6
6
  - main
7
- pull_request: {}
7
+ paths:
8
+ - 'modern_di/**'
9
+ - 'tests/**'
10
+ - '.github/workflows/core-ci.yml'
11
+ pull_request:
12
+ paths:
13
+ - 'modern_di/**'
14
+ - 'tests/**'
15
+ - '.github/workflows/core-ci.yml'
8
16
 
9
17
  concurrency:
10
- group: ${{ github.head_ref || github.run_id }}
18
+ group: ${{ github.head_ref || github.run_id }} core
11
19
  cancel-in-progress: true
12
20
 
13
21
  jobs:
@@ -19,7 +27,7 @@ jobs:
19
27
  - uses: astral-sh/setup-uv@v3
20
28
  with:
21
29
  enable-cache: true
22
- cache-dependency-glob: "**/pyproject.toml"
30
+ cache-dependency-glob: "pyproject.toml"
23
31
  - run: uv python install 3.10
24
32
  - run: just install lint-ci
25
33
 
@@ -39,13 +47,6 @@ jobs:
39
47
  - uses: astral-sh/setup-uv@v3
40
48
  with:
41
49
  enable-cache: true
42
- cache-dependency-glob: "**/pyproject.toml"
50
+ cache-dependency-glob: "pyproject.toml"
43
51
  - run: uv python install ${{ matrix.python-version }}
44
52
  - run: just install test . --cov=. --cov-report xml
45
- - uses: codecov/codecov-action@v4.0.1
46
- env:
47
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
48
- with:
49
- files: ./coverage.xml
50
- flags: unittests
51
- name: codecov-${{ matrix.python-version }}
@@ -0,0 +1,54 @@
1
+ name: fastapi ci
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - 'integrations/fastapi/**'
9
+ - '.github/workflows/fastapi-ci.yml'
10
+ pull_request:
11
+ paths:
12
+ - 'integrations/fastapi/**'
13
+ - '.github/workflows/fastapi-ci.yml'
14
+
15
+ defaults:
16
+ run:
17
+ working-directory: integrations/fastapi
18
+
19
+ concurrency:
20
+ group: ${{ github.head_ref || github.run_id }} fastapi
21
+ cancel-in-progress: false
22
+
23
+ jobs:
24
+ lint:
25
+ runs-on: ubuntu-latest
26
+ steps:
27
+ - uses: actions/checkout@v4
28
+ - uses: extractions/setup-just@v2
29
+ - uses: astral-sh/setup-uv@v3
30
+ with:
31
+ enable-cache: true
32
+ cache-dependency-glob: "pyproject.toml"
33
+ - run: uv python install 3.10
34
+ - run: just install lint-ci
35
+
36
+ pytest:
37
+ runs-on: ubuntu-latest
38
+ strategy:
39
+ fail-fast: false
40
+ matrix:
41
+ python-version:
42
+ - "3.10"
43
+ - "3.11"
44
+ - "3.12"
45
+ - "3.13"
46
+ steps:
47
+ - uses: actions/checkout@v4
48
+ - uses: extractions/setup-just@v2
49
+ - uses: astral-sh/setup-uv@v3
50
+ with:
51
+ enable-cache: true
52
+ cache-dependency-glob: "pyproject.toml"
53
+ - run: uv python install ${{ matrix.python-version }}
54
+ - run: just install test . --cov=. --cov-report xml
@@ -0,0 +1,41 @@
1
+ name: Publish Package
2
+
3
+ on:
4
+ release:
5
+ types:
6
+ - published
7
+
8
+ jobs:
9
+ publish-core:
10
+ if: startsWith(github.ref_name, 'core')
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: extractions/setup-just@v2
15
+ - uses: astral-sh/setup-uv@v3
16
+ with:
17
+ enable-cache: true
18
+ cache-dependency-glob: "pyproject.toml"
19
+ - run: just publish
20
+ env:
21
+ PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
22
+
23
+ publish-fastapi:
24
+ if: startsWith(github.ref_name, 'fastapi')
25
+ runs-on: ubuntu-latest
26
+ defaults:
27
+ run:
28
+ working-directory: integrations/fastapi
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+ - uses: extractions/setup-just@v2
32
+ - uses: astral-sh/setup-uv@v3
33
+ with:
34
+ enable-cache: true
35
+ cache-dependency-glob: "pyproject.toml"
36
+ - run: |
37
+ export SETUPTOOLS_SCM_PRETEND_VERSION=$(echo "${{ github.ref_name }}" | sed 's/^fastapi-//; s/-.*$//')
38
+ echo "SETUPTOOLS_SCM_PRETEND_VERSION=$SETUPTOOLS_SCM_PRETEND_VERSION"
39
+ just publish
40
+ env:
41
+ PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
@@ -0,0 +1,23 @@
1
+ default: install lint test
2
+
3
+ install:
4
+ uv lock --upgrade
5
+ uv sync --all-extras --frozen
6
+
7
+ lint:
8
+ uv run ruff format .
9
+ uv run ruff check . --fix
10
+ uv run mypy .
11
+
12
+ lint-ci:
13
+ uv run ruff format . --check
14
+ uv run ruff check . --no-fix
15
+ uv run mypy .
16
+
17
+ test *args:
18
+ uv run pytest tests {{ args }}
19
+
20
+ publish:
21
+ rm -rf dist
22
+ uv build
23
+ uv publish --token $PYPI_TOKEN
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: modern-di
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Dependency Injection framework with IOC-container and scopes
5
5
  Project-URL: repository, https://github.com/modern-python/modern-di
6
6
  Project-URL: docs, https://modern-di.readthedocs.io
@@ -19,7 +19,6 @@ Description-Content-Type: text/markdown
19
19
 
20
20
  "Modern-DI"
21
21
  ==
22
- [![Test Coverage](https://codecov.io/gh/modern-python/modern-di/branch/main/graph/badge.svg)](https://codecov.io/gh/modern-python/modern-di)
23
22
  [![MyPy Strict](https://img.shields.io/badge/mypy-strict-blue)](https://mypy.readthedocs.io/en/stable/getting_started.html#strict-mode-and-configuration)
24
23
  [![Supported versions](https://img.shields.io/pypi/pyversions/modern-di.svg)](https://pypi.python.org/pypi/modern-di)
25
24
  [![downloads](https://img.shields.io/pypi/dm/modern-di.svg)](https://pypistats.org/packages/modern-di)
@@ -27,7 +26,7 @@ Description-Content-Type: text/markdown
27
26
 
28
27
  Dependency injection framework for Python inspired by `dependency-injector` and `dishka`.
29
28
 
30
- It is production-ready and gives you the following:
29
+ It is in early development state and gives you the following:
31
30
  - DI framework with IOC-container and scopes.
32
31
  - Async and sync resolving.
33
32
  - Python 3.10-3.13 support.
@@ -1,6 +1,5 @@
1
1
  "Modern-DI"
2
2
  ==
3
- [![Test Coverage](https://codecov.io/gh/modern-python/modern-di/branch/main/graph/badge.svg)](https://codecov.io/gh/modern-python/modern-di)
4
3
  [![MyPy Strict](https://img.shields.io/badge/mypy-strict-blue)](https://mypy.readthedocs.io/en/stable/getting_started.html#strict-mode-and-configuration)
5
4
  [![Supported versions](https://img.shields.io/pypi/pyversions/modern-di.svg)](https://pypi.python.org/pypi/modern-di)
6
5
  [![downloads](https://img.shields.io/pypi/dm/modern-di.svg)](https://pypistats.org/packages/modern-di)
@@ -8,7 +7,7 @@
8
7
 
9
8
  Dependency injection framework for Python inspired by `dependency-injector` and `dishka`.
10
9
 
11
- It is production-ready and gives you the following:
10
+ It is in early development state and gives you the following:
12
11
  - DI framework with IOC-container and scopes.
13
12
  - Async and sync resolving.
14
13
  - Python 3.10-3.13 support.
@@ -9,7 +9,7 @@
9
9
  - context stacks for resources
10
10
  - overrides
11
11
 
12
- ### Resolvers
12
+ ### Providers
13
13
  - completely stateless
14
14
  - if dependency is already saved or overridden in `Container`, returns it
15
15
  - otherwise build dependency and save it to `Container`
@@ -17,7 +17,7 @@
17
17
 
18
18
  ### Graph
19
19
  - Cannot be instantiated
20
- - Contains graph of `Resolvers`
20
+ - Contains graph of `Providers`
21
21
  - Can initialize its resources and factories to container
22
22
 
23
23
  ### Questions
@@ -0,0 +1,6 @@
1
+ "Modern-DI-FastAPI"
2
+ ==
3
+
4
+ Integration of [Modern-DI](https://github.com/modern-python/modern-di) to FastAPI
5
+
6
+ 📚 [Documentation](https://modern-di.readthedocs.io)
@@ -0,0 +1,9 @@
1
+ from modern_di_fastapi.depends import FromDI, setup_modern_di
2
+ from modern_di_fastapi.middleware import ContainerMiddleware
3
+
4
+
5
+ __all__ = [
6
+ "ContainerMiddleware",
7
+ "FromDI",
8
+ "setup_modern_di",
9
+ ]
@@ -0,0 +1,24 @@
1
+ import dataclasses
2
+ import typing
3
+
4
+ import fastapi
5
+ from modern_di import Container, providers
6
+
7
+
8
+ T_co = typing.TypeVar("T_co", covariant=True)
9
+
10
+
11
+ @dataclasses.dataclass(slots=True, frozen=True)
12
+ class Dependency(typing.Generic[T_co]):
13
+ dependency: providers.AbstractProvider[T_co]
14
+
15
+ async def __call__(self, request: fastapi.Request) -> T_co:
16
+ return await self.dependency.async_resolve(request.state.modern_di_container)
17
+
18
+
19
+ def FromDI(dependency: providers.AbstractProvider[T_co], *, use_cache: bool = True) -> T_co: # noqa: N802
20
+ return typing.cast(T_co, fastapi.Depends(dependency=Dependency(dependency), use_cache=use_cache))
21
+
22
+
23
+ def setup_modern_di(container: Container, app: fastapi.FastAPI) -> None:
24
+ app.state.modern_di_container = container
@@ -0,0 +1,27 @@
1
+ import typing
2
+
3
+ import modern_di
4
+ from starlette.requests import Request
5
+ from starlette.types import ASGIApp, Receive, Scope, Send
6
+
7
+
8
+ class ContainerMiddleware:
9
+ def __init__(self, app: ASGIApp) -> None:
10
+ self.app = app
11
+
12
+ async def __call__(
13
+ self,
14
+ scope: Scope,
15
+ receive: Receive,
16
+ send: Send,
17
+ ) -> None:
18
+ if scope["type"] != "http":
19
+ return await self.app(scope, receive, send)
20
+
21
+ request = Request(scope, receive=receive, send=send)
22
+ context: dict[str, typing.Any] = {"request": request}
23
+
24
+ container: modern_di.Container = request.app.state.modern_di_container
25
+ async with container.build_child_container(context=context) as request_container:
26
+ request.state.modern_di_container = request_container
27
+ return await self.app(scope, receive, send)
@@ -0,0 +1,90 @@
1
+ [project]
2
+ name = "modern-di-fastapi"
3
+ description = "Modern-DI integration for FastAPI"
4
+ authors = [
5
+ { name = "Artur Shiriev", email = "me@shiriev.ru" },
6
+ ]
7
+ readme = "README.md"
8
+ requires-python = ">=3.10,<4"
9
+ license = "MIT"
10
+ keywords = ["DI", "dependency injector", "ioc-container", "FastAPI", "python"]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3.10",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Typing :: Typed",
17
+ "Topic :: Software Development :: Libraries",
18
+ ]
19
+ packages = [
20
+ { include = "modern_di_fastapi" },
21
+ ]
22
+ dynamic = ["version"]
23
+ dependencies = [
24
+ "fastapi>=0.100",
25
+ "modern-di",
26
+ ]
27
+
28
+ [project.urls]
29
+ repository = "https://github.com/modern-python/modern-di"
30
+ docs = "https://modern-di.readthedocs.io"
31
+
32
+ [dependency-groups]
33
+ dev = [
34
+ "httpx",
35
+ "pytest",
36
+ "pytest-cov",
37
+ "pytest-asyncio",
38
+ "ruff",
39
+ "mypy",
40
+ "typing-extensions",
41
+ "asgi-lifespan",
42
+ ]
43
+
44
+ [tool.uv.sources]
45
+ modern-di = { path = "../../" }
46
+
47
+ [build-system]
48
+ requires = ["hatchling", "hatch-vcs"]
49
+ build-backend = "hatchling.build"
50
+
51
+ [tool.hatch.version]
52
+ source = "vcs"
53
+ fallback-version = "0"
54
+
55
+ [tool.mypy]
56
+ python_version = "3.10"
57
+ strict = true
58
+
59
+ [tool.ruff]
60
+ fix = true
61
+ unsafe-fixes = true
62
+ line-length = 120
63
+ target-version = "py310"
64
+ extend-exclude = [
65
+ "docs",
66
+ ]
67
+
68
+ [tool.ruff.lint]
69
+ select = ["ALL"]
70
+ ignore = [
71
+ "D1", # allow missing docstrings
72
+ "S101", # allow asserts
73
+ "TCH", # ignore flake8-type-checking
74
+ "FBT", # allow boolean args
75
+ "ANN101", # missing-type-self
76
+ "ANN102", # missing-type-cls
77
+ "D203", # "one-blank-line-before-class" conflicting with D211
78
+ "D213", # "multi-line-summary-second-line" conflicting with D212
79
+ "COM812", # flake8-commas "Trailing comma missing"
80
+ "ISC001", # flake8-implicit-str-concat
81
+ ]
82
+ isort.lines-after-imports = 2
83
+ isort.no-lines-before = ["standard-library", "local-folder"]
84
+
85
+ [tool.pytest.ini_options]
86
+ addopts = "--cov=. --cov-report term-missing"
87
+ asyncio_mode = "auto"
88
+
89
+ [tool.coverage.report]
90
+ exclude_also = ["if typing.TYPE_CHECKING:"]
@@ -0,0 +1,69 @@
1
+ import contextlib
2
+ import dataclasses
3
+ import typing
4
+
5
+ import fastapi
6
+ import httpx
7
+ import modern_di
8
+ import pytest
9
+ from asgi_lifespan import LifespanManager
10
+ from modern_di import Scope, providers
11
+ from starlette import status
12
+ from starlette.requests import Request
13
+
14
+ import modern_di_fastapi
15
+ from modern_di_fastapi import ContainerMiddleware, FromDI
16
+
17
+
18
+ @contextlib.asynccontextmanager
19
+ async def lifespan(app_: fastapi.FastAPI) -> typing.AsyncIterator[None]:
20
+ di_container = modern_di.Container(scope=modern_di.Scope.APP)
21
+ modern_di_fastapi.setup_modern_di(container=di_container, app=app_)
22
+ async with di_container:
23
+ yield
24
+
25
+
26
+ app = fastapi.FastAPI(lifespan=lifespan)
27
+ app.add_middleware(ContainerMiddleware)
28
+
29
+
30
+ @dataclasses.dataclass(kw_only=True, slots=True)
31
+ class SimpleCreator:
32
+ dep1: str
33
+
34
+
35
+ @dataclasses.dataclass(kw_only=True, slots=True)
36
+ class DependentCreator:
37
+ dep1: SimpleCreator
38
+
39
+
40
+ def context_adapter_function(*, request: Request, **_: object) -> str:
41
+ return request.method
42
+
43
+
44
+ app_factory = providers.Factory(Scope.APP, SimpleCreator, dep1="original")
45
+ request_factory = providers.Factory(Scope.REQUEST, DependentCreator, dep1=app_factory.cast)
46
+ context_adapter = providers.ContextAdapter(Scope.REQUEST, context_adapter_function)
47
+
48
+
49
+ @app.get("/")
50
+ async def read_root(
51
+ app_factory_instance: typing.Annotated[SimpleCreator, FromDI(app_factory)],
52
+ request_factory_instance: typing.Annotated[DependentCreator, FromDI(request_factory)],
53
+ method: typing.Annotated[str, FromDI(context_adapter)],
54
+ ) -> str:
55
+ assert isinstance(app_factory_instance, SimpleCreator)
56
+ assert isinstance(request_factory_instance, DependentCreator)
57
+ return method
58
+
59
+
60
+ @pytest.fixture(scope="session")
61
+ async def client() -> typing.AsyncIterator[httpx.AsyncClient]:
62
+ async with LifespanManager(app):
63
+ yield httpx.AsyncClient(app=app, base_url="http://test")
64
+
65
+
66
+ async def test_read_main(client: httpx.AsyncClient) -> None:
67
+ response = await client.get("/")
68
+ assert response.status_code == status.HTTP_200_OK
69
+ assert response.json() == "GET"
@@ -7,5 +7,5 @@ __all__ = [
7
7
  "BaseGraph",
8
8
  "Container",
9
9
  "Scope",
10
- "resolvers",
10
+ "providers",
11
11
  ]
@@ -3,7 +3,7 @@ import enum
3
3
  import types
4
4
  import typing
5
5
 
6
- from modern_di.resolver_state import ResolverState
6
+ from modern_di.provider_state import ProviderState
7
7
 
8
8
 
9
9
  if typing.TYPE_CHECKING:
@@ -14,29 +14,37 @@ T_co = typing.TypeVar("T_co", covariant=True)
14
14
 
15
15
 
16
16
  class Container(contextlib.AbstractAsyncContextManager["Container"]):
17
- __slots__ = "scope", "parent_container", "_is_async", "_resolver_states", "_overrides"
17
+ __slots__ = "scope", "parent_container", "context", "_is_async", "_provider_states", "_overrides"
18
18
 
19
- def __init__(self, *, scope: enum.IntEnum, parent_container: typing.Optional["Container"] = None) -> None:
19
+ def __init__(
20
+ self,
21
+ *,
22
+ scope: enum.IntEnum,
23
+ parent_container: typing.Optional["Container"] = None,
24
+ context: dict[str, typing.Any] | None = None,
25
+ ) -> None:
20
26
  if scope.value != 1 and parent_container is None:
21
27
  msg = "Only first scope can be used without parent_container"
22
28
  raise RuntimeError(msg)
23
29
 
24
30
  self.scope = scope
25
31
  self.parent_container = parent_container
32
+ self.context: dict[str, typing.Any] = context or {}
26
33
  self._is_async: bool | None = None
27
- self._resolver_states: dict[str, ResolverState[typing.Any]] = {}
34
+ self._provider_states: dict[str, ProviderState[typing.Any]] = {}
28
35
  self._overrides: dict[str, typing.Any] = {}
29
36
 
30
37
  def _exit(self) -> None:
31
38
  self._is_async = None
32
- self._resolver_states = {}
39
+ self._provider_states = {}
40
+ self._overrides = {}
33
41
 
34
42
  def _check_entered(self) -> None:
35
43
  if self._is_async is None:
36
44
  msg = "Enter the context first"
37
45
  raise RuntimeError(msg)
38
46
 
39
- def build_child_container(self) -> "typing_extensions.Self":
47
+ def build_child_container(self, context: dict[str, typing.Any] | None = None) -> "typing_extensions.Self":
40
48
  self._check_entered()
41
49
 
42
50
  try:
@@ -45,7 +53,7 @@ class Container(contextlib.AbstractAsyncContextManager["Container"]):
45
53
  msg = f"Max scope is reached, {self.scope.name}"
46
54
  raise RuntimeError(msg) from exc
47
55
 
48
- return self.__class__(scope=new_scope, parent_container=self)
56
+ return self.__class__(scope=new_scope, parent_container=self, context=context)
49
57
 
50
58
  def find_container(self, scope: enum.IntEnum) -> "typing_extensions.Self":
51
59
  container = self
@@ -53,30 +61,30 @@ class Container(contextlib.AbstractAsyncContextManager["Container"]):
53
61
  container = typing.cast("typing_extensions.Self", container.parent_container)
54
62
  return container
55
63
 
56
- def fetch_resolver_state(
57
- self, resolver_id: str, is_async_resource: bool = False, is_lock_required: bool = False
58
- ) -> ResolverState[typing.Any]:
64
+ def fetch_provider_state(
65
+ self, provider_id: str, is_async_resource: bool = False, is_lock_required: bool = False
66
+ ) -> ProviderState[typing.Any]:
59
67
  self._check_entered()
60
68
  if is_async_resource and self._is_async is False:
61
69
  msg = "Resolving async resource in sync container is not allowed"
62
70
  raise RuntimeError(msg)
63
71
 
64
- if resolver_id not in self._resolver_states:
65
- self._resolver_states[resolver_id] = ResolverState(is_lock_required=is_lock_required)
72
+ if provider_id not in self._provider_states:
73
+ self._provider_states[provider_id] = ProviderState(is_lock_required=is_lock_required)
66
74
 
67
- return self._resolver_states[resolver_id]
75
+ return self._provider_states[provider_id]
68
76
 
69
- def override(self, resolver_id: str, override_object: object) -> None:
70
- self._overrides[resolver_id] = override_object
77
+ def override(self, provider_id: str, override_object: object) -> None:
78
+ self._overrides[provider_id] = override_object
71
79
 
72
- def fetch_override(self, resolver_id: str) -> object | None:
73
- return self._overrides.get(resolver_id)
80
+ def fetch_override(self, provider_id: str) -> object | None:
81
+ return self._overrides.get(provider_id)
74
82
 
75
- def reset_override(self, resolver_id: str | None = None) -> None:
76
- if resolver_id is None:
83
+ def reset_override(self, provider_id: str | None = None) -> None:
84
+ if provider_id is None:
77
85
  self._overrides = {}
78
86
  else:
79
- self._overrides.pop(resolver_id, None)
87
+ self._overrides.pop(provider_id, None)
80
88
 
81
89
  async def __aenter__(self) -> "Container":
82
90
  self._is_async = True
@@ -89,8 +97,8 @@ class Container(contextlib.AbstractAsyncContextManager["Container"]):
89
97
  traceback: types.TracebackType | None,
90
98
  ) -> None:
91
99
  self._check_entered()
92
- for resolver_state in reversed(self._resolver_states.values()):
93
- await resolver_state.async_tear_down()
100
+ for provider_state in reversed(self._provider_states.values()):
101
+ await provider_state.async_tear_down()
94
102
  self._exit()
95
103
 
96
104
  def __enter__(self) -> "Container":
@@ -104,6 +112,6 @@ class Container(contextlib.AbstractAsyncContextManager["Container"]):
104
112
  traceback: types.TracebackType | None,
105
113
  ) -> None:
106
114
  self._check_entered()
107
- for resolver_state in reversed(self._resolver_states.values()):
108
- resolver_state.sync_tear_down()
115
+ for provider_state in reversed(self._provider_states.values()):
116
+ provider_state.sync_tear_down()
109
117
  self._exit()
@@ -0,0 +1,39 @@
1
+ import typing
2
+
3
+ from modern_di import Container
4
+ from modern_di.providers import AbstractProvider, BaseCreatorProvider
5
+
6
+
7
+ if typing.TYPE_CHECKING:
8
+ import typing_extensions
9
+
10
+
11
+ T = typing.TypeVar("T")
12
+ P = typing.ParamSpec("P")
13
+
14
+
15
+ class BaseGraph:
16
+ providers: dict[str, AbstractProvider[typing.Any]]
17
+
18
+ def __new__(cls, *_: typing.Any, **__: typing.Any) -> "typing_extensions.Self": # noqa: ANN401
19
+ msg = f"{cls.__name__} cannot not be instantiated"
20
+ raise RuntimeError(msg)
21
+
22
+ @classmethod
23
+ def get_providers(cls) -> dict[str, AbstractProvider[typing.Any]]:
24
+ if not hasattr(cls, "providers"):
25
+ cls.providers = {k: v for k, v in cls.__dict__.items() if isinstance(v, AbstractProvider)}
26
+
27
+ return cls.providers
28
+
29
+ @classmethod
30
+ async def async_resolve_creators(cls, container: Container) -> None:
31
+ for provider in cls.get_providers().values():
32
+ if isinstance(provider, BaseCreatorProvider) and provider.scope == container.scope:
33
+ await provider.async_resolve(container)
34
+
35
+ @classmethod
36
+ def sync_resolve_creators(cls, container: Container) -> None:
37
+ for provider in cls.get_providers().values():
38
+ if isinstance(provider, BaseCreatorProvider) and provider.scope == container.scope:
39
+ provider.sync_resolve(container)
@@ -6,13 +6,13 @@ import typing
6
6
  T_co = typing.TypeVar("T_co", covariant=True)
7
7
 
8
8
 
9
- class ResolverState(typing.Generic[T_co]):
10
- __slots__ = "context_stack", "instance", "resolver_lock"
9
+ class ProviderState(typing.Generic[T_co]):
10
+ __slots__ = "context_stack", "instance", "provider_lock"
11
11
 
12
12
  def __init__(self, is_lock_required: bool) -> None:
13
13
  self.context_stack: contextlib.AsyncExitStack | contextlib.ExitStack | None = None
14
14
  self.instance: T_co | None = None
15
- self.resolver_lock: typing.Final = asyncio.Lock() if is_lock_required else None
15
+ self.provider_lock: typing.Final = asyncio.Lock() if is_lock_required else None
16
16
 
17
17
  async def async_tear_down(self) -> None:
18
18
  if self.context_stack is None:
@@ -0,0 +1,15 @@
1
+ from modern_di.providers.base import AbstractProvider, BaseCreatorProvider
2
+ from modern_di.providers.context_adapter import ContextAdapter
3
+ from modern_di.providers.factory import Factory
4
+ from modern_di.providers.resource import Resource
5
+ from modern_di.providers.singleton import Singleton
6
+
7
+
8
+ __all__ = [
9
+ "AbstractProvider",
10
+ "BaseCreatorProvider",
11
+ "ContextAdapter",
12
+ "Factory",
13
+ "Singleton",
14
+ "Resource",
15
+ ]