fastapi-injected 0.4.2__tar.gz → 0.4.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/PKG-INFO +59 -5
  2. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/README.md +58 -4
  3. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/__init__.py +4 -1
  4. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_bind.py +7 -1
  5. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_deps_tp.py +15 -1
  6. fastapi_injected-0.4.3/fastapi_injected/_not_none.py +63 -0
  7. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/ctx.py +126 -25
  8. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/deps.py +2 -1
  9. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/fastapi.py +3 -1
  10. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/overrides.py +3 -5
  11. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/signature.py +6 -1
  12. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/pyproject.toml +1 -1
  13. fastapi_injected-0.4.3/tests/conftest.py +12 -0
  14. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_bind.py +43 -2
  15. fastapi_injected-0.4.3/tests/test_default_app.py +76 -0
  16. fastapi_injected-0.4.3/tests/test_not_none.py +88 -0
  17. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_overrides.py +73 -1
  18. fastapi_injected-0.4.3/tests/test_type_checking_aliases.py +43 -0
  19. fastapi_injected-0.4.3/uv.lock +857 -0
  20. fastapi_injected-0.4.2/uv.lock +0 -839
  21. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.github/dependabot.yml +0 -0
  22. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.github/workflows/automerge.yml +0 -0
  23. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.github/workflows/lint.yml +0 -0
  24. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.github/workflows/publish.yml +0 -0
  25. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.github/workflows/test.yml +0 -0
  26. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.gitignore +0 -0
  27. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/.pre-commit-config.yaml +0 -0
  28. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/LICENSE +0 -0
  29. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_body.py +0 -0
  30. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_cache.py +0 -0
  31. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_calls.py +0 -0
  32. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_dataclass.py +0 -0
  33. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_given.py +0 -0
  34. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_injected.py +0 -0
  35. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_overrides.py +0 -0
  36. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/_rlock.py +0 -0
  37. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/ext.py +0 -0
  38. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/inject.py +0 -0
  39. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/reflect/__init__.py +0 -0
  40. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/reflect/_dependant.py +0 -0
  41. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/reflect/_openapi.py +0 -0
  42. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/reflect/_routes.py +0 -0
  43. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/resolve.py +0 -0
  44. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/fastapi_injected/types.py +0 -0
  45. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/__init__.py +0 -0
  46. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/__init__.py +0 -0
  47. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/annotations.py +0 -0
  48. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/arg.py +0 -0
  49. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/bind.py +0 -0
  50. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/ctx.py +0 -0
  51. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/dataclass.py +0 -0
  52. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/deps.py +0 -0
  53. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/errors.py +0 -0
  54. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/given.py +0 -0
  55. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/inject.py +0 -0
  56. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/injected.py +0 -0
  57. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/integration.py +0 -0
  58. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/markers.py +0 -0
  59. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/overrides.py +0 -0
  60. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/_typing/resolve.py +0 -0
  61. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/deps.py +0 -0
  62. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/ext/__init__.py +0 -0
  63. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/ext/test_pydantic_ai.py +0 -0
  64. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_body.py +0 -0
  65. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_body_reads.py +0 -0
  66. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_cache.py +0 -0
  67. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_calls.py +0 -0
  68. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_concurrency.py +0 -0
  69. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_ctx.py +0 -0
  70. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_dataclass.py +0 -0
  71. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_dependant_cache.py +0 -0
  72. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_errors.py +0 -0
  73. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_fastapi.py +0 -0
  74. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_given.py +0 -0
  75. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_inject.py +0 -0
  76. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_injected.py +0 -0
  77. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_reflect.py +0 -0
  78. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_request_params.py +0 -0
  79. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_resolve.py +0 -0
  80. {fastapi_injected-0.4.2 → fastapi_injected-0.4.3}/tests/test_rlock.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: fastapi-injected
3
- Version: 0.4.2
3
+ Version: 0.4.3
4
4
  Summary: Yet another library to reuse fastapi dependency injection
5
5
  Project-URL: Repository, https://github.com/uriyyo/fastapi-injected
6
6
  Author-email: Yurii Karabas <1998uriyyo@gmail.com>
@@ -163,7 +163,7 @@ async with injection_ctx(app=app):
163
163
  await handler() # `request.app.state` resolves as it does in a route
