Skip to content

Commit f2c14b3

Browse files
authored
Merge pull request #19 from taskiq-python/feature/annotated-override
2 parents 48f1191 + 223a821 commit f2c14b3

3 files changed

Lines changed: 42 additions & 1 deletion

File tree

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,3 +345,20 @@ def my_function(dependency: DepType):
345345
pass
346346

347347
```
348+
349+
Also we support overrides for annotated types.
350+
351+
For example:
352+
353+
```python
354+
from typing import Annotated
355+
356+
DepType = Annotated[int, Depends(my_func)]
357+
358+
def my_function(
359+
dependency: DepType,
360+
no_cache_dep: Annotated[DepType, Depends(my_func, use_cache=False)],
361+
) -> None:
362+
pass
363+
364+
```

taskiq_dependencies/graph.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,14 @@ def _build_graph(self) -> None: # noqa: C901, WPS210
172172
for param_name, param in sign.parameters.items():
173173
default_value = param.default
174174
if hasattr(param.annotation, "__metadata__"): # noqa: WPS421
175-
for meta in param.annotation.__metadata__:
175+
# We go backwards,
176+
# because you may want to override your annotation
177+
# and the overriden value will appear to be after
178+
# the original `Depends` annotation.
179+
for meta in reversed(param.annotation.__metadata__):
176180
if isinstance(meta, (Dependency, FastapiDepends)):
177181
default_value = meta
182+
break
178183

179184
# This is for FastAPI integration. So you can
180185
# use Depends from taskiq mixed with fastapi's dependencies.

tests/test_annotated.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,22 @@ def test_func(dep: MyType, dep2: MyType) -> Tuple[MyType, MyType]:
105105
value = test_func(**(g.resolve_kwargs()))
106106
assert id(value[0]) == id(value[1])
107107
assert isinstance(value[0], TestClass)
108+
109+
110+
def test_override() -> None:
111+
class TestClass:
112+
pass
113+
114+
MyType = Annotated[TestClass, Depends()]
115+
116+
def test_func(
117+
dep: MyType,
118+
dep2: Annotated[MyType, Depends(use_cache=False)],
119+
) -> Tuple[MyType, MyType]:
120+
return dep, dep2
121+
122+
with DependencyGraph(target=test_func).sync_ctx(exception_propagation=False) as g:
123+
value = test_func(**(g.resolve_kwargs()))
124+
assert id(value[0]) != id(value[1])
125+
assert isinstance(value[0], TestClass)
126+
assert isinstance(value[1], TestClass)

0 commit comments

Comments
 (0)