From 7474113a0f726be85f3e9d1ed397154d10b92d67 Mon Sep 17 00:00:00 2001
From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Date: Wed, 2 Nov 2022 14:55:35 -0500
Subject: [PATCH] Rename Dependant to Dependent (#90)
* Rename Dependant to Dependent
Fixes #89
---
README.md | 4 +-
benchmarks/solve.py | 6 +-
benchmarks/utils.py | 8 +--
di/_utils/task.py | 8 +--
di/api/dependencies.py | 14 ++--
di/api/executor.py | 4 +-
di/api/solved.py | 16 ++---
di/container/_bind_by_type_hook.py | 10 +--
di/container/_bind_hook.py | 6 +-
di/container/_container.py | 14 ++--
di/container/_execution_planning.py | 10 +--
di/container/_solving.py | 66 +++++++++----------
di/dependant/__init__.py | 10 ---
di/dependant/_joined.py | 39 -----------
di/dependent/__init__.py | 10 +++
.../_dependant.py => dependent/_dependent.py} | 26 ++++----
.../_injectable_type.py | 8 +--
di/dependent/_joined.py | 39 +++++++++++
di/exceptions.py | 8 +--
di/typing.py | 4 +-
docs/architecture.md | 30 ++++-----
docs/autowiring.py | 4 +-
docs/binds.md | 4 +-
docs/cache.md | 8 +--
docs/dependants.md | 18 ++---
docs/scopes.md | 2 +-
docs/solving.md | 22 +++----
docs/wiring.md | 30 ++++-----
docs_src/async_constructor.py | 10 +--
docs_src/async_init_dependency.py | 4 +-
docs_src/autowiring.py | 4 +-
docs_src/bind_as_a_dep.py | 8 +--
docs_src/bind_hooks.py | 12 ++--
docs_src/default_scope.py | 12 ++--
docs_src/headers_example.py | 14 ++--
docs_src/injectable_class.py | 4 +-
...endance.py => invalid_scope_dependence.py} | 4 +-
...oined_dependant.py => joined_dependent.py} | 10 +--
docs_src/markers.py | 4 +-
docs_src/sharing.py | 6 +-
docs_src/simple.py | 4 +-
docs_src/singleton.py | 8 +--
...olved_dependant.py => solved_dependent.py} | 12 ++--
docs_src/web_framework.py | 4 +-
mkdocs.yml | 2 +-
pyproject.toml | 2 +-
tests/docs/test_joined_dependant.py | 4 +-
tests/docs/test_scopes_example.py | 4 +-
tests/docs/test_solved.py | 4 +-
tests/test_binding.py | 36 +++++-----
tests/test_caching.py | 22 +++----
tests/test_dependant.py | 22 +++----
tests/test_dependency_cycles.py | 4 +-
tests/test_exceptions.py | 48 +++++++-------
tests/test_execute.py | 18 ++---
tests/test_injectable_class.py | 6 +-
tests/test_positional_only.py | 4 +-
tests/test_scoping.py | 16 ++---
tests/test_solving.py | 46 ++++++-------
tests/test_task.py | 4 +-
tests/test_wiring.py | 12 ++--
tests/test_wiring_annotated.py | 12 ++--
tests/test_wiring_forward_refs.py | 4 +-
tests/test_wiring_pep_563.py | 4 +-
64 files changed, 411 insertions(+), 411 deletions(-)
delete mode 100644 di/dependant/__init__.py
delete mode 100644 di/dependant/_joined.py
create mode 100644 di/dependent/__init__.py
rename di/{dependant/_dependant.py => dependent/_dependent.py} (91%)
rename di/{dependant => dependent}/_injectable_type.py (62%)
create mode 100644 di/dependent/_joined.py
rename docs_src/{invalid_scope_dependance.py => invalid_scope_dependence.py} (79%)
rename docs_src/{joined_dependant.py => joined_dependent.py} (63%)
rename docs_src/{solved_dependant.py => solved_dependent.py} (63%)
diff --git a/README.md b/README.md
index 82ab2b87..50c71c33 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@ Here is a simple example of how `di` works:
```python
from dataclasses import dataclass
-from di import Container, Dependant, SyncExecutor
+from di import Container, Dependent, SyncExecutor
class A:
@@ -60,7 +60,7 @@ class C:
def main():
container = Container()
executor = SyncExecutor()
- solved = container.solve(Dependant(C, scope="request"), scopes=["request"])
+ solved = container.solve(Dependent(C, scope="request"), scopes=["request"])
with container.enter_scope("request") as state:
c = container.execute_sync(solved, executor=executor, state=state)
assert isinstance(c, C)
diff --git a/benchmarks/solve.py b/benchmarks/solve.py
index 9ed266d8..760e0713 100644
--- a/benchmarks/solve.py
+++ b/benchmarks/solve.py
@@ -10,7 +10,7 @@
from benchmarks.utils import GraphSize, SleepTimes, generate_dag
from di.api.executor import SupportsAsyncExecutor, SupportsSyncExecutor
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import AsyncExecutor, ConcurrentAsyncExecutor, SyncExecutor
INTERVAL = 10e-6 # 10 us
@@ -25,7 +25,7 @@ async def async_bench(
) -> None:
container = Container()
solved = container.solve(
- Dependant(generate_dag(graph, sync=False, sleep=sleep)), scopes=[None]
+ Dependent(generate_dag(graph, sync=False, sleep=sleep)), scopes=[None]
)
p = Profiler()
async with container.enter_scope(None) as state:
@@ -49,7 +49,7 @@ def sync_bench(
) -> None:
container = Container()
solved = container.solve(
- Dependant(generate_dag(graph, sync=True, sleep=sleep)), scopes=[None]
+ Dependent(generate_dag(graph, sync=True, sleep=sleep)), scopes=[None]
)
executor = SyncExecutor()
p = Profiler()
diff --git a/benchmarks/utils.py b/benchmarks/utils.py
index fdb40a27..e3f1ebb1 100644
--- a/benchmarks/utils.py
+++ b/benchmarks/utils.py
@@ -5,7 +5,7 @@
import anyio # noqa
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.typing import Annotated
random = Random(0)
@@ -52,7 +52,7 @@ async def fasync(secs: float) -> None:
globals: Dict[str, Any] = {
"Annotated": Annotated,
"sleep": sleep_func,
- "Dependant": Dependant,
+ "Dependent": Dependent,
}
funcs: Dict[str, Callable[..., Any]] = {}
@@ -66,7 +66,7 @@ async def fasync(secs: float) -> None:
)
params = ", ".join(
[
- f"dep_{dep_name}: Annotated[None, Dependant({dep_name})]"
+ f"dep_{dep_name}: Annotated[None, Dependent({dep_name})]"
for dep_name in deps
]
)
@@ -77,7 +77,7 @@ async def fasync(secs: float) -> None:
name = "final"
deps = list(funcs.keys())
params = ", ".join(
- [f"dep_{dep_name}: Annotated[None, Dependant({dep_name})]" for dep_name in deps]
+ [f"dep_{dep_name}: Annotated[None, Dependent({dep_name})]" for dep_name in deps]
)
func_def = template.format(name, params, 0)
exec(func_def, globals, funcs)
diff --git a/di/_utils/task.py b/di/_utils/task.py
index 1a3369c0..4e9f6a34 100644
--- a/di/_utils/task.py
+++ b/di/_utils/task.py
@@ -22,7 +22,7 @@
)
from di._utils.scope_map import ScopeMap
from di._utils.types import CacheKey
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
from di.api.providers import DependencyProvider
from di.api.scopes import Scope
from di.exceptions import IncompatibleDependencyError
@@ -47,7 +47,7 @@ class Task:
"user_function",
"scope",
"cache_key",
- "dependant",
+ "dependent",
"task_id",
"call_user_func_with_deps",
"compute",
@@ -66,7 +66,7 @@ def __init__(
call: DependencyProvider,
use_cache: bool,
cache_key: CacheKey,
- dependant: DependantBase[Any],
+ dependent: DependentBase[Any],
task_id: int,
positional_parameters: Iterable[Task],
keyword_parameters: Mapping[str, Task],
@@ -74,7 +74,7 @@ def __init__(
self.scope = scope
self.user_function = call
self.cache_key = cache_key
- self.dependant = dependant
+ self.dependent = dependent
self.task_id = task_id
if is_async_gen_callable(self.user_function):
self.wrapped_call = contextlib.asynccontextmanager(call) # type: ignore[arg-type]
diff --git a/di/api/dependencies.py b/di/api/dependencies.py
index 23da2025..d968bf98 100644
--- a/di/api/dependencies.py
+++ b/di/api/dependencies.py
@@ -16,7 +16,7 @@
__all__ = (
"CacheKey",
- "DependantBase",
+ "DependentBase",
"DependencyParameter",
"InjectableClassProvider",
)
@@ -25,13 +25,13 @@
@runtime_checkable
class InjectableClassProvider(Protocol):
@classmethod
- def __di_dependency__(cls, param: inspect.Parameter) -> "DependantBase[Any]":
+ def __di_dependency__(cls, param: inspect.Parameter) -> "DependentBase[Any]":
...
-class DependantBase(Generic[T]):
- """A dependant is an object that can provide the container with:
- - A hash, to compare itself against other dependants
+class DependentBase(Generic[T]):
+ """A dependent is an object that can provide the container with:
+ - A hash, to compare itself against other dependents
- A scope
- A callable who's returned value is the dependency
"""
@@ -45,10 +45,10 @@ def cache_key(self) -> CacheKey:
raise NotImplementedError
def get_dependencies(self) -> "List[DependencyParameter]":
- """Collect all of the sub dependencies for this dependant"""
+ """Collect all of the sub dependencies for this dependent"""
raise NotImplementedError
class DependencyParameter(NamedTuple):
- dependency: DependantBase[Any]
+ dependency: DependentBase[Any]
parameter: Optional[inspect.Parameter]
diff --git a/di/api/executor.py b/di/api/executor.py
index 4df8aa5f..6fa3049b 100644
--- a/di/api/executor.py
+++ b/di/api/executor.py
@@ -8,13 +8,13 @@
else:
from typing import Protocol
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
StateType = TypeVar("StateType")
class Task(Hashable, Protocol[StateType]):
- dependant: DependantBase[StateType]
+ dependent: DependentBase[StateType]
@property
def compute(self) -> Callable[[StateType], Union[Awaitable[None], None]]:
diff --git a/di/api/solved.py b/di/api/solved.py
index 0d1aad5f..c046f75c 100644
--- a/di/api/solved.py
+++ b/di/api/solved.py
@@ -1,31 +1,31 @@
import typing
from typing import Any, Generic, Iterable, Mapping, TypeVar
-from di.api.dependencies import DependantBase, DependencyParameter
+from di.api.dependencies import DependencyParameter, DependentBase
Dependency = Any
DependencyType = TypeVar("DependencyType")
-class SolvedDependant(Generic[DependencyType]):
+class SolvedDependent(Generic[DependencyType]):
"""Representation of a fully solved dependency as DAG.
- A SolvedDependant could be a user's endpoint/controller function.
+ A SolvedDependent could be a user's endpoint/controller function.
"""
__slots__ = ("dependency", "dag", "container_cache")
- dependency: DependantBase[DependencyType]
- dag: Mapping[DependantBase[Any], Iterable[DependencyParameter]]
+ dependency: DependentBase[DependencyType]
+ dag: Mapping[DependentBase[Any], Iterable[DependencyParameter]]
# container_cache can be used by the creating container to store data that is tied
- # to the SolvedDependant
+ # to the SolvedDependent
container_cache: typing.Any
def __init__(
self,
- dependency: DependantBase[DependencyType],
- dag: Mapping[DependantBase[Any], Iterable[DependencyParameter]],
+ dependency: DependentBase[DependencyType],
+ dag: Mapping[DependentBase[Any], Iterable[DependencyParameter]],
container_cache: typing.Any,
):
self.dependency = dependency
diff --git a/di/container/_bind_by_type_hook.py b/di/container/_bind_by_type_hook.py
index a41c27ad..23375cfa 100644
--- a/di/container/_bind_by_type_hook.py
+++ b/di/container/_bind_by_type_hook.py
@@ -2,12 +2,12 @@
from typing import Any, Optional
from di._utils.inspect import get_type
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
from di.container._bind_hook import BindHook
def bind_by_type(
- provider: DependantBase[Any],
+ provider: DependentBase[Any],
dependency: type,
*,
covariant: bool = False,
@@ -15,9 +15,9 @@ def bind_by_type(
"""Hook to substitute the matched dependency"""
def hook(
- param: Optional[inspect.Parameter], dependant: DependantBase[Any]
- ) -> Optional[DependantBase[Any]]:
- if dependant.call is dependency:
+ param: Optional[inspect.Parameter], dependent: DependentBase[Any]
+ ) -> Optional[DependentBase[Any]]:
+ if dependent.call is dependency:
return provider
if param is None:
return None
diff --git a/di/container/_bind_hook.py b/di/container/_bind_hook.py
index a16b374d..fc0a8fee 100644
--- a/di/container/_bind_hook.py
+++ b/di/container/_bind_hook.py
@@ -8,11 +8,11 @@
from typing import Protocol
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
class BindHook(Protocol):
def __call__(
- self, param: Optional[inspect.Parameter], dependant: DependantBase[Any]
- ) -> Optional[DependantBase[Any]]: # pragma: no cover
+ self, param: Optional[inspect.Parameter], dependent: DependentBase[Any]
+ ) -> Optional[DependentBase[Any]]: # pragma: no cover
...
diff --git a/di/container/_container.py b/di/container/_container.py
index cb753c0b..6cc3a0a3 100644
--- a/di/container/_container.py
+++ b/di/container/_container.py
@@ -11,11 +11,11 @@
)
from di._utils.types import FusedContextManager
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
from di.api.executor import SupportsAsyncExecutor, SupportsSyncExecutor
from di.api.providers import DependencyProvider
from di.api.scopes import Scope
-from di.api.solved import SolvedDependant
+from di.api.solved import SolvedDependent
from di.container._bind_hook import BindHook
from di.container._execution_planning import plan_execution
from di.container._solving import ScopeResolver, solve
@@ -30,7 +30,7 @@ class Container:
Generally you will want one Container per application.
There is not performance advantage to re-using a container, the only reason to do so is to share binds.
For each "thing" you want to wire with di and execute you'll want to call `Container.solve()`
- exactly once and then keep a reference to the returned `SolvedDependant` to pass to `Container.execute`.
+ exactly once and then keep a reference to the returned `SolvedDependent` to pass to `Container.execute`.
Solving is very expensive so avoid doing it in a hot loop.
"""
@@ -64,10 +64,10 @@ def unbind() -> "Generator[None, None, None]":
def solve(
self,
- dependency: DependantBase[DependencyType],
+ dependency: DependentBase[DependencyType],
scopes: Sequence[Scope],
scope_resolver: Optional[ScopeResolver] = None,
- ) -> SolvedDependant[DependencyType]:
+ ) -> SolvedDependent[DependencyType]:
"""Build the dependency graph.
Should happen once, maybe during startup.
@@ -78,7 +78,7 @@ def solve(
def execute_sync(
self,
- solved: SolvedDependant[DependencyType],
+ solved: SolvedDependent[DependencyType],
executor: SupportsSyncExecutor,
*,
state: ContainerState,
@@ -100,7 +100,7 @@ def execute_sync(
async def execute_async(
self,
- solved: SolvedDependant[DependencyType],
+ solved: SolvedDependent[DependencyType],
executor: SupportsAsyncExecutor,
*,
state: ContainerState,
diff --git a/di/container/_execution_planning.py b/di/container/_execution_planning.py
index 4eee0548..18e41676 100644
--- a/di/container/_execution_planning.py
+++ b/di/container/_execution_planning.py
@@ -21,7 +21,7 @@
from di.api.executor import Task as SupportsTask
from di.api.providers import DependencyProvider
from di.api.scopes import Scope
-from di.api.solved import SolvedDependant
+from di.api.solved import SolvedDependent
class TaskGraph:
@@ -56,8 +56,8 @@ def static_order(self) -> Iterable[Task]:
return self._static_order
-class SolvedDependantCache(NamedTuple):
- """Private data that the Container attaches to SolvedDependant"""
+class SolvedDependentCache(NamedTuple):
+ """Private data that the Container attaches to SolvedDependent"""
root_task: Task
topological_sorter: TopologicalSorter[Task]
@@ -71,10 +71,10 @@ class SolvedDependantCache(NamedTuple):
def plan_execution(
stacks: Mapping[Scope, Union[AsyncExitStack, ExitStack]],
cache: ScopeMap[CacheKey, Any],
- solved: SolvedDependant[Any],
+ solved: SolvedDependent[Any],
values: Optional[Mapping[DependencyProvider, Any]] = None,
) -> Tuple[List[Any], SupportsTaskGraph[ExecutionState], ExecutionState, Task,]:
- solved_dependency_cache: SolvedDependantCache = solved.container_cache
+ solved_dependency_cache: SolvedDependentCache = solved.container_cache
results = solved_dependency_cache.empty_results.copy()
if values is None:
values = EMPTY_VALUES
diff --git a/di/container/_solving.py b/di/container/_solving.py
index 03026c7d..f55a913c 100644
--- a/di/container/_solving.py
+++ b/di/container/_solving.py
@@ -10,11 +10,11 @@
from graphlib2 import TopologicalSorter
from di._utils.task import Task
-from di.api.dependencies import CacheKey, DependantBase, DependencyParameter
+from di.api.dependencies import CacheKey, DependencyParameter, DependentBase
from di.api.scopes import Scope
-from di.api.solved import SolvedDependant
+from di.api.solved import SolvedDependent
from di.container._bind_hook import BindHook
-from di.container._execution_planning import SolvedDependantCache
+from di.container._execution_planning import SolvedDependentCache
from di.exceptions import (
DependencyCycleError,
ScopeViolationError,
@@ -35,35 +35,35 @@
class ScopeResolver(Protocol):
def __call__(
self,
- __dependant: DependantBase[Any],
+ __dependent: DependentBase[Any],
__sub_dependenant_scopes: Sequence[Scope],
__solver_scopes: Sequence[Scope],
) -> Scope:
- """Infer scopes for a Marker/Dependant that does not have an explicit scope.
+ """Infer scopes for a Marker/Dependent that does not have an explicit scope.
- The three paramters given are:
+ The three parameters given are:
- `sub_dependenant_scopes`: the scopes of all sub-dependencies (if any).
This can be used to set a lower bound for the scope.
For example, if a sub dependency has some "singleton" scope
- our current dependency (the `dependant` argument) cannot have some "ephemeral"
+ our current dependency (the `dependent` argument) cannot have some "ephemeral"
scope because that would violate scoping rules.
- `solver_scopes`: the scopes passed to `Container.solve`. Provided for convenience.
- - `dependant`: the current dependency we are inferring a scope for.
+ - `dependent`: the current dependency we are inferring a scope for.
"""
-def get_path_str(path: Iterable[DependantBase[Any]]) -> str:
+def get_path_str(path: Iterable[DependentBase[Any]]) -> str:
return " -> ".join(
[repr(item) if item.call is not None else repr(item.call) for item in path]
)
def get_params(
- dep: DependantBase[Any],
+ dep: DependentBase[Any],
binds: Iterable[BindHook],
- path: Iterable[DependantBase[Any]],
+ path: Iterable[DependentBase[Any]],
) -> List[DependencyParameter]:
- """Get Dependants for parameters and resolve binds"""
+ """Get Dependents for parameters and resolve binds"""
params = dep.get_dependencies().copy()
for idx, param in enumerate(params):
for hook in binds:
@@ -93,30 +93,30 @@ def check_task_scope_validity(
task: Task,
subtasks: Iterable[Task],
scopes: Mapping[Scope, int],
- path: Iterable[DependantBase[Any]],
+ path: Iterable[DependentBase[Any]],
) -> None:
if task.scope not in scopes:
raise UnknownScopeError(
- f"Dependency{task.dependant} has an unknown scope {task.scope}."
+ f"Dependency{task.dependent} has an unknown scope {task.scope}."
f"\nExample Path: {get_path_str(path)}"
)
for subtask in subtasks:
if scopes[task.scope] < scopes[subtask.scope]:
raise ScopeViolationError(
- f"{task.dependant.call} cannot depend on {subtask.dependant.call}"
- f" because {subtask.dependant.call}'s scope ({subtask.scope})"
- f" is narrower than {task.dependant.call}'s scope ({task.scope})"
+ f"{task.dependent.call} cannot depend on {subtask.dependent.call}"
+ f" because {subtask.dependent.call}'s scope ({subtask.scope})"
+ f" is narrower than {task.dependent.call}'s scope ({task.scope})"
f"\nExample Path: {get_path_str(path)}"
)
def build_task(
- dependency: DependantBase[Any],
+ dependency: DependentBase[Any],
binds: Iterable[BindHook],
tasks: Dict[CacheKey, Task],
task_dag: Dict[Task, List[Task]],
- dependant_dag: Dict[DependantBase[Any], List[DependencyParameter]],
- path: Dict[DependantBase[Any], Any],
+ dependent_dag: Dict[DependentBase[Any], List[DependencyParameter]],
+ path: Dict[DependentBase[Any], Any],
scope_idxs: Mapping[Scope, int],
scope_resolver: Optional[ScopeResolver],
) -> Task:
@@ -148,7 +148,7 @@ def build_task(
binds,
tasks,
task_dag,
- dependant_dag,
+ dependent_dag,
path,
scope_idxs,
scope_resolver,
@@ -160,10 +160,10 @@ def build_task(
else:
keyword_parameters[param.parameter.name] = child_task
if (
- param.dependency not in dependant_dag
+ param.dependency not in dependent_dag
and param.dependency.cache_key not in tasks
):
- dependant_dag[param.dependency] = []
+ dependent_dag[param.dependency] = []
if scope_resolver:
child_scopes = [st.scope for st in subtasks]
scope = scope_resolver(dependency, child_scopes, tuple(scope_idxs.keys()))
@@ -178,7 +178,7 @@ def build_task(
return tasks[dependency.cache_key]
task = Task(
- dependant=dependency,
+ dependent=dependency,
scope=scope,
call=call,
cache_key=dependency.cache_key,
@@ -187,7 +187,7 @@ def build_task(
keyword_parameters=keyword_parameters,
use_cache=dependency.use_cache,
)
- dependant_dag[dependency] = dep_params
+ dependent_dag[dependency] = dep_params
tasks[dependency.cache_key] = task
task_dag[task] = subtasks
check_task_scope_validity(
@@ -202,14 +202,14 @@ def build_task(
def solve(
- dependency: DependantBase[T],
+ dependency: DependentBase[T],
scopes: Sequence[Scope],
binds: Iterable[BindHook],
scope_resolver: Optional[ScopeResolver],
-) -> SolvedDependant[T]:
+) -> SolvedDependent[T]:
"""Solve a dependency.
- Returns a SolvedDependant that can be executed to get the dependency's value.
+ Returns a SolvedDependent that can be executed to get the dependency's value.
"""
# If the dependency itself is a bind, replace it
for hook in binds:
@@ -218,10 +218,10 @@ def solve(
dependency = match
if dependency.call is None: # pragma: no cover
- raise ValueError("DependantBase.call must not be None")
+ raise ValueError("DependentBase.call must not be None")
task_dag: "Dict[Task, List[Task]]" = {}
- dep_dag: "Dict[DependantBase[Any], List[DependencyParameter]]" = {}
+ dep_dag: "Dict[DependentBase[Any], List[DependencyParameter]]" = {}
scope_idxs = dict((scope, idx) for idx, scope in enumerate(scopes))
# this is implemented recursively
@@ -233,7 +233,7 @@ def solve(
binds=binds,
tasks={},
task_dag=task_dag,
- dependant_dag=dep_dag,
+ dependent_dag=dep_dag,
# we use a dict to represent the path so that we can have
# both O(1) lookups, and an ordered mutable sequence (via dict keys)
# we simply ignore / don't use the dict values
@@ -246,13 +246,13 @@ def solve(
static_order = tuple(ts.copy().static_order())
ts.prepare()
assert dependency.call is not None
- container_cache = SolvedDependantCache(
+ container_cache = SolvedDependentCache(
root_task=root_task,
topological_sorter=ts,
static_order=static_order,
empty_results=[None] * len(task_dag),
)
- solved = SolvedDependant(
+ solved = SolvedDependent(
dependency=dependency,
dag=dep_dag,
container_cache=container_cache,
diff --git a/di/dependant/__init__.py b/di/dependant/__init__.py
deleted file mode 100644
index 3de4942b..00000000
--- a/di/dependant/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from di.dependant._dependant import Dependant, Marker
-from di.dependant._injectable_type import Injectable
-from di.dependant._joined import JoinedDependant
-
-__all__ = (
- "Marker",
- "Dependant",
- "JoinedDependant",
- "Injectable",
-)
diff --git a/di/dependant/_joined.py b/di/dependant/_joined.py
deleted file mode 100644
index e5408d88..00000000
--- a/di/dependant/_joined.py
+++ /dev/null
@@ -1,39 +0,0 @@
-from __future__ import annotations
-
-from typing import Any, Iterable, List, TypeVar
-
-from di.api.dependencies import CacheKey, DependantBase, DependencyParameter
-
-T = TypeVar("T")
-
-
-class JoinedDependant(DependantBase[T]):
- """A Dependant that aggregates other dependants without directly depending on them"""
-
- __slots__ = ("dependant", "siblings")
-
- def __init__(
- self,
- dependant: DependantBase[T],
- *,
- siblings: Iterable[DependantBase[Any]],
- ) -> None:
- self.call = dependant.call
- self.dependant = dependant
- self.siblings = siblings
- self.scope = dependant.scope
- self.use_cache = dependant.use_cache
-
- def get_dependencies(self) -> List[DependencyParameter]:
- """Get the dependencies of our main dependant and all siblings"""
- return [
- *self.dependant.get_dependencies(),
- *(DependencyParameter(dep, None) for dep in self.siblings),
- ]
-
- @property
- def cache_key(self) -> CacheKey:
- return (self.dependant.cache_key, tuple((s.cache_key for s in self.siblings)))
-
- def __repr__(self) -> str:
- return f"{self.__class__.__name__}(dependant={self.dependant}, siblings={self.siblings})"
diff --git a/di/dependent/__init__.py b/di/dependent/__init__.py
new file mode 100644
index 00000000..b23bdf88
--- /dev/null
+++ b/di/dependent/__init__.py
@@ -0,0 +1,10 @@
+from di.dependent._dependent import Dependent, Marker
+from di.dependent._injectable_type import Injectable
+from di.dependent._joined import JoinedDependent
+
+__all__ = (
+ "Marker",
+ "Dependent",
+ "JoinedDependent",
+ "Injectable",
+)
diff --git a/di/dependant/_dependant.py b/di/dependent/_dependent.py
similarity index 91%
rename from di/dependant/_dependant.py
rename to di/dependent/_dependent.py
index 257f2948..6168738c 100644
--- a/di/dependant/_dependant.py
+++ b/di/dependent/_dependent.py
@@ -6,8 +6,8 @@
from di._utils.inspect import get_parameters, get_type
from di.api.dependencies import (
CacheKey,
- DependantBase,
DependencyParameter,
+ DependentBase,
InjectableClassProvider,
)
from di.api.providers import (
@@ -76,13 +76,13 @@ def __init__(
self.use_cache = use_cache
self.wire = wire
- def register_parameter(self, param: inspect.Parameter) -> DependantBase[Any]:
- """Hook to register the parameter this Dependant corresponds to.
+ def register_parameter(self, param: inspect.Parameter) -> DependentBase[Any]:
+ """Hook to register the parameter this Dependent corresponds to.
This can be used to inferr self.call from a type annotation (autowiring),
or to just register the type annotation.
- This method can return the same or a new instance of a Dependant to avoid modifying itself.
+ This method can return the same or a new instance of a Dependent to avoid modifying itself.
"""
call = self.call
if call is None and param.default is not param.empty:
@@ -101,7 +101,7 @@ def inject_default_value() -> Any:
else:
# a class type, a callable class instance or a function
call = annotation_type_option.value
- return Dependant[Any](
+ return Dependent[Any](
call=call,
scope=self.scope,
use_cache=self.use_cache,
@@ -109,10 +109,10 @@ def inject_default_value() -> Any:
)
-class Dependant(DependantBase[T]):
+class Dependent(DependentBase[T]):
"""Connect dependencies together.
- A `Dependant` can have sub-dependencies (also `Dependant`s).
+ A `Dependent` can have sub-dependencies (also `Dependent`s).
The first argument is a `Callable`, which is used to find the
sub-dependencies.
@@ -203,18 +203,18 @@ def get_dependencies(self) -> List[DependencyParameter]:
return []
res: "List[DependencyParameter]" = []
for param in get_parameters(self.call).values():
- sub_dependant: DependantBase[Any]
+ sub_dependent: DependentBase[Any]
if param.kind in _VARIABLE_PARAMETER_KINDS:
continue
else:
- maybe_sub_dependant_marker = next(
+ maybe_sub_dependent_marker = next(
get_markers_from_annotation(param.annotation, Marker), None
)
- if maybe_sub_dependant_marker is not None:
- sub_dependant = maybe_sub_dependant_marker.register_parameter(param)
+ if maybe_sub_dependent_marker is not None:
+ sub_dependent = maybe_sub_dependent_marker.register_parameter(param)
else:
- sub_dependant = self.get_default_marker().register_parameter(param)
- res.append(DependencyParameter(dependency=sub_dependant, parameter=param))
+ sub_dependent = self.get_default_marker().register_parameter(param)
+ res.append(DependencyParameter(dependency=sub_dependent, parameter=param))
return res
def get_default_marker(self) -> Marker:
diff --git a/di/dependant/_injectable_type.py b/di/dependent/_injectable_type.py
similarity index 62%
rename from di/dependant/_injectable_type.py
rename to di/dependent/_injectable_type.py
index 0aa60ac6..00ed452c 100644
--- a/di/dependant/_injectable_type.py
+++ b/di/dependent/_injectable_type.py
@@ -3,7 +3,7 @@
from di.api.providers import DependencyProvider
from di.api.scopes import Scope
-from di.dependant._dependant import Dependant
+from di.dependent._dependent import Dependent
class Injectable:
@@ -18,7 +18,7 @@ def __init_subclass__(
) -> None:
super().__init_subclass__(**kwargs)
- def create_dependant(cls_: Any, param: inspect.Parameter) -> Dependant[Any]:
- return Dependant(call or cls_, scope=scope, use_cache=use_cache)
+ def create_dependent(cls_: Any, param: inspect.Parameter) -> Dependent[Any]:
+ return Dependent(call or cls_, scope=scope, use_cache=use_cache)
- cls.__di_dependency__ = classmethod(create_dependant) # type: ignore
+ cls.__di_dependency__ = classmethod(create_dependent) # type: ignore
diff --git a/di/dependent/_joined.py b/di/dependent/_joined.py
new file mode 100644
index 00000000..b2a2ae32
--- /dev/null
+++ b/di/dependent/_joined.py
@@ -0,0 +1,39 @@
+from __future__ import annotations
+
+from typing import Any, Iterable, List, TypeVar
+
+from di.api.dependencies import CacheKey, DependencyParameter, DependentBase
+
+T = TypeVar("T")
+
+
+class JoinedDependent(DependentBase[T]):
+ """A Dependent that aggregates other dependents without directly depending on them"""
+
+ __slots__ = ("dependent", "siblings")
+
+ def __init__(
+ self,
+ dependent: DependentBase[T],
+ *,
+ siblings: Iterable[DependentBase[Any]],
+ ) -> None:
+ self.call = dependent.call
+ self.dependent = dependent
+ self.siblings = siblings
+ self.scope = dependent.scope
+ self.use_cache = dependent.use_cache
+
+ def get_dependencies(self) -> List[DependencyParameter]:
+ """Get the dependencies of our main dependent and all siblings"""
+ return [
+ *self.dependent.get_dependencies(),
+ *(DependencyParameter(dep, None) for dep in self.siblings),
+ ]
+
+ @property
+ def cache_key(self) -> CacheKey:
+ return (self.dependent.cache_key, tuple((s.cache_key for s in self.siblings)))
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(dependent={self.dependent}, siblings={self.siblings})"
diff --git a/di/exceptions.py b/di/exceptions.py
index 504b7155..9b456240 100644
--- a/di/exceptions.py
+++ b/di/exceptions.py
@@ -1,6 +1,6 @@
from typing import Any, List
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
class DependencyInjectionException(Exception):
@@ -12,7 +12,7 @@ class DependencyInjectionException(Exception):
class WiringError(DependencyInjectionException):
"""Raised when wiring (introspection into types) failed"""
- def __init__(self, msg: str, path: List[DependantBase[Any]]) -> None:
+ def __init__(self, msg: str, path: List[DependentBase[Any]]) -> None:
super().__init__(msg)
self.path = path
@@ -28,7 +28,7 @@ class DuplicateScopeError(DependencyInjectionException):
class DependencyCycleError(DependencyInjectionException):
"""Raised when a dependency cycle is detected"""
- def __init__(self, msg: str, path: List[DependantBase[Any]]) -> None:
+ def __init__(self, msg: str, path: List[DependentBase[Any]]) -> None:
super().__init__(msg)
self.path = path
@@ -43,7 +43,7 @@ class ScopeViolationError(DependencyInjectionException):
class SolvingError(DependencyInjectionException):
"""Raised when there is an issue solving, for example if a dependency appears twice with different scopes"""
- def __init__(self, msg: str, path: List[DependantBase[Any]]) -> None:
+ def __init__(self, msg: str, path: List[DependentBase[Any]]) -> None:
super().__init__(msg)
self.path = path
diff --git a/di/typing.py b/di/typing.py
index 83507b02..97962d13 100644
--- a/di/typing.py
+++ b/di/typing.py
@@ -17,7 +17,7 @@
def get_markers_from_annotation(
annotation: type, marker_cls: Type[T]
) -> Generator[T, None, None]:
- """Infer a sub-dependant from a parameter of this Dependant's .call
+ """Infer a sub-dependent from a parameter of this Dependent's .call
In the case of multiple markers in PEP 593 Annotated or nested use of Annotated
(which are equivalent and get flattened by Annoated itself) we return markers from
@@ -25,7 +25,7 @@ def get_markers_from_annotation(
"""
if get_origin(annotation) is Annotated:
# reverse the arguments so that in the case of
- # Annotated[Annotated[T, InnerDependant()], OuterDependant()]
+ # Annotated[Annotated[T, InnerDependent()], OuterDependent()]
# we discover "outer" first
# This is a somewhat arbitrary choice, but it is the convention we'll go with
# See https://www.python.org/dev/peps/pep-0593/#id18 for more details
diff --git a/docs/architecture.md b/docs/architecture.md
index 753a509d..5bd21ff6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -8,13 +8,13 @@ The fundamental design principle of `di` is to split up the complexity of depend
We map these responsibilities to well-defined classes/interfaces:
-- Wiring: this is handled by [Dependant]
+- Wiring: this is handled by [Dependent]
- Solving: this is handled by [Container]
- Execution: this is handled by [Executor]s
There are also some auxiliary support classes:
-- [SolvedDependant] holds a reference of the result of solving (an executable DAG) that can then be executed at a later time.
+- [SolvedDependent] holds a reference of the result of solving (an executable DAG) that can then be executed at a later time.
Fundamentally, our class diagram looks like this:
@@ -25,17 +25,17 @@ Fundamentally, our class diagram looks like this:
``` mermaid
classDiagram
- SolvedDependant "1..n" --o Dependant: aggregates into a DAG
- Container --> Dependant: visits sub-dependencies
+ SolvedDependent "1..n" --o Dependent: aggregates into a DAG
+ Container --> Dependent: visits sub-dependencies
Container --> Executor: delegates execution
- Container --> SolvedDependant: stores solved DAG
- Container --> SolvedDependant: executes solved DAG
- class Dependant{
- +get_dependencies() list~Dependant~
- +register_parameter() Dependant
+ Container --> SolvedDependent: stores solved DAG
+ Container --> SolvedDependent: executes solved DAG
+ class Dependent{
+ +get_dependencies() list~Dependent~
+ +register_parameter() Dependent
}
- class SolvedDependant{
- +dag Mapping~Dependant, SetOfDependant~
+ class SolvedDependent{
+ +dag Mapping~Dependent, SetOfDependent~
}
class Executor{
+execute()
@@ -43,13 +43,13 @@ classDiagram
class Container{
+bind()
+enter_scope(Scope) Container
- +solve(Dependant) SolvedDependant
- +execute(SolvedDependant, Executor) Result
+ +solve(Dependent) SolvedDependent
+ +execute(SolvedDependent, Executor) Result
}
```
-[Dependant]: https://github.com/adriangb/di/blob/main/di/api/dependencies.py
+[Dependent]: https://github.com/adriangb/di/blob/main/di/api/dependencies.py
[Container]: https://github.com/adriangb/di/blob/main/di/api/container.py
[Executor]: https://github.com/adriangb/di/blob/main/di/api/executor.py
-[SolvedDependant]: https://github.com/adriangb/di/blob/main/di/api/solved.py
+[SolvedDependent]: https://github.com/adriangb/di/blob/main/di/api/solved.py
diff --git a/docs/autowiring.py b/docs/autowiring.py
index 03e4fb1f..21093100 100644
--- a/docs/autowiring.py
+++ b/docs/autowiring.py
@@ -1,7 +1,7 @@
import os
from dataclasses import dataclass, field
-from di import AsyncExecutor, Container, Dependant
+from di import AsyncExecutor, Container, Dependent
@dataclass
@@ -20,6 +20,6 @@ async def endpoint(conn: DBConn) -> None:
async def framework():
container = Container()
- solved = container.solve(Dependant(endpoint, scope="request"), scopes=["request"])
+ solved = container.solve(Dependent(endpoint, scope="request"), scopes=["request"])
async with container.enter_scope("request") as state:
await container.execute_async(solved, executor=AsyncExecutor(), state=state)
diff --git a/docs/binds.md b/docs/binds.md
index 3c6ed954..4ad8b51a 100644
--- a/docs/binds.md
+++ b/docs/binds.md
@@ -8,7 +8,7 @@ Provider binding serves two important functions:
Every bind in `di` consists of:
- A target callable: this can be a function, an interface / protocol or a concrete class
-- A substitute dependency: an object implementing the `DependantBase`, usually just an instance of `Dependant`
+- A substitute dependency: an object implementing the `DependentBase`, usually just an instance of `Dependent`
This means that binds are themselves dependencies:
@@ -22,7 +22,7 @@ Binds can be used as a direct function call, in which case they are permanent, o
## Bind hooks
-Binding is implemented as hooks / callbacks: when we solve a dependency graph, every hook is called with every dependant and if the hook "matches" the dependent it returns the substitute dependency (otherwise it just returns `None`).
+Binding is implemented as hooks / callbacks: when we solve a dependency graph, every hook is called with every dependent and if the hook "matches" the dependent it returns the substitute dependency (otherwise it just returns `None`).
This means you can implement any sort of matching you want, including:
diff --git a/docs/cache.md b/docs/cache.md
index 8d655e09..6fffb145 100644
--- a/docs/cache.md
+++ b/docs/cache.md
@@ -6,9 +6,9 @@ To avoid re-computing the shared dependency, `di` will cache shared dependencies
## How caching works
-Dependencies are cached by their cache key, computed in `Dependant.cache_key`.
-See [dependants] for more information on `Dependant.cache_key`.
-Dependencies are cached by default, but this behavior can be changed on a per-dependency basis using the `use_cache=False` parameter to `Dependant`.
+Dependencies are cached by their cache key, computed in `Dependent.cache_key`.
+See [dependents] for more information on `Dependent.cache_key`.
+Dependencies are cached by default, but this behavior can be changed on a per-dependency basis using the `use_cache=False` parameter to `Dependent`.
```Python hl_lines="10-15"
--8<-- "docs_src/sharing.py"
@@ -19,4 +19,4 @@ Dependencies are cached by default, but this behavior can be changed on a per-de
Dependencies are cached within their scope and any inner scopes.
Once a dependency's scope exits, it's cached value is discarded and the next time the scope is entered a fresh value will be computed.
-[dependants]: dependants.md
+[dependents]: dependents.md
diff --git a/docs/dependants.md b/docs/dependants.md
index e45bee34..f3813b25 100644
--- a/docs/dependants.md
+++ b/docs/dependants.md
@@ -1,11 +1,11 @@
-# Dependants and the DependantBase
+# Dependents and the DependentBase
-Most of these docs use `Dependant` as the main marker for dependencies.
+Most of these docs use `Dependent` as the main marker for dependencies.
But the container doesn't actually know about either of these two things!
-In fact, the container only knows about the `DependantBase`, which you can find in `di.api.dependencies`.
-`Dependant` is just one possible implementation of the `DependantBase`.
+In fact, the container only knows about the `DependentBase`, which you can find in `di.api.dependencies`.
+`Dependent` is just one possible implementation of the `DependentBase`.
-You can easily build your own version of `Dependant` by inheriting from `Dependant` or `DependantBase`.
+You can easily build your own version of `Dependent` by inheriting from `Dependent` or `DependentBase`.
Here is an example that extracts headers from requests:
@@ -13,14 +13,14 @@ Here is an example that extracts headers from requests:
--8<-- "docs_src/headers_example.py"
```
-Another good example of the flexibility provided by `DependantBase` is the implementation of [JointDependant], which lets you schedule and execute dependencies together even if they are not directly connected by wiring:
+Another good example of the flexibility provided by `DependentBase` is the implementation of [JointDependent], which lets you schedule and execute dependencies together even if they are not directly connected by wiring:
```python
---8<-- "docs_src/joined_dependant.py"
+--8<-- "docs_src/joined_dependent.py"
```
Here `B` is executed even though `A` does not depend on it.
-This is because `JoinedDependant` leverages the `DependantBase` interface to tell `di` that `B` is a dependency of `A` even if `B` is not a parameter or otherwise related to `A`.
+This is because `JoinedDependent` leverages the `DependentBase` interface to tell `di` that `B` is a dependency of `A` even if `B` is not a parameter or otherwise related to `A`.
[Solving docs]: solving.md
-[JointDependant]: https://github.com/adriangb/di/blob/b7398fbdf30213c1acb94b423bb4f2e2badd0fdd/di/dependant.py#L194-L218
+[JointDependent]: https://github.com/adriangb/di/blob/b7398fbdf30213c1acb94b423bb4f2e2badd0fdd/di/dependent.py#L194-L218
diff --git a/docs/scopes.md b/docs/scopes.md
index 209b9b97..2a032483 100644
--- a/docs/scopes.md
+++ b/docs/scopes.md
@@ -38,7 +38,7 @@ In Pytest, a `"session"` scoped fixture cannot depend on a `"function"` scoped f
You may encounter situations where you don't want to make your users explicitly set the scope for each dependency.
For example, Spring defaults dependencies to the "singleton" scope.
-Our approach is to give you a callback that gets information on the current context (the scopes passed to `Container.solve`, the current `DependantBase` and the scopes of all of it's sub-dependencies) where you can inject your own logic for determining the right scope.
+Our approach is to give you a callback that gets information on the current context (the scopes passed to `Container.solve`, the current `DependentBase` and the scopes of all of it's sub-dependencies) where you can inject your own logic for determining the right scope.
Some examples of this include:
- A fixed default scope. You ignore all of the inputs and return a fixed value. This allows you to emulate Spring's behavior by returning a "singleton" scope or FastAPI's behavior by returning a "connection"/"request" scope.
diff --git a/docs/solving.md b/docs/solving.md
index 7efd5535..c3e67f52 100644
--- a/docs/solving.md
+++ b/docs/solving.md
@@ -4,16 +4,16 @@ Solving a dependency means build a directed acyclic graph (DAG) of dependencies
Once we solve a dependency, we can execute it without doing any introspection.
Solving is done by the **Container**.
-The result of solving is stored in a `SolvedDependant` object which you can pass to `Container.execute_{sync,async}` to get back the result.
+The result of solving is stored in a `SolvedDependent` object which you can pass to `Container.execute_{sync,async}` to get back the result.
The simplest form of executing a dependency is thus:
```python
-result = container.execute(container.solve(Dependant(lambda: 1)))
+result = container.execute(container.solve(Dependent(lambda: 1)))
```
For a more comprehensive overview, see the [architecture] section.
-## SolvedDependant
+## SolvedDependent
`di` lets you pre-solve your dependencies so that you don't have to run the solver each time you execute.
This usually comes with a huge performance boost, but only works if you have a static dependency graph.
@@ -25,31 +25,31 @@ For example, here is a more advanced use case where the framework solves the end
This means that `di` does *not* do any reflection for each request, nor does it have to do dependency resolution.
```Python hl_lines="13-15 18-20"
---8<-- "docs_src/solved_dependant.py"
+--8<-- "docs_src/solved_dependent.py"
```
## Getting a list of dependencies
-You can easily list all dependencies in a dag via `SolvedDependant.dag.keys()`.
+You can easily list all dependencies in a dag via `SolvedDependent.dag.keys()`.
```Python hl_lines="22"
---8<-- "docs_src/solved_dependant.py"
+--8<-- "docs_src/solved_dependent.py"
```
-This lists all of the *Dependants* for the solved dependency.
+This lists all of the *Dependents* for the solved dependency.
This means that you can create custom markers and easily enumerate them.
For example, you might make a `Header` dependency and then want to know what headers are being requested by the controller, even if they are nested inside other dependencies:
```python
-from di import Dependant
+from di import Dependent
-class Header(Dependant[str]):
+class Header(Dependent[str]):
...
```
-See the [dependants] section for a more complete example of this.
+See the [dependents] section for a more complete example of this.
[architecture]: architecture.md
[Performance section of the Wiring docs]: wiring.md#performance
-[dependants]: dependants.md
+[dependents]: dependents.md
diff --git a/docs/wiring.md b/docs/wiring.md
index c2779fd6..a8b39aad 100644
--- a/docs/wiring.md
+++ b/docs/wiring.md
@@ -2,14 +2,14 @@
Wiring is the act of "connecting" together dependencies.
-In `di`, wiring is handled by the `Dependant` API.
-The general idea is that `Container` accepts a `Dependant` and then asks it for it's sub-dependencies.
-These sub-dependencies are themselves `Dependant`s, and so the `Container` keeps asking them for _their_ sub-dependenices until there are none.
-
-But how does `Dependant` know what it's dependencies are?
-Every `Dependant` has a `call` attribute which is a callable (a class, a function, etc.) that which can be introspected (usually with `inpsect.signature`) to find it's parameters.
-The from these parameters the `Dependant` determine's what it's dependencies are.
-But how do we go from a parameter `param: Foo` to a `Dependant`?
+In `di`, wiring is handled by the `Dependent` API.
+The general idea is that `Container` accepts a `Dependent` and then asks it for it's sub-dependencies.
+These sub-dependencies are themselves `Dependent`s, and so the `Container` keeps asking them for _their_ sub-dependenices until there are none.
+
+But how does `Dependent` know what it's dependencies are?
+Every `Dependent` has a `call` attribute which is a callable (a class, a function, etc.) that which can be introspected (usually with `inpsect.signature`) to find it's parameters.
+The from these parameters the `Dependent` determine's what it's dependencies are.
+But how do we go from a parameter `param: Foo` to a `Dependent`?
There are actually several different mechanisms available:
## Autowiring
@@ -38,16 +38,16 @@ So metadata is just inherited from the parent dependency: in the example above,
## Dependency markers
-Dependency markers, in the form of `di.dependant.Marker` serve to hold information about a dependency, for example how to construct it or it's scope.
+Dependency markers, in the form of `di.dependent.Marker` serve to hold information about a dependency, for example how to construct it or it's scope.
Markers are generally useful when:
-- Injecting a non-identifiabletype, like a `list[str]`
+- Injecting a non-identifiable type, like a `list[str]`
- Injecting the result of a function (`param: some_function` is not valid in Python)
- The type being injected is not well-behaved and you need to tell `di` how to construct it
- You want to attach metadata to the target (like explicitly setting the `scope`)
-Let's take our previous example and look at how we would have used markers if `DBConn` accepted a `host: str` paramter instead of our `Config` class directly:
+Let's take our previous example and look at how we would have used markers if `DBConn` accepted a `host: str` parameter instead of our `Config` class directly:
```Python
--8<-- "docs_src/markers.py"
@@ -94,7 +94,7 @@ This means that while `Annotated` can sometimes be verbose, it can also be made
If you are writing and injecting your own classes, you also have the option of putting the dependency injection metadata into the class itself, via the `__di_dependency__(cls) -> Marker` protocol. This obviously doesn't work if you are injecting a 3rd party class you are importing (unless you subclass it).
-The main advantage of this method is that the consumers of this class (wich may be your own codebase) don't have to apply markers everywhere or worry about inconsistent scopes (see [scopes]).
+The main advantage of this method is that the consumers of this class (which may be your own codebase) don't have to apply markers everywhere or worry about inconsistent scopes (see [scopes]).
For example, we can tell `di` constructing a class asynchronously`:
@@ -121,7 +121,7 @@ For example, you may only want to have one `UserRepo` for you entire app:
### InjectableClass
-As a convenience, `di` provides an `InjectableClass` type that you can inherit from so that you can easily pass parameters to `Marker` without implementing `__di_dependant__`:
+As a convenience, `di` provides an `InjectableClass` type that you can inherit from so that you can easily pass parameters to `Marker` without implementing `__di_dependent__`:
```Python
--8<-- "docs_src/injectable_class.py"
@@ -136,14 +136,14 @@ They can be used with any of the methods described above.
Reflection (inspecting function signatures for dependencies) _is very slow_.
For this reason, `di` tries to avoid it as much as possible.
-The best way to avoid extra introspection is to re-use [Solved Dependants].
+The best way to avoid extra introspection is to re-use [Solved Dependents].
## Conclusion
There are several ways to declare dependencies in `di`.
Which one makes sense for each use case depends on several factors, but ultimately they all achieve the same outcome.
-[Solved Dependants]: solving.md#SolvedDependant
+[Solved Dependents]: solving.md#SolvedDependent
[binds]: binds.md
[PEP 593's Annotated]: https://www.python.org/dev/peps/pep-0593/
[typing_extensions backport]: https://pypi.org/project/typing-extensions/
diff --git a/docs_src/async_constructor.py b/docs_src/async_constructor.py
index 3967ed64..138698cc 100644
--- a/docs_src/async_constructor.py
+++ b/docs_src/async_constructor.py
@@ -2,7 +2,7 @@
from dataclasses import dataclass
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import AsyncExecutor
@@ -15,13 +15,13 @@ class B:
msg: str
@classmethod
- def __di_dependency__(cls, param: inspect.Parameter) -> "Dependant[B]":
+ def __di_dependency__(cls, param: inspect.Parameter) -> "Dependent[B]":
# note that client is injected by di!
async def func(client: HTTPClient) -> B:
- # do an http rquest or something
+ # do an http request or something
return B(msg=f"👋 from {param.name}")
- return Dependant(func)
+ return Dependent(func)
async def main() -> None:
@@ -30,7 +30,7 @@ def endpoint(b: B) -> str:
container = Container()
executor = AsyncExecutor()
- solved = container.solve(Dependant(endpoint), scopes=(None,))
+ solved = container.solve(Dependent(endpoint), scopes=(None,))
async with container.enter_scope(None) as state:
res = await container.execute_async(solved, executor=executor, state=state)
assert res == "👋 from b"
diff --git a/docs_src/async_init_dependency.py b/docs_src/async_init_dependency.py
index e8c24103..5739dc23 100644
--- a/docs_src/async_init_dependency.py
+++ b/docs_src/async_init_dependency.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import AsyncExecutor
from di.typing import Annotated
@@ -22,7 +22,7 @@ def endpoint(b: B) -> str:
container = Container()
executor = AsyncExecutor()
- solved = container.solve(Dependant(endpoint), scopes=(None,))
+ solved = container.solve(Dependent(endpoint), scopes=(None,))
async with container.enter_scope(None) as state:
res = await container.execute_async(solved, executor=executor, state=state)
assert res == "👋"
diff --git a/docs_src/autowiring.py b/docs_src/autowiring.py
index 0b6c7a35..f5fabf3e 100644
--- a/docs_src/autowiring.py
+++ b/docs_src/autowiring.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import AsyncExecutor
@@ -21,6 +21,6 @@ async def endpoint(conn: DBConn) -> None:
async def framework():
container = Container()
- solved = container.solve(Dependant(endpoint, scope="request"), scopes=["request"])
+ solved = container.solve(Dependent(endpoint, scope="request"), scopes=["request"])
async with container.enter_scope("request") as state:
await container.execute_async(solved, executor=AsyncExecutor(), state=state)
diff --git a/docs_src/bind_as_a_dep.py b/docs_src/bind_as_a_dep.py
index 5f0fe1f1..9912a8ad 100644
--- a/docs_src/bind_as_a_dep.py
+++ b/docs_src/bind_as_a_dep.py
@@ -7,7 +7,7 @@
from typing import Protocol
from di.container import Container, bind_by_type
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import AsyncExecutor
@@ -35,8 +35,8 @@ async def execute(self, sql: str) -> None:
async def framework() -> None:
container = Container()
- container.bind(bind_by_type(Dependant(Postgres, scope="request"), DBProtocol))
- solved = container.solve(Dependant(controller, scope="request"), scopes=["request"])
+ container.bind(bind_by_type(Dependent(Postgres, scope="request"), DBProtocol))
+ solved = container.solve(Dependent(controller, scope="request"), scopes=["request"])
# this next line would fail without the bind
async with container.enter_scope("request") as state:
await container.execute_async(solved, executor=AsyncExecutor(), state=state)
@@ -44,7 +44,7 @@ async def framework() -> None:
# by requesting the instance directly
async with container.enter_scope("request") as state:
db = await container.execute_async(
- container.solve(Dependant(DBProtocol), scopes=["request"]),
+ container.solve(Dependent(DBProtocol), scopes=["request"]),
executor=AsyncExecutor(),
state=state,
)
diff --git a/docs_src/bind_hooks.py b/docs_src/bind_hooks.py
index 6d25a85f..f5d62b62 100644
--- a/docs_src/bind_hooks.py
+++ b/docs_src/bind_hooks.py
@@ -2,9 +2,9 @@
import typing
from dataclasses import dataclass
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -14,10 +14,10 @@ class Foo:
def match_by_parameter_name(
- param: typing.Optional[inspect.Parameter], dependant: DependantBase[typing.Any]
-) -> typing.Optional[DependantBase[typing.Any]]:
+ param: typing.Optional[inspect.Parameter], dependent: DependentBase[typing.Any]
+) -> typing.Optional[DependentBase[typing.Any]]:
if param is not None and param.name == "bar":
- return Dependant(lambda: "baz", scope=None)
+ return Dependent(lambda: "baz", scope=None)
return None
@@ -25,7 +25,7 @@ def match_by_parameter_name(
container.bind(match_by_parameter_name)
-solved = container.solve(Dependant(Foo, scope=None), scopes=[None])
+solved = container.solve(Dependent(Foo, scope=None), scopes=[None])
def main():
diff --git a/docs_src/default_scope.py b/docs_src/default_scope.py
index 405cccc7..2c7ccb38 100644
--- a/docs_src/default_scope.py
+++ b/docs_src/default_scope.py
@@ -1,10 +1,10 @@
import os
from typing import Any, Sequence
-from di.api.dependencies import DependantBase
+from di.api.dependencies import DependentBase
from di.api.scopes import Scope
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import AsyncExecutor
from di.typing import Annotated
@@ -18,13 +18,13 @@ def __init__(self, domain: str) -> None:
async def web_framework() -> None:
container = Container()
container.bind(
- lambda param, dependant: Dependant(Request, scope="request", wire=False)
- if dependant.call is Request
+ lambda param, dependent: Dependent(Request, scope="request", wire=False)
+ if dependent.call is Request
else None
)
def scope_resolver(
- dep: DependantBase[Any],
+ dep: DependentBase[Any],
subdep_scopes: Sequence[Scope],
scopes: Sequence[Scope],
) -> Scope:
@@ -33,7 +33,7 @@ def scope_resolver(
return dep.scope
solved = container.solve(
- Dependant(controller, scope="request"),
+ Dependent(controller, scope="request"),
scopes=["singleton", "request"],
scope_resolver=scope_resolver,
)
diff --git a/docs_src/headers_example.py b/docs_src/headers_example.py
index 8b6bc4fe..ec8bb677 100644
--- a/docs_src/headers_example.py
+++ b/docs_src/headers_example.py
@@ -2,7 +2,7 @@
from typing import Mapping, Optional, TypeVar
from di.container import Container, bind_by_type
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import AsyncExecutor
from di.typing import Annotated
@@ -17,7 +17,7 @@ def __init__(self, alias: Optional[str]) -> None:
self.alias = alias
super().__init__(call=None, scope="request", use_cache=False)
- def register_parameter(self, param: inspect.Parameter) -> Dependant[str]:
+ def register_parameter(self, param: inspect.Parameter) -> Dependent[str]:
if self.alias is not None:
name = self.alias
else:
@@ -26,7 +26,7 @@ def register_parameter(self, param: inspect.Parameter) -> Dependant[str]:
def get_header(request: Annotated[Request, Marker()]) -> str:
return param.annotation(request.headers[name])
- return Dependant(get_header, scope="request")
+ return Dependent(get_header, scope="request")
T = TypeVar("T")
@@ -39,10 +39,10 @@ async def web_framework() -> None:
valid_request = Request(headers={"x-header-one": "one", "x-header-two": "2"})
with container.bind(
- bind_by_type(Dependant(lambda: valid_request, scope="request"), Request)
+ bind_by_type(Dependent(lambda: valid_request, scope="request"), Request)
):
solved = container.solve(
- Dependant(controller, scope="request"), scopes=["request"]
+ Dependent(controller, scope="request"), scopes=["request"]
)
with container.enter_scope("request") as state:
await container.execute_async(
@@ -51,10 +51,10 @@ async def web_framework() -> None:
invalid_request = Request(headers={"x-header-one": "one"})
with container.bind(
- bind_by_type(Dependant(lambda: invalid_request, scope="request"), Request)
+ bind_by_type(Dependent(lambda: invalid_request, scope="request"), Request)
):
solved = container.solve(
- Dependant(controller, scope="request"), scopes=["request"]
+ Dependent(controller, scope="request"), scopes=["request"]
)
with container.enter_scope("request") as state:
diff --git a/docs_src/injectable_class.py b/docs_src/injectable_class.py
index a9697aec..fdaa68cc 100644
--- a/docs_src/injectable_class.py
+++ b/docs_src/injectable_class.py
@@ -1,5 +1,5 @@
from di.container import Container
-from di.dependant import Dependant, Injectable
+from di.dependent import Dependent, Injectable
from di.executors import SyncExecutor
@@ -14,7 +14,7 @@ def endpoint(repo: UsersRepo) -> UsersRepo:
def framework():
container = Container()
solved = container.solve(
- Dependant(endpoint, scope="request"), scopes=["app", "request"]
+ Dependent(endpoint, scope="request"), scopes=["app", "request"]
)
executor = SyncExecutor()
with container.enter_scope("app") as app_state:
diff --git a/docs_src/invalid_scope_dependance.py b/docs_src/invalid_scope_dependence.py
similarity index 79%
rename from docs_src/invalid_scope_dependance.py
rename to docs_src/invalid_scope_dependence.py
index a8a83787..eefc23ac 100644
--- a/docs_src/invalid_scope_dependance.py
+++ b/docs_src/invalid_scope_dependence.py
@@ -1,5 +1,5 @@
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.typing import Annotated
@@ -24,4 +24,4 @@ def controller(conn: DBConnDep) -> None:
def framework() -> None:
container = Container()
- container.solve(Dependant(controller, scope="request"), scopes=["app", "request"])
+ container.solve(Dependent(controller, scope="request"), scopes=["app", "request"])
diff --git a/docs_src/joined_dependant.py b/docs_src/joined_dependent.py
similarity index 63%
rename from docs_src/joined_dependant.py
rename to docs_src/joined_dependent.py
index ea09e044..4df8aa50 100644
--- a/docs_src/joined_dependant.py
+++ b/docs_src/joined_dependent.py
@@ -1,5 +1,5 @@
from di.container import Container
-from di.dependant import Dependant, JoinedDependant
+from di.dependent import Dependent, JoinedDependent
from di.executors import SyncExecutor
@@ -16,11 +16,11 @@ def __init__(self) -> None:
def main():
container = Container()
- dependant = JoinedDependant(
- Dependant(A, scope="request"),
- siblings=[Dependant(B, scope="request")],
+ dependent = JoinedDependent(
+ Dependent(A, scope="request"),
+ siblings=[Dependent(B, scope="request")],
)
- solved = container.solve(dependant, scopes=["request"])
+ solved = container.solve(dependent, scopes=["request"])
with container.enter_scope("request") as state:
a = container.execute_sync(solved, executor=SyncExecutor(), state=state)
assert isinstance(a, A)
diff --git a/docs_src/markers.py b/docs_src/markers.py
index 64062111..047785b5 100644
--- a/docs_src/markers.py
+++ b/docs_src/markers.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import SyncExecutor
from di.typing import Annotated
@@ -26,6 +26,6 @@ def endpoint(conn: Annotated[DBConn, Marker(inject_db, scope="request")]) -> Non
def framework():
container = Container()
- solved = container.solve(Dependant(endpoint, scope="request"), scopes=["request"])
+ solved = container.solve(Dependent(endpoint, scope="request"), scopes=["request"])
with container.enter_scope("request") as state:
container.execute_sync(solved, executor=SyncExecutor(), state=state)
diff --git a/docs_src/sharing.py b/docs_src/sharing.py
index e835f1a7..ed4730ba 100644
--- a/docs_src/sharing.py
+++ b/docs_src/sharing.py
@@ -1,13 +1,13 @@
from random import random
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import SyncExecutor
from di.typing import Annotated
def controller(
- # no marker is equivalent to Dependant(object)
+ # no marker is equivalent to Dependent(object)
v1: object,
# the default value is use_cache=True
v2: Annotated[object, Marker(object, scope="request")],
@@ -20,6 +20,6 @@ def controller(
def main() -> None:
container = Container()
- solved = container.solve(Dependant(controller, scope="request"), scopes=["request"])
+ solved = container.solve(Dependent(controller, scope="request"), scopes=["request"])
with container.enter_scope("request") as state:
container.execute_sync(solved, executor=SyncExecutor(), state=state)
diff --git a/docs_src/simple.py b/docs_src/simple.py
index 018a4e3d..f1705cae 100644
--- a/docs_src/simple.py
+++ b/docs_src/simple.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -21,7 +21,7 @@ class C:
def main():
container = Container()
- solved = container.solve(Dependant(C, scope="request"), scopes=["request"])
+ solved = container.solve(Dependent(C, scope="request"), scopes=["request"])
with container.enter_scope("request") as state:
c = container.execute_sync(solved, executor=SyncExecutor(), state=state)
assert isinstance(c, C)
diff --git a/docs_src/singleton.py b/docs_src/singleton.py
index 409bd649..ac85e4f2 100644
--- a/docs_src/singleton.py
+++ b/docs_src/singleton.py
@@ -1,14 +1,14 @@
import inspect
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
class UsersRepo:
@classmethod
- def __di_dependency__(cls, param: inspect.Parameter) -> "Dependant[UsersRepo]":
- return Dependant(UsersRepo, scope="app")
+ def __di_dependency__(cls, param: inspect.Parameter) -> "Dependent[UsersRepo]":
+ return Dependent(UsersRepo, scope="app")
def endpoint(repo: UsersRepo) -> UsersRepo:
@@ -18,7 +18,7 @@ def endpoint(repo: UsersRepo) -> UsersRepo:
def framework():
container = Container()
solved = container.solve(
- Dependant(endpoint, scope="request"), scopes=["app", "request"]
+ Dependent(endpoint, scope="request"), scopes=["app", "request"]
)
executor = SyncExecutor()
with container.enter_scope("app") as app_state:
diff --git a/docs_src/solved_dependant.py b/docs_src/solved_dependent.py
similarity index 63%
rename from docs_src/solved_dependant.py
rename to docs_src/solved_dependent.py
index ff59891b..59f3ff72 100644
--- a/docs_src/solved_dependant.py
+++ b/docs_src/solved_dependent.py
@@ -1,6 +1,6 @@
-from di.api.solved import SolvedDependant
+from di.api.solved import SolvedDependent
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -11,8 +11,8 @@ class Request:
def web_framework():
container = Container()
- solved = container.solve(Dependant(controller, scope="request"), scopes=["request"])
- assert isinstance(solved, SolvedDependant)
+ solved = container.solve(Dependent(controller, scope="request"), scopes=["request"])
+ assert isinstance(solved, SolvedDependent)
with container.enter_scope("request") as state:
container.execute_sync(
@@ -20,8 +20,8 @@ def web_framework():
)
dependencies = solved.dag.keys() - {solved.dependency}
- assert all(isinstance(item, Dependant) for item in dependencies)
- assert set(dependant.call for dependant in dependencies) == {Request, MyClass}
+ assert all(isinstance(item, Dependent) for item in dependencies)
+ assert set(dependent.call for dependent in dependencies) == {Request, MyClass}
# User code
diff --git a/docs_src/web_framework.py b/docs_src/web_framework.py
index 8aa3ac1e..45fa97d9 100644
--- a/docs_src/web_framework.py
+++ b/docs_src/web_framework.py
@@ -1,7 +1,7 @@
from typing import Any, Callable
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -15,7 +15,7 @@ class App:
def __init__(self, controller: Callable[..., Any]) -> None:
self.container = Container()
self.solved = self.container.solve(
- Dependant(controller, scope="request"),
+ Dependent(controller, scope="request"),
scopes=["request"],
)
self.executor = SyncExecutor()
diff --git a/mkdocs.yml b/mkdocs.yml
index 09bd350a..b8a6d111 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -34,7 +34,7 @@ nav:
- Wiring: wiring.md
- Scopes: scopes.md
- Registration and Binding: binds.md
- - Dependants: dependants.md
+ - Dependents: dependents.md
- Caching: cache.md
- Solving: solving.md
- Contributing: contributing.md
diff --git a/pyproject.toml b/pyproject.toml
index 4c9f3165..490d2adc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "di"
-version = "0.72.1"
+version = "0.73.0"
description = "Dependency injection toolkit"
authors = ["Adrian Garcia Badaracco "]
readme = "README.md"
diff --git a/tests/docs/test_joined_dependant.py b/tests/docs/test_joined_dependant.py
index 8d3235d7..637caafd 100644
--- a/tests/docs/test_joined_dependant.py
+++ b/tests/docs/test_joined_dependant.py
@@ -1,5 +1,5 @@
-from docs_src import joined_dependant
+from docs_src import joined_dependent
def test_bind_as_a_dep() -> None:
- joined_dependant.main()
+ joined_dependent.main()
diff --git a/tests/docs/test_scopes_example.py b/tests/docs/test_scopes_example.py
index ef4ecb0b..25a1ea1f 100644
--- a/tests/docs/test_scopes_example.py
+++ b/tests/docs/test_scopes_example.py
@@ -1,12 +1,12 @@
import pytest
from di.exceptions import ScopeViolationError
-from docs_src import default_scope, invalid_scope_dependance
+from docs_src import default_scope, invalid_scope_dependence
def test_invalid_scope_dependance() -> None:
with pytest.raises(ScopeViolationError):
- invalid_scope_dependance.framework()
+ invalid_scope_dependence.framework()
@pytest.mark.anyio
diff --git a/tests/docs/test_solved.py b/tests/docs/test_solved.py
index 81c4b441..f42e7e91 100644
--- a/tests/docs/test_solved.py
+++ b/tests/docs/test_solved.py
@@ -1,5 +1,5 @@
-from docs_src import solved_dependant
+from docs_src import solved_dependent
def test_solved() -> None:
- solved_dependant.web_framework()
+ solved_dependent.web_framework()
diff --git a/tests/test_binding.py b/tests/test_binding.py
index b7ac46b4..ebec48f2 100644
--- a/tests/test_binding.py
+++ b/tests/test_binding.py
@@ -3,7 +3,7 @@
import pytest
from di.container import Container, bind_by_type
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import SyncExecutor
from di.typing import Annotated
@@ -24,26 +24,26 @@ class Test:
def __init__(self, v: int = 1) -> None:
self.v = v
- dependant = Dependant(Test)
+ dependent = Dependent(Test)
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(dependant, scopes=[None]),
+ container.solve(dependent, scopes=[None]),
executor=SyncExecutor(),
state=state,
)
assert res.v == 1
- with container.bind(bind_by_type(Dependant(lambda: Test(2)), Test)):
+ with container.bind(bind_by_type(Dependent(lambda: Test(2)), Test)):
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(dependant, scopes=[None]),
+ container.solve(dependent, scopes=[None]),
executor=SyncExecutor(),
state=state,
)
assert res.v == 2
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(dependant, scopes=[None]),
+ container.solve(dependent, scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -70,7 +70,7 @@ def dep(t: Annotated[None, Marker(Transitive)]) -> None:
# we get an error from raises_exception
with pytest.raises(ValueError):
container.execute_sync(
- container.solve(Dependant(dep), scopes=[None]),
+ container.solve(Dependent(dep), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -81,10 +81,10 @@ def dep(t: Annotated[None, Marker(Transitive)]) -> None:
def not_error() -> None:
...
- with container.bind(bind_by_type(Dependant(not_error), Transitive)):
+ with container.bind(bind_by_type(Dependent(not_error), Transitive)):
with container.enter_scope(None) as state:
container.execute_sync(
- container.solve(Dependant(dep), scopes=[None]),
+ container.solve(Dependent(dep), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -92,14 +92,14 @@ def not_error() -> None:
with container.enter_scope(None) as state:
with pytest.raises(ValueError):
container.execute_sync(
- container.solve(Dependant(dep), scopes=[None]),
+ container.solve(Dependent(dep), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
def test_bind_with_dependencies():
- """When we bind a new dependant, we resolve it's dependencies as well"""
+ """When we bind a new dependent, we resolve it's dependencies as well"""
def return_one() -> int:
return 1
@@ -117,19 +117,19 @@ def return_four(two: Annotated[int, Marker(return_two)]) -> int:
with container.enter_scope(None) as state:
assert (
container.execute_sync(
- container.solve(Dependant(return_four), scopes=[None]),
+ container.solve(Dependent(return_four), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
) == 4
container.bind(
- lambda param, dependant: None
- if dependant.call is not return_two
- else Dependant(return_three)
+ lambda param, dependent: None
+ if dependent.call is not return_two
+ else Dependent(return_three)
)
with container.enter_scope(None) as state:
val = container.execute_sync(
- container.solve(Dependant(return_four), scopes=[None]),
+ container.solve(Dependent(return_four), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -146,7 +146,7 @@ class Dog(Animal):
container = Container()
container.bind(
bind_by_type(
- Dependant(lambda: Dog()),
+ Dependent(lambda: Dog()),
Animal,
covariant=True,
)
@@ -157,7 +157,7 @@ class Dog(Animal):
def dep(animal: Animal, generic: Annotated[List[int], Marker(list)]) -> Animal:
return animal
- solved = container.solve(Dependant(dep), scopes=[None])
+ solved = container.solve(Dependent(dep), scopes=[None])
with container.enter_scope(None) as state:
instance = container.execute_sync(solved, executor=SyncExecutor(), state=state)
diff --git a/tests/test_caching.py b/tests/test_caching.py
index 5e2c8a60..c9f5e476 100644
--- a/tests/test_caching.py
+++ b/tests/test_caching.py
@@ -2,7 +2,7 @@
from typing import Any, Tuple
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import SyncExecutor
from di.typing import Annotated
@@ -15,7 +15,7 @@ def dep() -> int:
container = Container()
executor = SyncExecutor()
- solved = container.solve(Dependant(dep), scopes=[None])
+ solved = container.solve(Dependent(dep), scopes=[None])
with container.enter_scope(None) as state:
val = container.execute_sync(solved, executor=executor, state=state)
@@ -38,7 +38,7 @@ def dep() -> int:
container = Container()
executor = SyncExecutor()
- solved = container.solve(Dependant(dep, use_cache=False), scopes=[None])
+ solved = container.solve(Dependent(dep, use_cache=False), scopes=[None])
with container.enter_scope(None) as state:
val = container.execute_sync(solved, executor=executor, state=state)
@@ -61,7 +61,7 @@ def dep() -> int:
container = Container()
executor = SyncExecutor()
- solved = container.solve(Dependant(dep, scope="outer"), scopes=["outer", "inner"])
+ solved = container.solve(Dependent(dep, scope="outer"), scopes=["outer", "inner"])
with container.enter_scope("outer") as outer_state:
with container.enter_scope("inner", state=outer_state) as inner_state:
@@ -99,7 +99,7 @@ def dep() -> int:
container = Container()
executor = SyncExecutor()
solved = container.solve(
- Dependant(dep, scope="outer", use_cache=False), scopes=["outer", "inner"]
+ Dependent(dep, scope="outer", use_cache=False), scopes=["outer", "inner"]
)
with container.enter_scope("outer") as outer_state:
@@ -142,18 +142,18 @@ def dep(
container = Container()
executor = SyncExecutor()
- solved = container.solve(Dependant(dep), scopes=[None])
+ solved = container.solve(Dependent(dep), scopes=[None])
with container.enter_scope(None) as state:
one, two, three = container.execute_sync(solved, executor=executor, state=state)
assert one is three
assert two is not one
-def test_dependant_custom_cache_key() -> None:
+def test_dependent_custom_cache_key() -> None:
- # we make a dependant that does not care about the scope
+ # we make a dependent that does not care about the scope
# so a "request" scoped dependency will pick up cache from an "app" scoped one
- class CustomDependant(Dependant[Any]):
+ class CustomDependent(Dependent[Any]):
@property
def cache_key(self) -> Any:
return (self.__class__, self.call)
@@ -163,9 +163,9 @@ class State:
foo: str = "bar"
container = Container()
- app_scoped_state_dep = CustomDependant(State, scope="app")
+ app_scoped_state_dep = CustomDependent(State, scope="app")
app_scoped_state_solved = container.solve(app_scoped_state_dep, scopes=["app"])
- request_scoped_state_dep = CustomDependant(State, scope="request")
+ request_scoped_state_dep = CustomDependent(State, scope="request")
request_scoped_state_solved = container.solve(
request_scoped_state_dep, scopes=["app", "request"]
)
diff --git a/tests/test_dependant.py b/tests/test_dependant.py
index 5ac3b7e5..562ae612 100644
--- a/tests/test_dependant.py
+++ b/tests/test_dependant.py
@@ -2,7 +2,7 @@
import pytest
-from di.dependant import Dependant
+from di.dependent import Dependent
T = TypeVar("T")
@@ -15,29 +15,29 @@ def other_func() -> None:
...
-class DependantSubclass(Dependant[T]):
+class DependentSubclass(Dependent[T]):
...
@pytest.mark.parametrize(
"left,right,hash_eq,eq_qe",
[
- (Dependant(func), Dependant(func), True, True),
- (Dependant(func, use_cache=False), Dependant(func), False, False),
- (Dependant(func), Dependant(func, use_cache=False), False, False),
+ (Dependent(func), Dependent(func), True, True),
+ (Dependent(func, use_cache=False), Dependent(func), False, False),
+ (Dependent(func), Dependent(func, use_cache=False), False, False),
(
- Dependant(func, use_cache=False),
- Dependant(func, use_cache=False),
+ Dependent(func, use_cache=False),
+ Dependent(func, use_cache=False),
False,
False,
),
- (Dependant(func), DependantSubclass(func), False, False),
- (Dependant(func), Dependant(other_func), False, False),
- (Dependant(None), Dependant(None), False, False),
+ (Dependent(func), DependentSubclass(func), False, False),
+ (Dependent(func), Dependent(other_func), False, False),
+ (Dependent(None), Dependent(None), False, False),
],
)
def test_equality(
- left: Dependant[Any], right: Dependant[Any], hash_eq: bool, eq_qe: bool
+ left: Dependent[Any], right: Dependent[Any], hash_eq: bool, eq_qe: bool
):
assert (hash(left.cache_key) == hash(right.cache_key)) == hash_eq
assert (left.cache_key == right.cache_key) == eq_qe
diff --git a/tests/test_dependency_cycles.py b/tests/test_dependency_cycles.py
index 087bfe45..786627d0 100644
--- a/tests/test_dependency_cycles.py
+++ b/tests/test_dependency_cycles.py
@@ -2,7 +2,7 @@
import pytest
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.exceptions import DependencyCycleError
from di.typing import Annotated
@@ -21,4 +21,4 @@ def test_cycle() -> None:
container = Container()
with container.enter_scope(None):
with pytest.raises(DependencyCycleError, match="are in a cycle"):
- container.solve(Dependant(dep1), scopes=[None])
+ container.solve(Dependent(dep1), scopes=[None])
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
index 1c307763..1bc09696 100644
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -4,7 +4,7 @@
import pytest
from di.container import Container, bind_by_type
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import AsyncExecutor, SyncExecutor
from di.typing import Annotated
@@ -52,10 +52,10 @@ def collector(one: Annotated[None, Marker(dep1)]) -> None:
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
with container.enter_scope(None) as state:
container.execute_sync(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -69,8 +69,8 @@ def collector(one: Annotated[None, Marker(async_dep1)]) -> None:
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
- solved = container.solve(Dependant(collector), scopes=[None])
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
+ solved = container.solve(Dependent(collector), scopes=[None])
async with container.enter_scope(None) as state:
await container.execute_async(
solved,
@@ -88,15 +88,15 @@ def collector(
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
with container.enter_scope(None) as state:
container.execute_sync(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
# one of the dependencies catches and swallows the exception
- # so the other one nevers sees it
+ # so the other one never sees it
# there is no promises as to the order, both cases are valid
assert rec.caught == {"dep1": True} or rec.caught == {"dep2": True}
@@ -111,8 +111,8 @@ def collector(
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
- solved = container.solve(Dependant(collector), scopes=[None])
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
+ solved = container.solve(Dependent(collector), scopes=[None])
async with container.enter_scope(None) as state:
await container.execute_async(
solved,
@@ -135,15 +135,15 @@ def collector(
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
async with container.enter_scope(None) as state:
await container.execute_async(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=AsyncExecutor(),
state=state,
)
# one of the dependencies catches and swallows the exception
- # so the other one nevers sees it
+ # so the other one never sees it
# there is no promises as to the order, both cases are valid
assert rec.caught == {"async_dep1": True} or rec.caught == {"dep2": True}
@@ -186,11 +186,11 @@ def collector(one: Annotated[None, Marker(dep1_reraise)]) -> None:
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
try:
with container.enter_scope(None) as state:
container.execute_sync(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -210,11 +210,11 @@ def collector(one: Annotated[None, Marker(async_dep1_reraise)]) -> None:
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
try:
async with container.enter_scope(None) as state:
await container.execute_async(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=AsyncExecutor(),
state=state,
)
@@ -236,11 +236,11 @@ def collector(
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
try:
with container.enter_scope(None) as state:
container.execute_sync(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -263,11 +263,11 @@ def collector(
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
try:
async with container.enter_scope(None) as state:
await container.execute_async(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=AsyncExecutor(),
state=state,
)
@@ -290,11 +290,11 @@ def collector(
container = Container()
rec = Recorder()
- container.bind(bind_by_type(Dependant(lambda: rec), Recorder))
+ container.bind(bind_by_type(Dependent(lambda: rec), Recorder))
try:
async with container.enter_scope(None) as state:
await container.execute_async(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=AsyncExecutor(),
state=state,
)
@@ -328,7 +328,7 @@ def root(child: Annotated[None, Marker(parent)]) -> None:
container = Container()
with container.enter_scope(None) as state:
container.execute_sync(
- container.solve(Dependant(root), scopes=[None]),
+ container.solve(Dependent(root), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
diff --git a/tests/test_execute.py b/tests/test_execute.py
index f6179ac2..9f84da5b 100644
--- a/tests/test_execute.py
+++ b/tests/test_execute.py
@@ -14,7 +14,7 @@
from di.concurrency import as_async
from di.container import Container, ContainerState, bind_by_type
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.exceptions import IncompatibleDependencyError, UnknownScopeError
from di.executors import AsyncExecutor, ConcurrentAsyncExecutor, SyncExecutor
from di.typing import Annotated
@@ -86,7 +86,7 @@ def test_execute():
container = Container()
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(Dependant(v5), scopes=[None]),
+ container.solve(Dependent(v5), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -208,7 +208,7 @@ async def test_concurrency_async(dep1: Any, sync1: bool, dep2: Any, sync2: bool)
container = Container()
synchronizer = Synchronizer([anyio.Event(), anyio.Event()], anyio.Event())
- container.bind(bind_by_type(Dependant(lambda: synchronizer), Synchronizer))
+ container.bind(bind_by_type(Dependent(lambda: synchronizer), Synchronizer))
async def collector(
a: Annotated[None, Marker(dep1, use_cache=False)],
@@ -227,7 +227,7 @@ async def monitor() -> None:
async with container.enter_scope(None) as state:
tg.start_soon(monitor)
await container.execute_async(
- container.solve(Dependant(collector), scopes=[None]),
+ container.solve(Dependent(collector), scopes=[None]),
executor=ConcurrentAsyncExecutor(),
state=state,
)
@@ -262,7 +262,7 @@ async def dep2(
assert one == expected # replaced in results state
container = Container()
- solved = container.solve(Dependant(dep2), scopes=[None])
+ solved = container.solve(Dependent(dep2), scopes=[None])
async def execute_in_ctx(id: int) -> None:
ctx.set(id)
@@ -300,8 +300,8 @@ async def collect2(
objects.append(obj)
container = Container()
- solved1 = container.solve(Dependant(collect1), scopes=["app", None])
- solved2 = container.solve(Dependant(collect2), scopes=["app", None])
+ solved1 = container.solve(Dependent(collect1), scopes=["app", None])
+ solved2 = container.solve(Dependent(collect2), scopes=["app", None])
async def execute_1(state: ContainerState):
async with container.enter_scope(None, state=state) as state:
@@ -337,7 +337,7 @@ async def dep() -> AsyncGenerator[None, None]:
IncompatibleDependencyError, match="cannot be used in the sync scope"
):
await container.execute_async(
- container.solve(Dependant(dep, scope=None), scopes=[None]),
+ container.solve(Dependent(dep, scope=None), scopes=[None]),
executor=AsyncExecutor(),
state=state,
)
@@ -349,4 +349,4 @@ def bad_dep(v: Annotated[int, Marker(lambda: 1, scope="foo")]) -> int:
container = Container()
with pytest.raises(UnknownScopeError):
- container.solve(Dependant(bad_dep, scope="app"), scopes=["app"])
+ container.solve(Dependent(bad_dep, scope="app"), scopes=["app"])
diff --git a/tests/test_injectable_class.py b/tests/test_injectable_class.py
index f1eca34b..24d956eb 100644
--- a/tests/test_injectable_class.py
+++ b/tests/test_injectable_class.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from di.container import Container
-from di.dependant import Dependant, Injectable
+from di.dependent import Dependent, Injectable
from di.executors import SyncExecutor
@@ -14,7 +14,7 @@ def func(item: Bar) -> Bar:
return item
container = Container()
- dep = Dependant(func, scope="app")
+ dep = Dependent(func, scope="app")
solved = container.solve(dep, scopes=["app"])
assert next(iter(solved.dag[dep])).dependency.scope == "app"
@@ -29,7 +29,7 @@ def func(item: Bar) -> Bar:
return item
container = Container()
- dep = Dependant(func)
+ dep = Dependent(func)
solved = container.solve(dep, scopes=[None])
executor = SyncExecutor()
with container.enter_scope(None) as state:
diff --git a/tests/test_positional_only.py b/tests/test_positional_only.py
index 74ffb4b4..7864d648 100644
--- a/tests/test_positional_only.py
+++ b/tests/test_positional_only.py
@@ -3,7 +3,7 @@
import pytest
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -23,6 +23,6 @@ def func(one: Test) -> None:
exec(func_def, globals())
container = Container()
- solved = container.solve(Dependant(func), scopes=[None])
+ solved = container.solve(Dependent(func), scopes=[None])
with container.enter_scope(None) as state:
container.execute_sync(solved, executor=SyncExecutor(), state=state)
diff --git a/tests/test_scoping.py b/tests/test_scoping.py
index caf17350..68495ecb 100644
--- a/tests/test_scoping.py
+++ b/tests/test_scoping.py
@@ -4,7 +4,7 @@
import pytest
from di.container import Container
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.exceptions import DuplicateScopeError
from di.executors import SyncExecutor
from di.typing import Annotated
@@ -33,10 +33,10 @@ def not_use_cache(v: Annotated[int, Marker(dep1, scope="outer", use_cache=False)
def test_scoped_execute():
container = Container()
use_cache_solved = container.solve(
- Dependant(use_cache, scope="outer"), scopes=["outer", "inner"]
+ Dependent(use_cache, scope="outer"), scopes=["outer", "inner"]
)
not_use_cache_solved = container.solve(
- Dependant(not_use_cache, scope="outer"), scopes=["outer", "inner"]
+ Dependent(not_use_cache, scope="outer"), scopes=["outer", "inner"]
)
with container.enter_scope("outer") as outer_state:
dep1.value = 1
@@ -89,24 +89,24 @@ def A() -> str:
return holder[0]
MarkerA = Marker(A, scope="app")
- DepA = Dependant(A, scope="request")
+ DepA = Dependent(A, scope="request")
def B(a: Annotated[str, MarkerA]) -> str:
return a + holder[1]
MarkerB = Marker(B, scope="request")
- DepB = Dependant(B, scope="request")
+ DepB = Dependent(B, scope="request")
def C(b: Annotated[str, MarkerB]) -> str:
return b + holder[2]
MarkerC = Marker(C, scope="request")
- DepC = Dependant(C, scope="request")
+ DepC = Dependent(C, scope="request")
def endpoint(c: Annotated[str, MarkerC]) -> str:
return c
- DepEndpoint = Dependant(endpoint, scope="request")
+ DepEndpoint = Dependent(endpoint, scope="request")
container = Container()
scopes = ["app", "request", "endpoint"]
@@ -189,7 +189,7 @@ def endpoint(c: Annotated[None, Marker(C, scope="request")]) -> None:
container = Container()
solved = container.solve(
- Dependant(endpoint, scope="endpoint"),
+ Dependent(endpoint, scope="endpoint"),
scopes=["lifespan", "request", "endpoint"],
)
with container.enter_scope("lifespan") as app_state:
diff --git a/tests/test_solving.py b/tests/test_solving.py
index fec2ecf7..0fee1681 100644
--- a/tests/test_solving.py
+++ b/tests/test_solving.py
@@ -6,7 +6,7 @@
from di.api.dependencies import DependencyParameter
from di.api.providers import DependencyProvider
from di.container import Container, bind_by_type
-from di.dependant import Dependant, JoinedDependant, Marker
+from di.dependent import Dependent, JoinedDependent, Marker
from di.exceptions import (
ScopeViolationError,
SolvingError,
@@ -24,7 +24,7 @@ def badfunc(value): # type: ignore # for Pylance
def root(v: Annotated[None, Marker(badfunc)]) -> None: # type: ignore
raise AssertionError("This function should never be called")
- dep_root = Dependant(root)
+ dep_root = Dependent(root)
container = Container()
@@ -46,7 +46,7 @@ def default_func(value=2) -> int: # type: ignore # for Pylance
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(Dependant(default_func), scopes=[None]),
+ container.solve(Dependent(default_func), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -63,7 +63,7 @@ def marker_default_func(value: Annotated[Any, Marker(lambda: 2)]) -> int:
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(Dependant(marker_default_func), scopes=[None]),
+ container.solve(Dependent(marker_default_func), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -81,7 +81,7 @@ def B(a: Annotated[None, Marker(A, scope="inner")]):
container = Container()
- dep = Dependant(B, scope="outer")
+ dep = Dependent(B, scope="outer")
match = r"scope \(inner\) is narrower than .+'s scope \(outer\)"
with pytest.raises(ScopeViolationError, match=match):
@@ -100,7 +100,7 @@ def B(
container = Container()
with pytest.raises(SolvingError, match="used with multiple scopes"):
- container.solve(Dependant(B, scope="request"), scopes=["app", "request"])
+ container.solve(Dependent(B, scope="request"), scopes=["app", "request"])
def test_siblings() -> None:
@@ -126,7 +126,7 @@ def dep2(one: Annotated[int, Marker(dep1)]) -> int:
container = Container()
siblings = [Sibling(), Sibling()]
- dep = JoinedDependant(Dependant(dep2), siblings=[Dependant(s) for s in siblings])
+ dep = JoinedDependent(Dependent(dep2), siblings=[Dependent(s) for s in siblings])
solved = container.solve(dep, scopes=[None])
with container.enter_scope(None) as state:
container.execute_sync(solved, executor=SyncExecutor(), state=state)
@@ -138,9 +138,9 @@ def test_non_executable_siblings_is_included_in_dag_but_not_executed() -> None:
container = Container()
# sibling should be ignored and excluded from the dag
- main_dep = Dependant(lambda: 1)
- sibling = Dependant[Any](None)
- dep = JoinedDependant(main_dep, siblings=[sibling])
+ main_dep = Dependent(lambda: 1)
+ sibling = Dependent[Any](None)
+ dep = JoinedDependent(main_dep, siblings=[sibling])
solved = container.solve(dep, scopes=[None])
assert [p.dependency for p in solved.dag[dep]] == [sibling]
assert sibling in solved.dag
@@ -158,13 +158,13 @@ def should_be_called() -> None:
nonlocal calls
calls += 1
- class CustomDependant(Dependant[None]):
+ class CustomDependent(Dependent[None]):
called: bool = False
def get_dependencies(self) -> List[DependencyParameter]:
return [
DependencyParameter(
- dependency=Dependant(should_be_called), parameter=None
+ dependency=Dependent(should_be_called), parameter=None
)
]
@@ -173,7 +173,7 @@ def get_dependencies(self) -> List[DependencyParameter]:
def takes_no_parameters() -> None:
pass
- solved = container.solve(CustomDependant(takes_no_parameters), scopes=[None])
+ solved = container.solve(CustomDependent(takes_no_parameters), scopes=[None])
# should_be_called is called, but it's return value is not passed into
# takes_no_parameters since the DependencyParameter has parameter=None
@@ -188,7 +188,7 @@ def takes_no_parameters() -> None:
class CannotBeWired:
def __init__(self, arg) -> None: # type: ignore # for Pylance
- assert arg == 1 # a sentinal value to make sure a bug didn't inject something
+ assert arg == 1 # a sentinel value to make sure a bug didn't inject something
def test_no_wire() -> None:
@@ -202,8 +202,8 @@ def with_flag(dep: Annotated[CannotBeWired, Marker(wire=False)]) -> None:
container = Container()
with pytest.raises(WiringError):
- container.solve(Dependant(without_flag), scopes=[None])
- container.solve(Dependant(with_flag), scopes=[None])
+ container.solve(Dependent(without_flag), scopes=[None])
+ container.solve(Dependent(with_flag), scopes=[None])
def test_wiring_from_binds() -> None:
@@ -214,13 +214,13 @@ def __init__(self) -> None:
super().__init__(1)
container = Container()
- # container.register_by_type(Dependant(CanBeWired), CannotBeWired)
+ # container.register_by_type(Dependent(CanBeWired), CannotBeWired)
with pytest.raises(WiringError):
- container.solve(Dependant(CannotBeWired), scopes=[None])
- container.bind(bind_by_type(Dependant(CanBeWired), CannotBeWired))
+ container.solve(Dependent(CannotBeWired), scopes=[None])
+ container.bind(bind_by_type(Dependent(CanBeWired), CannotBeWired))
with container.enter_scope(None) as state:
c = container.execute_sync(
- container.solve(Dependant(CannotBeWired), scopes=[None]),
+ container.solve(Dependent(CannotBeWired), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
@@ -233,7 +233,7 @@ def bad_dep(v: Annotated[int, Marker(lambda: 1, scope="app")]) -> int:
container = Container()
with pytest.raises(UnknownScopeError):
- container.solve(Dependant(bad_dep), scopes=[None])
+ container.solve(Dependent(bad_dep), scopes=[None])
RandomInt = Annotated[float, Marker(lambda: random(), use_cache=False)]
@@ -250,7 +250,7 @@ def dep3(
assert num_2 != new_num
container = Container()
- solved = container.solve(Dependant(dep3, scope=None), scopes=[None])
+ solved = container.solve(Dependent(dep3, scope=None), scopes=[None])
with container.enter_scope(None) as state:
container.execute_sync(solved, SyncExecutor(), state=state)
@@ -329,7 +329,7 @@ def test_solved_dag(
) -> None:
container = Container()
- dag = container.solve(Dependant(call=dep), scopes=[None]).dag
+ dag = container.solve(Dependent(call=dep), scopes=[None]).dag
got = {d.call: [s.dependency.call for s in dag[d]] for d in dag}
assert got == expected
diff --git a/tests/test_task.py b/tests/test_task.py
index 7e2f2ef8..65ee2296 100644
--- a/tests/test_task.py
+++ b/tests/test_task.py
@@ -7,7 +7,7 @@
import pytest
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import ConcurrentAsyncExecutor
@@ -89,7 +89,7 @@ async def test_dependency_types(
):
dep = wrapper(dep)
container = Container()
- solved = container.solve(Dependant(dep, use_cache=use_cache), scopes=[None]) # type: ignore
+ solved = container.solve(Dependent(dep, use_cache=use_cache), scopes=[None]) # type: ignore
executor = ConcurrentAsyncExecutor()
async with container.enter_scope(None) as state:
res = await container.execute_async(solved, executor=executor, state=state)
diff --git a/tests/test_wiring.py b/tests/test_wiring.py
index e1c6408c..45c21d7f 100644
--- a/tests/test_wiring.py
+++ b/tests/test_wiring.py
@@ -1,7 +1,7 @@
from typing import Optional
from di.container import Container, bind_by_type
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import SyncExecutor
from di.typing import Annotated
@@ -26,7 +26,7 @@ def f(
) -> None:
pass
- dep = Dependant(f)
+ dep = Dependent(f)
subdeps = dep.get_dependencies()
assert [d.dependency.call for d in subdeps] == [g, G, g, g]
@@ -39,7 +39,7 @@ def __init__(self, value: str = "default") -> None:
def func(a: A) -> str:
return a.value
- dep = Dependant(func)
+ dep = Dependent(func)
container = Container()
solved = container.solve(dep, scopes=[None])
@@ -61,7 +61,7 @@ def __init__(self, a: A = A("default")) -> None:
def func(b: B) -> str:
return b.a.value
- dep = Dependant(func)
+ dep = Dependent(func)
container = Container()
solved = container.solve(dep, scopes=[None])
@@ -83,9 +83,9 @@ def __init__(self, a: A = A("default")) -> None:
def func(b: B) -> str:
return b.a.value
- dep = Dependant(func)
+ dep = Dependent(func)
container = Container()
- container.bind(bind_by_type(Dependant(lambda: A("bound")), A))
+ container.bind(bind_by_type(Dependent(lambda: A("bound")), A))
solved = container.solve(dep, scopes=[None])
with container.enter_scope(None) as state:
diff --git a/tests/test_wiring_annotated.py b/tests/test_wiring_annotated.py
index 9a3fc87c..33143d09 100644
--- a/tests/test_wiring_annotated.py
+++ b/tests/test_wiring_annotated.py
@@ -1,7 +1,7 @@
from typing import Optional, Tuple
from di.container import Container, bind_by_type
-from di.dependant import Dependant, Marker
+from di.dependent import Dependent, Marker
from di.executors import SyncExecutor
from di.typing import Annotated
@@ -26,7 +26,7 @@ def f(
) -> None:
pass
- dep = Dependant(f)
+ dep = Dependent(f)
subdeps = dep.get_dependencies()
assert [d.dependency.call for d in subdeps] == [g, G, g, g]
@@ -40,7 +40,7 @@ def __init__(self, value1: str = "default", value2: int = 1) -> None:
def func(a: A) -> Tuple[str, int]:
return (a.value1, a.value2)
- dep = Dependant(func)
+ dep = Dependent(func)
container = Container()
solved = container.solve(dep, scopes=[None])
@@ -62,7 +62,7 @@ def __init__(self, a: A = A("default")) -> None:
def func(b: B) -> str:
return b.a.value
- dep = Dependant(func)
+ dep = Dependent(func)
container = Container()
solved = container.solve(dep, scopes=[None])
@@ -84,9 +84,9 @@ def __init__(self, a: A = A("default")) -> None:
def func(b: B) -> str:
return b.a.value
- dep = Dependant(func)
+ dep = Dependent(func)
container = Container()
- container.bind(bind_by_type(Dependant(lambda: A("bound")), A))
+ container.bind(bind_by_type(Dependent(lambda: A("bound")), A))
solved = container.solve(dep, scopes=[None])
with container.enter_scope(None) as state:
diff --git a/tests/test_wiring_forward_refs.py b/tests/test_wiring_forward_refs.py
index 0f4ecb8d..30be5eb3 100644
--- a/tests/test_wiring_forward_refs.py
+++ b/tests/test_wiring_forward_refs.py
@@ -1,5 +1,5 @@
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -15,7 +15,7 @@ def test_forward_ref_evalutation():
container = Container()
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(Dependant(Foo.foo), scopes=[None]),
+ container.solve(Dependent(Foo.foo), scopes=[None]),
executor=SyncExecutor(),
state=state,
)
diff --git a/tests/test_wiring_pep_563.py b/tests/test_wiring_pep_563.py
index c614e969..8d2b9d94 100644
--- a/tests/test_wiring_pep_563.py
+++ b/tests/test_wiring_pep_563.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from di.container import Container
-from di.dependant import Dependant
+from di.dependent import Dependent
from di.executors import SyncExecutor
@@ -14,7 +14,7 @@ def test_postponed_evaluation_solving():
container = Container()
with container.enter_scope(None) as state:
res = container.execute_sync(
- container.solve(Dependant(Test.__call__), scopes=[None]),
+ container.solve(Dependent(Test.__call__), scopes=[None]),
executor=SyncExecutor(),
state=state,
)