164
164
  ```
165
165
 
166
- Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
166
+ Without it, the context falls back to the default app — the last one given to `add_injection` (see [FastAPI request integration](#fastapi-request-integration)). With neither, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
167
167
 
168
168
  When a dependency reads more of the request than that — a header, a cookie, a query or path parameter, the body — describe the request with `synthetic_request` and hand it to the context:
169
169
 
@@ -222,7 +222,22 @@ with push_overrides(
222
222
 
223
223
  Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested `push_overrides` blocks merge, with the innermost one winning.
224
224
 
225
- An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override:
225
+ An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override.
226
+
227
+ Enter the block with `async with` for what it builds to be torn down when the block ends. A plain `with` cannot run async teardown, so generator dependencies first built inside it are torn down with the surrounding context instead:
228
+
229
+ ```python
230
+ async with injection_ctx():
231
+ async with push_overrides({Session: fake}):
232
+ await handler() # a generator dependency built here...
233
+ # ...is torn down here
234
+
235
+ with push_overrides({Session: fake}):
236
+ await handler()
237
+ # still open - torn down when `injection_ctx()` ends
238
+ ```
239
+
240
+ Reuse of the surrounding cache works the same either way:
226
241
 
227
242
  ```python
228
243
  async with injection_ctx():
@@ -246,6 +261,8 @@ async with injection_ctx({Session: fake}) as ctx:
246
261
 
247
262
  For FastAPI's own `app.dependency_overrides`, `override_app(app, {dep: fake})` sets entries for a `with` block and restores the previous mapping afterwards, including entries added inside the block.
248
263
 
264
+ A route reads `app.dependency_overrides` on its own. Outside a request, a context only knows the application it is given: `injection_ctx(app=app)`, or a `request=` whose scope carries one, applies that app's overrides the way a route would, beneath the overrides passed to the context itself. A context given neither uses the default app, the last one given to `add_injection`, and applies none when there is no default.
265
+
249
266
  ### Dependencies that are objects
250
267
 
251
268
  Resolved values are cached in their context by the callable that resolves them, so a dependency that is an object — a class holding configuration, a parametrized resolver — has to be hashable to get there. A plain dataclass is not, and a frozen one still refuses as soon as it holds a list or a dict.
@@ -291,6 +308,28 @@ except DependencyResolutionError as exc:
291
308
 
292
309
  It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
293
310
 
311
+ ### Values that must be there
312
+
313
+ A dependency that loads something often returns `None` when it is missing. `NotNone[T, dep]` is what `dep` resolves to, or a 404 when that is `None`, and a type checker sees it as plain `T`:
314
+
315
+ ```python
316
+ from typing import Annotated
317
+ from fastapi import Depends
318
+ from fastapi_injected import NotNone
319
+
320
+ type MaybeUserDep = Annotated[User | None, Depends(load_user)]
321
+ type UserDep = NotNone[User, MaybeUserDep]
322
+
323
+
324
+ @app.get("/users/{user_id}")
325
+ async def get_user(user: UserDep) -> User:
326
+ return user # never None here
327
+ ```
328
+
329
+ A third item chooses the error: anything called with no arguments that returns an exception, such as an exception class — `NotNone[User, MaybeUserDep, UserGone]`.
330
+
331
+ `NotNone` reads the same dependency it wraps, so a handler can ask for `UserDep` and `MaybeUserDep` side by side and the user is still loaded once per request. A dependency made at runtime, like `Given(...)`, works too, and is not kept once its resolve is done.
332
+
294
333
  ### Dependencies decided at runtime
295
334
 
296
335
  A dependency is usually written as an annotation, but sometimes it is a value a caller already has, or one picked while the program runs. `Given` turns a value into a dependency that resolves to it:
@@ -323,6 +362,8 @@ What a parameter is bound to can be written any way a dependency can be: a marke
323
362
 
324
363
  Binding takes the parameters away, and a type checker sees what is left: `bind_deps(describe, Given(doc))` is a function of `(role)`, and binding both leaves one of no arguments at all. The bound function is a dependency like any other — resolve it, `@inject` it, override what it depends on. Binding more markers than the function has parameters is a `TypeError` rather than a silent truncation.
325
364
 
365
+ A request marker is bound under a made-up parameter name, so it has to say what it reads: `Annotated[int, Path(alias="item_id")]` binds, while a bare `Path()`, `Query()`, `Header()` or `Cookie()` raises `UnnamedParamError` instead of reading a parameter no request carries.
366
+
326
367
  ### Dependencies as objects
