Debian Codegraph @

src/inject/__init__.py

raw symbols SCIP
1 """
2 Python dependency injection framework.
3
4 Usage:
5 - Create an optional configuration::
6 def my_config(binder):
7 binder.bind(Cache, RedisCache('localhost:1234'))
8 binder.bind_to_provider(CurrentUser, get_current_user)
9
10 - Create a shared injector::
11 inject.configure(my_config)
12
13 - Use `inject.instance`, `inject.attr` or `inject.param` to inject dependencies::
14 class User:
15 cache = inject.attr(Cache)
16
17 @classmethod
18 def load(cls, id):
19 return cls.cache.load('user', id)
20
21 def save(self):
22 self.cache.save(self)
23
24 def foo(bar):
25 cache = inject.instance(Cache)
26 cache.save('bar', bar)
27
28 @inject.params(cache=Cache)
29 def bar(foo, cache=None):
30 cache.save('foo', foo)
31
32 Binding types:
33 - Instance bindings configured via `bind(cls, instance) which always return the same instance.
34 - Constructor bindings `bind_to_constructor(cls, callable)` which create a singleton
35 on first access.
36 - Provider bindings `bind_to_provider(cls, callable)` which call the provider
37 for each injection.
38 - Runtime bindings which automatically create class singletons.
39
40 Thread-safety:
41 After configuration the injector is thread-safe and can be safely reused by multiple threads.
42
43 Unit testing:
44 In tests use `inject.clear_and_configure(callable)` to create a new injector on setup,
45 and `inject.clear()` to clean-up on tear down.
46
47 Runtime bindings greatly reduce the required configuration by automatically creating singletons
48 on first access. For example, below only the Config class requires binding configuration,
49 all other classes are runtime bindings::
50 class Cache:
51 config = inject.attr(Config)
52
53 def __init__(self):
54 self._redis = connect(self.config.redis_address)
55
56 class Db:
57 pass
58
59 class UserRepo:
60 cache = inject.attr(Cache)
61 db = inject.attr(Db)
62
63 def load(self, user_id):
64 return cache.load('user', user_id) or db.load('user', user_id)
65
66 class Config:
67 def __init__(self, redis_address):
68 self.redis_address = redis_address
69
70 def my_config(binder):
71 binder.bind(Config, load_config_file())
72
73 inject.configure(my_config)
74
75 """ # noqa: E501
76
77 from __future__ import annotations
78
79 import contextlib
80 import functools
81 import inspect
82 import logging
83 import threading
84 import typing as t
85 from types import UnionType
86
87 from inject._version import __version__ as __version__
88
89 _RETURN = "return"
90 _MISSING = object()
91
92 logger = logging.getLogger("inject")
93
94 _INJECTOR = None # Shared injector instance.
95 _INJECTOR_LOCK = threading.RLock() # Guards injector initialization.
96 _BINDING_LOCK = threading.RLock() # Guards runtime bindings.
97
98 Injectable = object | t.Any
99 T = t.TypeVar("T", bound=Injectable)
100 P = t.ParamSpec("P")
101 Binding = type[Injectable] | t.Hashable
102 Constructor = t.Callable[
103 [],
104 Injectable
105 | contextlib.AbstractContextManager[Injectable]
106 | contextlib.AbstractAsyncContextManager[Injectable],
107 ]
108 Provider = Constructor
109 # `t.Optional` because PEP 604 unions don't support forward references.
110 BinderCallable = t.Callable[["Binder"], t.Optional["Binder"]]
111 _InjectionDecorator = t.Callable[[t.Callable[..., t.Any]], t.Callable[..., t.Any]]
112
113
114 class ConstructorTypeError(TypeError):
115 def __init__(
116 self, constructor: t.Callable[..., t.Any], previous_error: TypeError
117 ) -> None:
118 super().__init__(f"{constructor} raised an error: {previous_error}")
119
120
121 class Binder:
122 _bindings: dict[Binding, Constructor]
123
124 def __init__(self, allow_override: bool = False) -> None: # noqa: FBT001, FBT002
125 self._bindings = {}
126 self.allow_override = allow_override
127
128 def install(self, config: BinderCallable) -> Binder:
129 """Install another callable configuration."""
130 config(self)
131 return self
132
133 def bind(self, cls: Binding, instance: T) -> Binder:
134 """Bind a class to an instance."""
135 self._check_class(cls)
136
137 b = lambda: instance # noqa: E731
138 self._bindings[cls] = b
139 self._maybe_bind_forward(cls, b)
140
141 logger.debug("Bound %s to an instance %s", cls, instance)
142 return self
143
144 def bind_to_constructor(self, cls: Binding, constructor: Constructor) -> Binder:
145 """
146 Bind a class to a callable singleton constructor.
147
148 Raises:
149 InjectorException: if no constructor
150
151 """
152 self._check_class(cls)
153 if constructor is None:
154 raise InjectorException(f"Constructor cannot be None, key={cls}")
155
156 b = _ConstructorBinding(constructor)
157 self._bindings[cls] = b
158 self._maybe_bind_forward(cls, b)
159
160 logger.debug("Bound %s to a constructor %s", cls, constructor)
161 return self
162
163 def bind_to_provider(self, cls: Binding, provider: Provider) -> Binder:
164 """
165 Bind a class to a callable instance provider executed for each injection.
166
167 A provider can be a normal function or a context manager.
168 Both sync and async are supported.
169
170 Raises:
171 InjectorException: if no provider
172
173 """
174 self._check_class(cls)
175 if provider is None:
176 raise InjectorException(f"Provider cannot be None, key={cls}")
177
178 b = provider
179 self._bindings[cls] = b
180 self._maybe_bind_forward(cls, b)
181
182 logger.debug("Bound %s to a provider %s", cls, provider)
183 return self
184
185 def _check_class(self, cls: Binding) -> None:
186 if cls is None:
187 raise InjectorException("Binding key cannot be None")
188
189 if not self.allow_override and cls in self._bindings:
190 raise InjectorException(f"Duplicate binding, key={cls}")
191
192 if isinstance(cls, str):
193 ref = t.ForwardRef(cls)
194 if not self.allow_override and ref in self._bindings:
195 msg = f'Duplicate forward binding, i.e. "int" and int, key={cls}'
196 raise InjectorException(msg)
197
198 def _maybe_bind_forward(self, cls: Binding, binding: t.Any) -> None: # noqa: ANN401
199 """Bind a string forward reference."""
200 if not isinstance(cls, str):
201 return
202
203 ref = t.ForwardRef(cls)
204 self._bindings[ref] = binding
205 logger.debug('Bound forward ref "%s"', cls)
206
207
208 class Injector:
209 _bindings: dict[Binding, Constructor]
210
211 def __init__(
212 self,
213 config: BinderCallable | None = None,
214 # TODO(pyctrl): force following flags to be kwargs
215 bind_in_runtime: bool = True, # noqa: FBT001, FBT002
216 allow_override: bool = False, # noqa: FBT001, FBT002
217 ) -> None:
218 self._bind_in_runtime = bind_in_runtime
219 if config:
220 binder = Binder(allow_override)
221 config(binder)
222 self._bindings = binder._bindings # noqa: SLF001
223 else:
224 self._bindings = {}
225
226 @t.overload
227 def get_instance(self, cls: type[T]) -> T: ...
228
229 @t.overload
230 def get_instance(self, cls: t.Hashable) -> Injectable: ...
231
232 def get_instance(self, cls: Binding) -> Injectable:
233 """
234 Return an instance for a class.
235
236 Raises:
237 InjectorException: on errors
238 ConstructorTypeError: over TypeError
239
240 """
241 binding = self._bindings.get(cls)
242 if binding:
243 return binding()
244
245 # Try to create a runtime binding.
246 with _BINDING_LOCK:
247 binding = self._bindings.get(cls)
248 if binding:
249 return binding()
250
251 if not self._bind_in_runtime:
252 msg = f"No binding was found for key={cls}"
253 raise InjectorException(msg)
254
255 if not callable(cls):
256 msg = (
257 "Cannot create a runtime binding, the key is not callable,"
258 f" key={cls}"
259 )
260 raise InjectorException(msg)
261
262 try:
263 instance = cls()
264 except TypeError as previous_error:
265 raise ConstructorTypeError(cls, previous_error) # noqa: B904
266
267 self._bindings[cls] = lambda: instance
268
269 msg = "Created a runtime binding for key=%s, instance=%s"
270 logger.debug(msg, cls, instance)
271 return instance
272
273
274 class InjectorException(Exception):
275 pass
276
277
278 class _ConstructorBinding(t.Generic[T]):
279 _instance: T | None
280
281 def __init__(self, constructor: t.Callable[[], T]) -> None:
282 self._constructor = constructor
283 self._created = False
284 self._instance = None
285
286 def __call__(self) -> T:
287 if self._created and self._instance is not None:
288 return self._instance
289
290 with _BINDING_LOCK:
291 if self._created and self._instance is not None:
292 return self._instance
293 self._instance = self._constructor()
294 self._created = True
295 return self._instance
296
297
298 # NOTE(pyctrl): we MUST inherit `_AttributeInjection` from `property`
299 # 0. (personal opinion, based on a bunch of cases including this one)
300 # dataclasses are mess
301 # 1. dataclasses treat all non-`property` descriptors by the very specific logic
302 # https://docs.python.org/3/library/dataclasses.html#descriptor-typed-fields
303 # 2. and treat `property` descriptors in a special way — like we used to know:
304 # ```
305 # @dataclass
306 # class MyDataclass:
307 # @property
308 # def my_prop(self) -> int:
309 # return 42
310 # MyDataclass.my_prop # gives '<property at 0x73055337f150>' on class
311 # MyDataclass().my_prop # and on instance will show you '42'
312 # ```
313 # it behaves the same in the case of alternative notation:
314 # ```
315 # @dataclass
316 # class MyDataclass2:
317 # my_prop = property(fget=lambda _: 42)
318 # MyDataclass2.my_prop # gives '<property at 0x73055337ec00>' on class
319 # MyDataclass2().my_prop # and on instance will show you '42'
320 # ```
321 # which is more relevant to the `inject.attr` case
322 # 3. but the behavior around `property`-ies has an exception
323 # - you can't annotate `property` attribute when using the second notation
324 # (this one `my_prop: int = property(fget=lambda _: 42)` will fail)
325 # - so the type hinting the very matters
326 # - in this case dataclasses don't treat class member as property
327 # (even if it's inherited from `property` or used directly)
328 # - dataclasses behave greedy when discover their attributes
329 # and class member annotations are "must have" markers
330 # 4. so for `inject.attr`s case we should follow 2 rules:
331 # - `attr` implementation is inherited from `property`
332 # - `attr` class member is not annotated
333 class _AttributeInjection(property):
334 def __init__(self, cls: type[T] | t.Hashable) -> None:
335 self._cls = cls
336 super().__init__(
337 fget=lambda _: instance(self._cls),
338 doc="Return an attribute injection",
339 )
340
341 def __set_name__(self, owner: type[T], name: str) -> None:
342 if self._cls is _MISSING:
343 self._cls = _unwrap_cls_annotation(owner, name)
344
345
346 class _ParameterInjection(t.Generic[T]):
347 __slots__ = ("_cls", "_name")
348
349 def __init__(self, name: str, cls: Binding | None = None) -> None:
350 self._name = name
351 self._cls = cls
352
353 def __call__(
354 self, func: t.Callable[..., T | t.Awaitable[T]]
355 ) -> t.Callable[..., T | t.Awaitable[T]]:
356 if inspect.iscoroutinefunction(func):
357
358 @functools.wraps(func)
359 async def async_injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
360 if self._name not in kwargs:
361 kwargs[self._name] = instance(self._cls or self._name)
362 async_func = t.cast("t.Callable[..., t.Awaitable[T]]", func)
363 return await async_func(*args, **kwargs)
364
365 return async_injection_wrapper
366
367 @functools.wraps(func)
368 def injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
369 if self._name not in kwargs:
370 kwargs[self._name] = instance(self._cls or self._name)
371 sync_func = t.cast("t.Callable[..., T]", func)
372 return sync_func(*args, **kwargs)
373
374 return injection_wrapper
375
376
377 class _ParametersInjection(t.Generic[T]):
378 __slots__ = ("_params",)
379
380 def __init__(self, **kwargs: Binding) -> None:
381 self._params = kwargs
382
383 @staticmethod
384 def _aggregate_sync_stack(
385 sync_stack: contextlib.ExitStack,
386 provided_params: frozenset[str],
387 kwargs: dict[str, t.Any],
388 ) -> None:
389 """
390 Manage context stack.
391
392 Extracts context managers, aggregate them in an ExitStack
393 and swap out the param value with results of running `__enter__()`.
394 The result is equivalent to using `with` multiple times.
395 """
396 executed_kwargs = {
397 param: sync_stack.enter_context(inst)
398 for param, inst in kwargs.items()
399 if param not in provided_params
400 and isinstance(inst, contextlib.AbstractContextManager)
401 }
402 kwargs.update(executed_kwargs)
403
404 @staticmethod
405 async def _aggregate_async_stack(
406 async_stack: contextlib.AsyncExitStack,
407 provided_params: frozenset[str],
408 kwargs: dict[str, t.Any],
409 ) -> None:
410 """Similar to _aggregate_sync_stack, but for async context managers."""
411 executed_kwargs = {
412 param: await async_stack.enter_async_context(inst)
413 for param, inst in kwargs.items()
414 if param not in provided_params
415 and isinstance(inst, contextlib.AbstractAsyncContextManager)
416 }
417 kwargs.update(executed_kwargs)
418
419 def __call__(
420 self, func: t.Callable[..., t.Awaitable[T] | T]
421 ) -> t.Callable[..., t.Awaitable[T] | T]:
422 arg_names = inspect.getfullargspec(func).args
423 params_to_provide = self._params
424
425 if inspect.iscoroutinefunction(func):
426
427 @functools.wraps(func)
428 async def async_injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
429 provided_params = frozenset(arg_names[: len(args)]) | frozenset(
430 kwargs.keys()
431 )
432 for param, cls in params_to_provide.items():
433 if param not in provided_params:
434 kwargs[param] = instance(cls)
435 async_func = t.cast("t.Callable[..., t.Awaitable[T]]", func)
436 try:
437 with contextlib.ExitStack() as sync_stack:
438 async with contextlib.AsyncExitStack() as async_stack:
439 self._aggregate_sync_stack(
440 sync_stack, provided_params, kwargs
441 )
442 await self._aggregate_async_stack(
443 async_stack, provided_params, kwargs
444 )
445 return await async_func(*args, **kwargs)
446 except TypeError as previous_error:
447 raise ConstructorTypeError(func, previous_error) # noqa: B904
448
449 return async_injection_wrapper
450
451 @functools.wraps(func)
452 def injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
453 provided_params = frozenset(arg_names[: len(args)]) | frozenset(
454 kwargs.keys()
455 )
456 for param, cls in params_to_provide.items():
457 if param not in provided_params:
458 kwargs[param] = instance(cls)
459 sync_func = t.cast("t.Callable[..., T]", func)
460 try:
461 with contextlib.ExitStack() as sync_stack:
462 self._aggregate_sync_stack(sync_stack, provided_params, kwargs)
463 return sync_func(*args, **kwargs)
464 except TypeError as previous_error:
465 raise ConstructorTypeError(func, previous_error) # noqa: B904
466
467 return injection_wrapper
468
469
470 def configure(
471 config: BinderCallable | None = None,
472 # TODO(pyctrl): force following flags to be kwargs
473 bind_in_runtime: bool = True, # noqa: FBT001, FBT002
474 allow_override: bool = False, # noqa: FBT001, FBT002
475 clear: bool = False, # noqa: FBT001, FBT002
476 once: bool = False, # noqa: FBT001, FBT002
477 ) -> Injector:
478 """
479 Create an injector using callable config.
480
481 Raises:
482 InjectorException: if already configured.
483
484 """
485 global _INJECTOR # noqa: PLW0603
486
487 if clear and once:
488 msg = "clear and once are mutually exclusive, only one can be True"
489 raise InjectorException(msg)
490
491 with _INJECTOR_LOCK:
492 if _INJECTOR:
493 if clear:
494 _clear_injector()
495 elif once:
496 return _INJECTOR
497 else:
498 raise InjectorException("Injector is already configured")
499
500 _INJECTOR = Injector(
501 config,
502 bind_in_runtime=bind_in_runtime,
503 allow_override=allow_override,
504 )
505 logger.debug("Created and configured an injector, config=%s", config)
506 return _INJECTOR
507
508
509 def configure_once(
510 config: BinderCallable | None = None,
511 # TODO(pyctrl): force following flags to be kwargs
512 bind_in_runtime: bool = True, # noqa: FBT001, FBT002
513 allow_override: bool = False, # noqa: FBT001, FBT002
514 ) -> Injector:
515 """
516 Create an injector with a callable config if not present, otherwise, do nothing.
517
518 Deprecated, use `configure(once=True)` instead.
519 """
520 with _INJECTOR_LOCK:
521 if _INJECTOR:
522 return _INJECTOR
523
524 return configure(
525 config, bind_in_runtime=bind_in_runtime, allow_override=allow_override
526 )
527
528
529 def clear_and_configure(
530 config: BinderCallable | None = None,
531 # TODO(pyctrl): force following flags to be kwargs
532 bind_in_runtime: bool = True, # noqa: FBT001, FBT002
533 allow_override: bool = False, # noqa: FBT001, FBT002
534 ) -> Injector:
535 """
536 Clear an existing injector and create another one with a callable config.
537
538 Deprecated, use configure(clear=True) instead.
539 """
540 with _INJECTOR_LOCK:
541 _clear_injector()
542 return configure(
543 config,
544 bind_in_runtime=bind_in_runtime,
545 allow_override=allow_override,
546 )
547
548
549 def is_configured() -> bool:
550 """Return true if an injector is already configured."""
551 with _INJECTOR_LOCK:
552 return _INJECTOR is not None
553
554
555 def clear() -> None:
556 """Clear an existing injector if present."""
557 _clear_injector()
558
559
560 def _clear_injector() -> None:
561 """Clear an existing injector if present."""
562 global _INJECTOR # noqa: PLW0603
563
564 with _INJECTOR_LOCK:
565 if _INJECTOR is None:
566 return
567
568 _INJECTOR = None
569 logger.debug("Cleared an injector")
570
571
572 @t.overload
573 def instance(cls: type[T]) -> T: ...
574
575
576 @t.overload
577 def instance(cls: t.Hashable) -> Injectable: ...
578
579
580 def instance(cls: Binding) -> Injectable:
581 """Inject an instance of a class."""
582 return get_injector_or_die().get_instance(cls)
583
584
585 @t.overload
586 def attr() -> Injectable: ...
587
588
589 @t.overload
590 def attr(cls: type[T]) -> T: ...
591
592
593 @t.overload
594 def attr(cls: t.Hashable) -> Injectable: ...
595
596
597 def attr(cls: type[T] | t.Hashable = _MISSING) -> Injectable:
598 """Return an attribute injection (descriptor)."""
599 return _AttributeInjection(cls)
600
601
602 # Deprecated, use `attr`
603 attr_dc = attr
604
605
606 def param(name: str, cls: Binding | None = None) -> _InjectionDecorator:
607 """
608 Return a decorator which injects an arg into a function.
609
610 Deprecated, use @inject.params.
611 """
612 return _ParameterInjection(name, cls)
613
614
615 def params(**args_to_classes: Binding) -> _InjectionDecorator:
616 """
617 Return a decorator which injects args into a function.
618
619 For example::
620
621 @inject.params(cache=RedisCache, db=DbInterface)
622 def sign_up(name, email, cache, db):
623 pass
624 """
625 return _ParametersInjection(**args_to_classes)
626
627
628 @t.overload
629 def autoparams(fn: t.Callable[P, T], /) -> t.Callable[P, T]: ...
630
631
632 @t.overload
633 def autoparams(*selected: str) -> t.Callable[[T], T]: ...
634
635
636 def autoparams(*selected: t.Callable[..., t.Any] | str) -> t.Callable[..., t.Any]:
637 """
638 Return a decorator injecting args based on function type hints.
639
640 For example::
641
642 @inject.autoparams
643 def refresh_cache(cache: RedisCache, db: DbInterface):
644 pass
645
646 There is an option to specify which arguments we want to
647 inject without attempts of injecting everything:
648
649 For example::
650
651 @inject.autoparams('cache', 'db')
652 def sign_up(name, email, cache: RedisCache, db: DbInterface):
653 pass
654 """
655 only_these: set[str] = set()
656
657 def autoparams_decorator(
658 fn: t.Callable[..., T],
659 ) -> t.Callable[..., t.Awaitable[T] | T]:
660 if inspect.isclass(fn):
661 types = t.get_type_hints(fn.__init__)
662 else:
663 types = t.get_type_hints(fn)
664
665 # Skip the return annotation.
666 types = {name: typ for name, typ in types.items() if name != _RETURN}
667
668 # Convert Union types into single types, i.e. Union[A, None] => A.
669 types = {name: _unwrap_union_arg(typ) for name, typ in types.items()}
670
671 # Filter types if selected args present.
672 if only_these:
673 types = {name: typ for name, typ in types.items() if name in only_these}
674
675 wrapper: _ParametersInjection[T] = _ParametersInjection(**types)
676 return wrapper(fn)
677
678 target = selected[0] if selected else None
679 if len(selected) == 1 and callable(target):
680 return autoparams_decorator(target)
681
682 only_these.update(s for s in selected if isinstance(s, str))
683 return autoparams_decorator
684
685
686 def get_injector() -> Injector | None:
687 """Return the current injector or None."""
688 return _INJECTOR
689
690
691 def get_injector_or_die() -> Injector:
692 """
693 Return the current injector or raise an InjectorException.
694
695 Returns:
696 Configured injector.
697
698 Raises:
699 InjectorException: If injector is not configured.
700
701 """
702 injector = _INJECTOR
703 if not injector:
704 raise InjectorException("No injector is configured")
705
706 return injector
707
708
709 def _unwrap_union_arg(typ: type) -> type:
710 """Return the first type A in typing.Union[A, B] or typ if not Union."""
711 if not _is_union_type(typ):
712 return typ
713 args: tuple[type, ...] = t.get_args(typ)
714 return args[0]
715
716
717 def _is_union_type(typ: object) -> bool:
718 """
719 Test if the type is a union type.
720
721 Examples::
722 is_union_type(int) == False
723 is_union_type(Union) == True
724 is_union_type(Union[int, int]) == False
725 is_union_type(Union[T, int]) == True
726 """
727 return typ is t.Union or isinstance(typ, UnionType) or t.get_origin(typ) is t.Union
728
729
730 def _unwrap_cls_annotation(cls: type, attr_name: str) -> type:
731 types = t.get_type_hints(cls)
732 try:
733 attr_type = types[attr_name]
734 except KeyError:
735 msg = f"Couldn't find type annotation for {attr_name}"
736 raise InjectorException(msg) from None
737
738 return _unwrap_union_arg(attr_type)