327
368
 
328
369
  When the markers belong together, `MakeInjected` makes a dataclass of them: fields annotated with `DepOf` hold the markers, and the call receives what they resolve to.
@@ -414,6 +455,19 @@ async def route(service: Dep[Service]) -> str:
414
455
  ...
415
456
  ```
416
457
 
458
+ `add_injection` also makes `app` the default app: a context opened without a request — a background job, a bot handler, a script — resolves against it, so `request.app` is that app and its `dependency_overrides` apply, as they would in a route. The last app given to `add_injection` wins. `set_default_app` sets it directly, and used with `with` puts the previous one back when the block ends:
459
+
460
+ ```python
461
+ from fastapi_injected import set_default_app
462
+
463
+ set_default_app(worker_app) # for the rest of the process
464
+
465
+ with set_default_app(test_app): # only inside the block
466
+ await job()
467
+ ```
468
+
469
+ The default lives in a context variable, so it reaches the tasks started after it is set: set it at startup, not inside a task that other tasks will not see.
470
+
417
471
  Anything called from the handler — including `@inject`-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request. The context is opened by a middleware, so `resolve` also works inside middleware added before it (before routing, `request.scope["route"]` and path params are not available yet).
418
472
 
419
473
  WebSocket routes work the same way: the context is bound to the `WebSocket` instead of a `Request`, and dependencies that ask for one get it. A websocket handed to a dependency shares its handshake with the one the route received, so it can be talked through after the route has called `accept()`:
@@ -471,8 +525,8 @@ The root package is what you need to use the library, and the surface a release
471
525
  | | |
472
526
  | --- | --- |
473
527
  | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
474
- | Resolving | `inject`, `resolve`, `bind_deps` |
475
- | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
528
+ | Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
529
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
476
530
  | FastAPI integration | `add_injection` |
477
531
  | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
478
532
 
@@ -141,7 +141,7 @@ async with injection_ctx(app=app):
141
141
  await handler() # `request.app.state` resolves as it does in a route
142
142
  ```
143
143
 
144
- Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
144
+ Without it, the context falls back to the default app — the last one given to `add_injection` (see [FastAPI request integration](#fastapi-request-integration)). With neither, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
145
145
 
146
146
  When a dependency reads more of the request than that — a header, a cookie, a query or path parameter, the body — describe the request with `synthetic_request` and hand it to the context:
147
147
 
@@ -200,7 +200,22 @@ with push_overrides(
200
200
 
201
201
  Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested `push_overrides` blocks merge, with the innermost one winning.
202
202
 
203
- An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override:
203
+ An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override.
204
+
205
+ Enter the block with `async with` for what it builds to be torn down when the block ends. A plain `with` cannot run async teardown, so generator dependencies first built inside it are torn down with the surrounding context instead:
206
+
207
+ ```python
208
+ async with injection_ctx():
209
+ async with push_overrides({Session: fake}):
210
+ await handler() # a generator dependency built here...
211
+ # ...is torn down here
212
+
213
+ with push_overrides({Session: fake}):
214
+ await handler()
215
+ # still open - torn down when `injection_ctx()` ends
216
+ ```
217
+
218
+ Reuse of the surrounding cache works the same either way:
204
219
 
205
220
  ```python
206
221
  async with injection_ctx():
@@ -224,6 +239,8 @@ async with injection_ctx({Session: fake}) as ctx:
224
239
 
225
240
  For FastAPI's own `app.dependency_overrides`, `override_app(app, {dep: fake})` sets entries for a `with` block and restores the previous mapping afterwards, including entries added inside the block.
226
241
 
242
+ A route reads `app.dependency_overrides` on its own. Outside a request, a context only knows the application it is given: `injection_ctx(app=app)`, or a `request=` whose scope carries one, applies that app's overrides the way a route would, beneath the overrides passed to the context itself. A context given neither uses the default app, the last one given to `add_injection`, and applies none when there is no default.
243
+
227
244
  ### Dependencies that are objects
228
245
 
229
246
  Resolved values are cached in their context by the callable that resolves them, so a dependency that is an object — a class holding configuration, a parametrized resolver — has to be hashable to get there. A plain dataclass is not, and a frozen one still refuses as soon as it holds a list or a dict.
@@ -269,6 +286,28 @@ except DependencyResolutionError as exc:
269
286
 
270
287
  It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
271
288
 
289
+ ### Values that must be there
290
+
291
+ A dependency that loads something often returns `None` when it is missing. `NotNone[T, dep]` is what `dep` resolves to, or a 404 when that is `None`, and a type checker sees it as plain `T`:
292
+
293
+ ```python
294
+ from typing import Annotated
295
+ from fastapi import Depends
296
+ from fastapi_injected import NotNone
297
+
298
+ type MaybeUserDep = Annotated[User | None, Depends(load_user)]
299
+ type UserDep = NotNone[User, MaybeUserDep]
300
+
301
+
302
+ @app.get("/users/{user_id}")
303
+ async def get_user(user: UserDep) -> User:
304
+ return user # never None here
305
+ ```
306
+
307
+ A third item chooses the error: anything called with no arguments that returns an exception, such as an exception class — `NotNone[User, MaybeUserDep, UserGone]`.
308
+
309
+ `NotNone` reads the same dependency it wraps, so a handler can ask for `UserDep` and `MaybeUserDep` side by side and the user is still loaded once per request. A dependency made at runtime, like `Given(...)`, works too, and is not kept once its resolve is done.
310
+
272
311
  ### Dependencies decided at runtime
273
312
 
274
313
  A dependency is usually written as an annotation, but sometimes it is a value a caller already has, or one picked while the program runs. `Given` turns a value into a dependency that resolves to it:
@@ -301,6 +340,8 @@ What a parameter is bound to can be written any way a dependency can be: a marke
301
340
 
302
341
  Binding takes the parameters away, and a type checker sees what is left: `bind_deps(describe, Given(doc))` is a function of `(role)`, and binding both leaves one of no arguments at all. The bound function is a dependency like any other — resolve it, `@inject` it, override what it depends on. Binding more markers than the function has parameters is a `TypeError` rather than a silent truncation.
303
342
 
343
+ A request marker is bound under a made-up parameter name, so it has to say what it reads: `Annotated[int, Path(alias="item_id")]` binds, while a bare `Path()`, `Query()`, `Header()` or `Cookie()` raises `UnnamedParamError` instead of reading a parameter no request carries.
344
+
304
345
  ### Dependencies as objects
305
346
 
306
347
  When the markers belong together, `MakeInjected` makes a dataclass of them: fields annotated with `DepOf` hold the markers, and the call receives what they resolve to.
@@ -392,6 +433,19 @@ async def route(service: Dep[Service]) -> str:
392
433
  ...
393
434
  ```
394
435
 
436
+ `add_injection` also makes `app` the default app: a context opened without a request — a background job, a bot handler, a script — resolves against it, so `request.app` is that app and its `dependency_overrides` apply, as they would in a route. The last app given to `add_injection` wins. `set_default_app` sets it directly, and used with `with` puts the previous one back when the block ends:
437
+
438
+ ```python
439
+ from fastapi_injected import set_default_app
440
+
441
+ set_default_app(worker_app) # for the rest of the process
442
+
443
+ with set_default_app(test_app): # only inside the block
444
+ await job()
445
+ ```
446
+
447
+ The default lives in a context variable, so it reaches the tasks started after it is set: set it at startup, not inside a task that other tasks will not see.
448
+
395
449
  Anything called from the handler — including `@inject`-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request. The context is opened by a middleware, so `resolve` also works inside middleware added before it (before routing, `request.scope["route"]` and path params are not available yet).
396
450
 
397
451
  WebSocket routes work the same way: the context is bound to the `WebSocket` instead of a `Request`, and dependencies that ask for one get it. A websocket handed to a dependency shares its handshake with the one the route received, so it can be talked through after the route has called `accept()`:
@@ -449,8 +503,8 @@ The root package is what you need to use the library, and the surface a release
449
503
  | | |
450
504
  | --- | --- |
451
505
  | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
452
- | Resolving | `inject`, `resolve`, `bind_deps` |
453
- | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
506
+ | Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
507
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
454
508
  | FastAPI integration | `add_injection` |
455
509
  | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
456
510
 
@@ -1,6 +1,7 @@
1
1
  from ._bind import bind_deps
2
2
  from ._given import Given
3
- from .ctx import InjectionContext, UnboundContextError, injection_ctx, synthetic_request
3
+ from ._not_none import NotNone
4
+ from .ctx import InjectionContext, UnboundContextError, injection_ctx, set_default_app, synthetic_request
4
5
  from .deps import DependencyResolutionError, UnnamedParamError
5
6
  from .fastapi import add_injection
6
7
  from .inject import inject
@@ -19,6 +20,7 @@ __all__ = [
19
20
  "Injected",
20
21
  "InjectionContext",
21
22
  "NotADependencyError",
23
+ "NotNone",
22
24
  "UnboundContextError",
23
25
  "UnnamedParamError",
24
26
  "ValueOverride",
@@ -29,5 +31,6 @@ __all__ = [
29
31
  "override_app",
30
32
  "push_overrides",
31
33
  "resolve",
34
+ "set_default_app",
32
35
  "synthetic_request",
33
36
  ]
@@ -7,6 +7,7 @@ from fastapi.params import Depends
7
7
 
8
8
  from ._calls import annotated
9
9
  from ._deps_tp import unwrap_tp
10
+ from .deps import _named_param
10
11
  from .signature import Signature
11
12
  from .types import AsyncFunc, DepOf, Func
12
13
 
@@ -41,7 +42,12 @@ def _dep_annotation(dep: DepOf[Any] | Callable[..., Any], /) -> Any:
41
42
  if isinstance(dep, Depends):
42
43
  return annotated(Any, dep)
43
44
 
44
- if _is_annotation(dep) or not callable(dep):
45
+ if _is_annotation(dep):
46
+ # bound, a marker is read under the made-up `__dep_arg_N` name, so it must name its own
47
+ _named_param(unwrap_tp(dep))
48
+ return dep
49
+
50
+ if not callable(dep):
45
51
  return dep
46
52
 
47
53
  return annotated(Any, Depends(dep))
@@ -1,3 +1,4 @@
1
+ import sys
1
2
  import types
2
3
  import typing
3
4
  from collections.abc import Callable
@@ -10,10 +11,23 @@ from typing_inspection.typing_objects import is_typealiastype
10
11
  from .types import ArgMarker, HasDependsHook
11
12
 
12
13
 
14
+ def _alias_value(alias: Any, /) -> Any:
15
+ try:
16
+ return alias.__value__
17
+ except NameError:
18
+ # a `TYPE_CHECKING`-only name: leave it a forward reference
19
+ if sys.version_info < (3, 14):
20
+ raise
21
+
22
+ from annotationlib import Format, call_evaluate_function # noqa: PLC0415
23
+
24
+ return call_evaluate_function(alias.evaluate_value, Format.FORWARDREF)
25
+
26
+
13
27
  def unwrap_tp(tp: Any) -> Any:
14
28
  # PEP 695 aliases can be nested, e.g. `type A = B` where `type B = Annotated[...]`
15
29
  while is_typealiastype(tp):
16
- tp = tp.__value__
30
+ tp = _alias_value(tp)
17
31
 
18
32
  return tp
19
33
 
@@ -0,0 +1,63 @@
1
+ import inspect
2
+ from collections.abc import Callable
3
+ from functools import cache
4
+ from typing import TYPE_CHECKING, Annotated, Any
5
+
6
+ from fastapi import Depends, HTTPException, status
7
+
8
+ from ._bind import _dep_annotation
9
+ from ._calls import is_static_annotation
10
+ from ._deps_tp import unwrap_tp
11
+
12
+
13
+ def not_found() -> Exception:
14
+ return HTTPException(status.HTTP_404_NOT_FOUND, "Not found")
15
+
16
+
17
+ def _build(annotation: Any, error: Callable[[], BaseException], /) -> Callable[..., Any]:
18
+ async def require(value: Any) -> Any:
19
+ if value is None:
20
+ raise error()
21
+
22
+ return value
23
+
24
+ require.__signature__ = inspect.Signature( # type: ignore[ty:missing-attribute]
25
+ [inspect.Parameter("value", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=annotation)],
26
+ )
27
+
28
+ return require
29
+
30
+
31
+ # one callable per source dependency, so FastAPI shares its result within a request
32
+ _build_static = cache(_build)
33
+
34
+
35
+ def not_none(tp: Any, dep: Any, error: Callable[[], BaseException] = not_found, /) -> Any:
36
+ annotation = unwrap_tp(_dep_annotation(dep))
37
+ build = _build_static if is_static_annotation(annotation) else _build
38
+
39
+ return Annotated[tp, Depends(build(annotation, error))]
40
+
41
+
42
+ if TYPE_CHECKING:
43
+ from typing import Annotated as NotNone
44
+ else:
45
+
46
+ class NotNone:
47
+ """`NotNone[T, dep]`: what `dep` resolves to, or `error()` raised when it is `None` (404 by default)."""
48
+
49
+ def __class_getitem__(cls, item: Any) -> Any:
50
+ match item:
51
+ case (tp, dep):
52
+ return not_none(tp, dep)
53
+ case (tp, dep, error):
54
+ return not_none(tp, dep, error)
55
+ case _:
56
+ raise TypeError(f"NotNone[...] takes a type, a dependency and optionally an error, got {item!r}")
57
+
58
+
59
+ __all__ = [
60
+ "NotNone",
61
+ "not_found",
62
+ "not_none",
63
+ ]
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  import json
2
4
  from collections import ChainMap
3
5
  from collections.abc import AsyncGenerator, Generator, Iterator, Mapping, MutableMapping, Sequence
@@ -7,8 +9,9 @@ from contextlib import (
7
9
  asynccontextmanager,
8
10
  contextmanager,
9
11
  )
10
- from contextvars import ContextVar
11
- from dataclasses import field, replace
12
+ from contextvars import ContextVar, Token
13
+ from dataclasses import dataclass, field, replace
14
+ from types import TracebackType
12
15
  from typing import Any, Self, cast
13
16
  from urllib.parse import urlencode
14
17
 
@@ -292,8 +295,8 @@ class InjectionContext(MakeDataclass):
292
295
  /,
293
296
  *,
294
297
  provider: HasDependencyOverrides | None = None,
295
- ) -> AbstractContextManager[Self]:
296
- return _enter_ctx(
298
+ ) -> OverrideBlock[Self]:
299
+ return OverrideBlock(
297
300
  replace(
298
301
  self,
299
302
  parent=self,
@@ -304,20 +307,117 @@ class InjectionContext(MakeDataclass):
304
307
  )
305
308
 
306
309
 
310
+ @contextmanager
311
+ def _reset_on_exit[T](var: ContextVar[T], token: Token[T], value: T, /) -> Generator[T]:
312
+ try:
313
+ yield value
314
+ finally:
315
+ var.reset(token)
316
+
317
+
318
+ def set_var[T](var: ContextVar[T], value: T, /) -> AbstractContextManager[T]:
319
+ # set right away; `with` also puts the previous value back
320
+ return _reset_on_exit(var, var.set(value), value)
321
+
322
+
307
323
  _injection_ctx: ContextVar[InjectionContext | None] = ContextVar(
308
324
  "_injection_ctx",
309
325
  default=None,
310
326
  )
311
327
 
312
328
 
313
- @contextmanager
314
- def _enter_ctx[S: InjectionContext](ctx: S, /) -> Generator[S]:
315
- token = _injection_ctx.set(ctx)
329
+ _default_app: ContextVar[FastAPI | None] = ContextVar("_default_app", default=None)
316
330
 
317
- try:
318
- yield ctx
319
- finally:
320
- _injection_ctx.reset(token)
331
+
332
+ def set_default_app(app: FastAPI | None, /) -> AbstractContextManager[FastAPI | None]:
333
+ return set_var(_default_app, app)
334
+
335
+
336
+ def _scope_app(request: BoundConnection | None, /) -> HasDependencyOverrides | None:
337
+ match request.scope.get("app") if request is not None else None:
338
+ case HasDependencyOverrides() as app:
339
+ return app
340
+ case _:
341
+ return None
342
+
343
+
344
+ def _with_stack(
345
+ request: BoundConnection | None,
346
+ stack: AsyncExitStack,
347
+ /,
348
+ *,
349
+ app: FastAPI | None = None,
350
+ ) -> BoundConnection:
351
+ # what is built against the returned request is torn down with `stack`
352
+ extra_scope: Scope = {
353
+ "fastapi_inner_astack": stack,
354
+ "fastapi_function_astack": stack,
355
+ "fastapi_async_cleanup_scopes": {
356
+ stack: stack.enter_context(CancelScope()),
357
+ },
358
+ }
359
+
360
+ request = (
361
+ _rebind_request(request, extra_scope=extra_scope)
362
+ if request is not None
363
+ else _dummy_request(app=app, extra_scope=extra_scope)
364
+ )
365
+
366
+ request.scope.setdefault("fastapi_middleware_astack", stack)
367
+
368
+ return request
369
+
370
+
371
+ @dataclass
372
+ class OverrideBlock[S: InjectionContext]:
373
+ ctx: S
374
+
375
+ _entered: AbstractContextManager[InjectionContext | None] | None = field(default=None, init=False)
376
+ _stack: AsyncExitStack | None = field(default=None, init=False)
377
+
378
+ def __init__(self, ctx: S, /) -> None:
379
+ self.ctx = ctx
380
+
381
+ def __enter__(self) -> S:
382
+ self._entered = set_var(_injection_ctx, self.ctx)
383
+ self._entered.__enter__()
384
+
385
+ return self.ctx
386
+
387
+ def __exit__(
388
+ self,
389
+ exc_type: type[BaseException] | None,
390
+ exc: BaseException | None,
391
+ tb: TracebackType | None,
392
+ /,
393
+ ) -> None:
394
+ if self._entered is not None:
395
+ self._entered.__exit__(exc_type, exc, tb)
396
+
397
+ async def __aenter__(self) -> S:
398
+ self._stack = stack = AsyncExitStack()
399
+ await stack.__aenter__()
400
+
401
+ try:
402
+ ctx = replace(self.ctx, request=_with_stack(self.ctx.request, stack))
403
+ stack.enter_context(set_var(_injection_ctx, ctx))
404
+ except BaseException as exc:
405
+ await stack.__aexit__(type(exc), exc, exc.__traceback__)
406
+ raise
407
+
408
+ return ctx
409
+
410
+ async def __aexit__(
411
+ self,
412
+ exc_type: type[BaseException] | None,
413
+ exc: BaseException | None,
414
+ tb: TracebackType | None,
415
+ /,
416
+ ) -> bool | None:
417
+ if self._stack is not None:
418
+ return await self._stack.__aexit__(exc_type, exc, tb)
419
+
420
+ return None
321
421
 
322
422
 
323
423
  @asynccontextmanager
@@ -335,26 +435,25 @@ async def injection_ctx(
335
435
 
336
436
  parent = InjectionContext.current()
337
437
 
438
+ # the app a context is told about overrides like the app of a route would; one only
439
+ # inherited from the parent already reaches it through the parent's overrides
440
+ if provider is None:
441
+ provider = cast("HasDependencyOverrides", app) if app is not None else _scope_app(request)
442
+
338
443
  # a context of its own is about building dependencies again, not about leaving the
339
444
  # request they are built for
340
445
  if request is None and parent is not None:
341
446
  request = parent.request
342
447
 
343
- async with AsyncExitStack() as stack:
344
- extra_scope: Scope = {
345
- "fastapi_inner_astack": stack,
346
- "fastapi_function_astack": stack,
347
- # entered here, not by fastapi inside a task group
348
- "fastapi_async_cleanup_scopes": {stack: stack.enter_context(CancelScope())},
349
- }
448
+ # no request to take the app from, so the default one stands in
449
+ if request is None and app is None:
450
+ app = _default_app.get()
350
451
 
351
- request = (
352
- _rebind_request(request, extra_scope=extra_scope)
353
- if request is not None
354
- else _dummy_request(app=app, extra_scope=extra_scope)
355
- )
452
+ if provider is None:
453
+ provider = cast("HasDependencyOverrides | None", app)
356
454
 
357
- request.scope.setdefault("fastapi_middleware_astack", stack)
455
+ async with AsyncExitStack() as stack:
456
+ request = _with_stack(request, stack, app=app)
358
457
 
359
458
  ctx = InjectionContext(
360
459
  dependency_cache,
@@ -363,7 +462,7 @@ async def injection_ctx(
363
462
  own_overrides=normalize_overrides(overrides, provider=provider),
364
463
  )
365
464
 
366
- with _enter_ctx(ctx):
465
+ with set_var(_injection_ctx, ctx):
367
466
  yield ctx
368
467
 
369
468
 
@@ -385,8 +484,10 @@ async def ensure_injection_ctx(
385
484
 
386
485
  __all__ = [
387
486
  "InjectionContext",
487
+ "OverrideBlock",
388
488
  "UnboundContextError",
389
489
  "ensure_injection_ctx",
390
490
  "injection_ctx",
491
+ "set_default_app",
391
492
  "synthetic_request",
392
493
  ]
@@ -30,7 +30,8 @@ class DependencyResolutionError(ValueError):
30
30
  class UnnamedParamError(TypeError):
31
31
  def __init__(self, param: Any, /) -> None:
32
32
  super().__init__(
33
- f"{type(param).__name__}() resolved on its own has no parameter name to read from the request - "
33
+ f"{type(param).__name__}() resolved on its own or bound with bind_deps has no parameter name "
34
+ f"to read from the request - "
34
35
  f"give it an alias, like {type(param).__name__}(alias='x-api-key')",
35
36
  )
36
37
 
@@ -9,7 +9,7 @@ from starlette.requests import HTTPConnection
9
9
  from starlette.types import ASGIApp, Message, Receive, Scope, Send
10
10
 
11
11
  from ._cache import ContextCache
12
- from .ctx import injection_ctx
12
+ from .ctx import injection_ctx, set_default_app
13
13
  from .types import BoundConnection, DependencyCache, HasDependencyOverrides
14
14
 
15
15
  _DEPENDENCY_CACHE_KEY = "__fastapi_injected_dependency_cache__"
@@ -140,6 +140,8 @@ def add_injection(
140
140
  app: FastAPI,
141
141
  /,
142
142
  ) -> None:
143
+ set_default_app(app)
144
+
143
145
  if not _is_build_middleware_stack_patched(app):
144
146
  _wrap_build_middleware_stack(app)
145
147
 
@@ -5,7 +5,7 @@ from typing import Any, Protocol
5
5
 
6
6
  from ._dataclass import MakeDataclass
7
7
  from ._overrides import FactoryOverride, Overrides, ValueOverride, normalize_overrides
8
- from .ctx import InjectionContext
8
+ from .ctx import InjectionContext, OverrideBlock
9
9
  from .types import HasDependencyOverrides
10
10
 
11
11
 
@@ -13,17 +13,15 @@ class OverridesProvider(MakeDataclass):
13
13
  dependency_overrides: Mapping[Any, Any] = field(default_factory=dict)
14
14
 
15
15
 
16
- @contextmanager
17
16
  def push_overrides(
18
17
  overrides: Overrides | None = None,
19
18
  /,
20
19
  *,
21
20
  provider: HasDependencyOverrides | None = None,
22
- ) -> Generator[InjectionContext]:
21
+ ) -> OverrideBlock[InjectionContext]:
23
22
  ctx = InjectionContext.current() or InjectionContext()
24
23
 
25
- with ctx.override(overrides, provider=provider) as child:
26
- yield child
24
+ return ctx.override(overrides, provider=provider)
27
25
 
28
26
 
29
27
  class HasMutableOverrides(Protocol):
@@ -7,8 +7,9 @@ from typing import Annotated, Any, NotRequired, Self, TypedDict, Unpack, cast
7
7
  from fastapi import params
8
8
  from fastapi.dependencies.models import Dependant
9
9
  from fastapi.dependencies.utils import get_typed_signature
10
+ from typing_inspection.typing_objects import is_typealiastype
10
11
 
11
- from ._deps_tp import DependsSource, as_depends, is_arg, is_dep, is_request_param
12
+ from ._deps_tp import DependsSource, as_depends, is_arg, is_dep, is_request_param, unwrap_tp
12
13
  from .types import Func, HasSignature, Injected
13
14
 
14
15
 
@@ -171,6 +172,10 @@ class Signature(inspect.Signature):
171
172
  if param.default is Injected:
172
173
  param = param.replace(default=inspect.Parameter.empty)
173
174
 
175
+ if is_typealiastype(param.annotation):
176
+ # FastAPI would evaluate the alias eagerly
177
+ param = param.replace(annotation=unwrap_tp(param.annotation))
178
+
174
179
  return param
175
180
 
176
181
  return self.replace(
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fastapi-injected"
3
- version = "0.4.2"
3
+ version = "0.4.3"
4
4
  description = "Yet another library to reuse fastapi dependency injection"
5
5
  authors = [
6
6
  { name = "Yurii Karabas", email = "1998uriyyo@gmail.com" },