2020-10-09 22:16:27 +03:00
|
|
|
"""Wiring module."""
|
|
|
|
|
2021-01-11 03:26:15 +03:00
|
|
|
import asyncio
|
2020-10-09 22:16:27 +03:00
|
|
|
import functools
|
|
|
|
import inspect
|
2020-11-05 20:20:09 +03:00
|
|
|
import importlib
|
2021-01-29 03:49:24 +03:00
|
|
|
import importlib.machinery
|
2020-10-09 22:16:27 +03:00
|
|
|
import pkgutil
|
2021-11-01 04:00:28 +03:00
|
|
|
import warnings
|
2020-10-09 22:16:27 +03:00
|
|
|
import sys
|
|
|
|
from types import ModuleType
|
2020-11-16 00:06:42 +03:00
|
|
|
from typing import (
|
|
|
|
Optional,
|
|
|
|
Iterable,
|
|
|
|
Iterator,
|
|
|
|
Callable,
|
|
|
|
Any,
|
|
|
|
Tuple,
|
|
|
|
Dict,
|
|
|
|
Generic,
|
|
|
|
TypeVar,
|
|
|
|
Type,
|
2021-01-11 16:18:02 +03:00
|
|
|
Union,
|
2021-03-01 05:07:50 +03:00
|
|
|
Set,
|
2020-11-16 00:06:42 +03:00
|
|
|
cast,
|
|
|
|
)
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
if sys.version_info < (3, 7):
|
|
|
|
from typing import GenericMeta
|
|
|
|
else:
|
|
|
|
class GenericMeta(type):
|
|
|
|
...
|
|
|
|
|
2021-01-19 04:49:56 +03:00
|
|
|
# Hotfix, see: https://github.com/ets-labs/python-dependency-injector/issues/362
|
|
|
|
if sys.version_info >= (3, 9):
|
|
|
|
from types import GenericAlias
|
|
|
|
else:
|
|
|
|
GenericAlias = None
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2020-11-18 07:44:32 +03:00
|
|
|
try:
|
2021-02-27 17:45:49 +03:00
|
|
|
import fastapi.params
|
2020-11-18 07:44:32 +03:00
|
|
|
except ImportError:
|
2021-02-27 17:45:49 +03:00
|
|
|
fastapi = None
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
import starlette.requests
|
|
|
|
except ImportError:
|
|
|
|
starlette = None
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
import werkzeug.local
|
|
|
|
except ImportError:
|
|
|
|
werkzeug = None
|
2020-11-18 07:44:32 +03:00
|
|
|
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
from . import providers
|
|
|
|
|
|
|
|
|
2021-11-01 04:00:28 +03:00
|
|
|
if sys.version_info[:2] == (3, 5):
|
|
|
|
warnings.warn(
|
|
|
|
"Dependency Injector will drop support of Python 3.5 after Jan 1st of 2022. "
|
|
|
|
"This does not mean that there will be any immediate breaking changes, "
|
|
|
|
"but tests will no longer be executed on Python 3.5, and bugs will not be addressed.",
|
|
|
|
category=DeprecationWarning,
|
|
|
|
)
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
__all__ = (
|
2022-01-17 04:32:42 +03:00
|
|
|
"wire",
|
|
|
|
"unwire",
|
|
|
|
"inject",
|
|
|
|
"as_int",
|
|
|
|
"as_float",
|
|
|
|
"as_",
|
|
|
|
"required",
|
|
|
|
"invariant",
|
|
|
|
"provided",
|
|
|
|
"Provide",
|
|
|
|
"Provider",
|
|
|
|
"Closing",
|
|
|
|
"register_loader_containers",
|
|
|
|
"unregister_loader_containers",
|
|
|
|
"install_loader",
|
|
|
|
"uninstall_loader",
|
|
|
|
"is_loader_installed",
|
2020-10-09 22:16:27 +03:00
|
|
|
)
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
T = TypeVar("T")
|
|
|
|
F = TypeVar("F", bound=Callable[..., Any])
|
2020-10-09 22:16:27 +03:00
|
|
|
Container = Any
|
|
|
|
|
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
class PatchedRegistry:
|
2020-11-16 00:06:42 +03:00
|
|
|
|
|
|
|
def __init__(self):
|
2021-03-01 05:07:50 +03:00
|
|
|
self._callables: Set[Callable[..., Any]] = set()
|
|
|
|
self._attributes: Set[PatchedAttribute] = set()
|
2020-11-16 00:06:42 +03:00
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
def add_callable(self, patched: Callable[..., Any]) -> None:
|
|
|
|
self._callables.add(patched)
|
2020-11-16 00:06:42 +03:00
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
def get_callables_from_module(self, module: ModuleType) -> Iterator[Callable[..., Any]]:
|
|
|
|
for patched in self._callables:
|
2020-11-16 00:06:42 +03:00
|
|
|
if patched.__module__ != module.__name__:
|
|
|
|
continue
|
|
|
|
yield patched
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
def add_attribute(self, patched: "PatchedAttribute"):
|
2021-03-01 05:07:50 +03:00
|
|
|
self._attributes.add(patched)
|
2020-11-16 00:06:42 +03:00
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
def get_attributes_from_module(self, module: ModuleType) -> Iterator["PatchedAttribute"]:
|
2021-03-01 05:07:50 +03:00
|
|
|
for attribute in self._attributes:
|
|
|
|
if not attribute.is_in_module(module):
|
|
|
|
continue
|
|
|
|
yield attribute
|
|
|
|
|
|
|
|
def clear_module_attributes(self, module: ModuleType):
|
|
|
|
for attribute in self._attributes.copy():
|
|
|
|
if not attribute.is_in_module(module):
|
|
|
|
continue
|
|
|
|
self._attributes.remove(attribute)
|
|
|
|
|
|
|
|
|
|
|
|
class PatchedAttribute:
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
def __init__(self, member: Any, name: str, marker: "_Marker"):
|
2021-03-01 05:07:50 +03:00
|
|
|
self.member = member
|
|
|
|
self.name = name
|
|
|
|
self.marker = marker
|
|
|
|
|
|
|
|
@property
|
|
|
|
def module_name(self) -> str:
|
|
|
|
if isinstance(self.member, ModuleType):
|
|
|
|
return self.member.__name__
|
|
|
|
else:
|
|
|
|
return self.member.__module__
|
|
|
|
|
|
|
|
def is_in_module(self, module: ModuleType) -> bool:
|
|
|
|
return self.module_name == module.__name__
|
2020-11-16 00:06:42 +03:00
|
|
|
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
class ProvidersMap:
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
CONTAINER_STRING_ID = "<container>"
|
2021-02-21 18:34:28 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
def __init__(self, container):
|
|
|
|
self._container = container
|
|
|
|
self._map = self._create_providers_map(
|
2021-01-11 16:18:02 +03:00
|
|
|
current_container=container,
|
2021-02-21 18:34:28 +03:00
|
|
|
original_container=(
|
|
|
|
container.declarative_parent
|
|
|
|
if container.declarative_parent
|
|
|
|
else container
|
|
|
|
),
|
2020-10-09 22:16:27 +03:00
|
|
|
)
|
|
|
|
|
2020-10-28 20:50:51 +03:00
|
|
|
def resolve_provider(
|
|
|
|
self,
|
2021-02-21 18:34:28 +03:00
|
|
|
provider: Union[providers.Provider, str],
|
2022-01-17 04:32:42 +03:00
|
|
|
modifier: Optional["Modifier"] = None,
|
2020-10-28 20:50:51 +03:00
|
|
|
) -> Optional[providers.Provider]:
|
2020-10-09 22:16:27 +03:00
|
|
|
if isinstance(provider, providers.Delegate):
|
|
|
|
return self._resolve_delegate(provider)
|
2021-02-27 17:45:49 +03:00
|
|
|
elif isinstance(provider, (
|
2020-10-09 22:16:27 +03:00
|
|
|
providers.ProvidedInstance,
|
|
|
|
providers.AttributeGetter,
|
|
|
|
providers.ItemGetter,
|
|
|
|
providers.MethodCaller,
|
|
|
|
)):
|
|
|
|
return self._resolve_provided_instance(provider)
|
2021-02-27 17:45:49 +03:00
|
|
|
elif isinstance(provider, providers.ConfigurationOption):
|
2020-10-09 22:16:27 +03:00
|
|
|
return self._resolve_config_option(provider)
|
2021-02-27 17:45:49 +03:00
|
|
|
elif isinstance(provider, providers.TypedConfigurationOption):
|
2020-10-09 22:16:27 +03:00
|
|
|
return self._resolve_config_option(provider.option, as_=provider.provides)
|
2021-02-27 17:45:49 +03:00
|
|
|
elif isinstance(provider, str):
|
2021-02-21 18:34:28 +03:00
|
|
|
return self._resolve_string_id(provider, modifier)
|
2021-02-27 17:45:49 +03:00
|
|
|
else:
|
|
|
|
return self._resolve_provider(provider)
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2021-02-21 18:34:28 +03:00
|
|
|
def _resolve_string_id(
|
2020-10-28 20:50:51 +03:00
|
|
|
self,
|
2021-02-21 18:34:28 +03:00
|
|
|
id: str,
|
2022-01-17 04:32:42 +03:00
|
|
|
modifier: Optional["Modifier"] = None,
|
2020-10-28 20:50:51 +03:00
|
|
|
) -> Optional[providers.Provider]:
|
2021-02-21 18:34:28 +03:00
|
|
|
if id == self.CONTAINER_STRING_ID:
|
|
|
|
return self._container.__self__
|
|
|
|
|
|
|
|
provider = self._container
|
2022-01-17 04:32:42 +03:00
|
|
|
for segment in id.split("."):
|
2021-02-21 18:34:28 +03:00
|
|
|
try:
|
|
|
|
provider = getattr(provider, segment)
|
|
|
|
except AttributeError:
|
|
|
|
return None
|
|
|
|
|
|
|
|
if modifier:
|
|
|
|
provider = modifier.modify(provider, providers_map=self)
|
|
|
|
return provider
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2020-10-28 20:50:51 +03:00
|
|
|
def _resolve_provided_instance(
|
|
|
|
self,
|
|
|
|
original: providers.Provider,
|
|
|
|
) -> Optional[providers.Provider]:
|
2020-10-09 22:16:27 +03:00
|
|
|
modifiers = []
|
|
|
|
while isinstance(original, (
|
|
|
|
providers.ProvidedInstance,
|
|
|
|
providers.AttributeGetter,
|
|
|
|
providers.ItemGetter,
|
|
|
|
providers.MethodCaller,
|
|
|
|
)):
|
|
|
|
modifiers.insert(0, original)
|
|
|
|
original = original.provides
|
|
|
|
|
|
|
|
new = self._resolve_provider(original)
|
2020-10-28 20:44:11 +03:00
|
|
|
if new is None:
|
|
|
|
return None
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
for modifier in modifiers:
|
|
|
|
if isinstance(modifier, providers.ProvidedInstance):
|
|
|
|
new = new.provided
|
|
|
|
elif isinstance(modifier, providers.AttributeGetter):
|
|
|
|
new = getattr(new, modifier.name)
|
|
|
|
elif isinstance(modifier, providers.ItemGetter):
|
|
|
|
new = new[modifier.name]
|
|
|
|
elif isinstance(modifier, providers.MethodCaller):
|
|
|
|
new = new.call(
|
|
|
|
*modifier.args,
|
|
|
|
**modifier.kwargs,
|
|
|
|
)
|
|
|
|
|
|
|
|
return new
|
|
|
|
|
2021-02-21 18:34:28 +03:00
|
|
|
def _resolve_delegate(
|
|
|
|
self,
|
|
|
|
original: providers.Delegate,
|
|
|
|
) -> Optional[providers.Provider]:
|
2021-09-25 22:36:48 +03:00
|
|
|
provider = self._resolve_provider(original.provides)
|
|
|
|
if provider:
|
|
|
|
provider = provider.provider
|
|
|
|
return provider
|
2021-02-21 18:34:28 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
def _resolve_config_option(
|
|
|
|
self,
|
|
|
|
original: providers.ConfigurationOption,
|
|
|
|
as_: Any = None,
|
2020-10-28 20:44:11 +03:00
|
|
|
) -> Optional[providers.Provider]:
|
2020-10-09 22:16:27 +03:00
|
|
|
original_root = original.root
|
|
|
|
new = self._resolve_provider(original_root)
|
2020-10-28 20:44:11 +03:00
|
|
|
if new is None:
|
|
|
|
return None
|
2020-10-09 22:16:27 +03:00
|
|
|
new = cast(providers.Configuration, new)
|
|
|
|
|
|
|
|
for segment in original.get_name_segments():
|
|
|
|
if providers.is_provider(segment):
|
|
|
|
segment = self.resolve_provider(segment)
|
|
|
|
new = new[segment]
|
|
|
|
else:
|
|
|
|
new = getattr(new, segment)
|
|
|
|
|
2021-01-16 16:53:40 +03:00
|
|
|
if original.is_required():
|
|
|
|
new = new.required()
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
if as_:
|
|
|
|
new = new.as_(as_)
|
|
|
|
|
|
|
|
return new
|
|
|
|
|
2020-10-28 20:50:51 +03:00
|
|
|
def _resolve_provider(
|
|
|
|
self,
|
|
|
|
original: providers.Provider,
|
|
|
|
) -> Optional[providers.Provider]:
|
2020-10-09 22:16:27 +03:00
|
|
|
try:
|
|
|
|
return self._map[original]
|
|
|
|
except KeyError:
|
2021-02-21 18:34:28 +03:00
|
|
|
return None
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _create_providers_map(
|
|
|
|
cls,
|
2021-01-11 16:18:02 +03:00
|
|
|
current_container: Container,
|
|
|
|
original_container: Container,
|
2020-10-09 22:16:27 +03:00
|
|
|
) -> Dict[providers.Provider, providers.Provider]:
|
2021-01-11 16:18:02 +03:00
|
|
|
current_providers = current_container.providers
|
2022-01-17 04:32:42 +03:00
|
|
|
current_providers["__self__"] = current_container.__self__
|
2021-01-11 16:18:02 +03:00
|
|
|
|
|
|
|
original_providers = original_container.providers
|
2022-01-17 04:32:42 +03:00
|
|
|
original_providers["__self__"] = original_container.__self__
|
2021-01-11 16:18:02 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
providers_map = {}
|
|
|
|
for provider_name, current_provider in current_providers.items():
|
|
|
|
original_provider = original_providers[provider_name]
|
|
|
|
providers_map[original_provider] = current_provider
|
|
|
|
|
|
|
|
if isinstance(current_provider, providers.Container) \
|
|
|
|
and isinstance(original_provider, providers.Container):
|
|
|
|
subcontainer_map = cls._create_providers_map(
|
2021-01-11 16:18:02 +03:00
|
|
|
current_container=current_provider.container,
|
|
|
|
original_container=original_provider.container,
|
2020-10-09 22:16:27 +03:00
|
|
|
)
|
|
|
|
providers_map.update(subcontainer_map)
|
|
|
|
|
|
|
|
return providers_map
|
|
|
|
|
|
|
|
|
2021-02-27 17:45:49 +03:00
|
|
|
class InspectFilter:
|
|
|
|
|
|
|
|
def is_excluded(self, instance: object) -> bool:
|
|
|
|
if self._is_werkzeug_local_proxy(instance):
|
|
|
|
return True
|
|
|
|
elif self._is_starlette_request_cls(instance):
|
|
|
|
return True
|
2021-03-09 00:32:34 +03:00
|
|
|
elif self._is_builtin(instance):
|
|
|
|
return True
|
2021-02-27 17:45:49 +03:00
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def _is_werkzeug_local_proxy(self, instance: object) -> bool:
|
|
|
|
return werkzeug and isinstance(instance, werkzeug.local.LocalProxy)
|
|
|
|
|
|
|
|
def _is_starlette_request_cls(self, instance: object) -> bool:
|
|
|
|
return starlette \
|
|
|
|
and isinstance(instance, type) \
|
2022-03-27 21:18:46 +03:00
|
|
|
and _safe_is_subclass(instance, starlette.requests.Request)
|
2021-02-27 17:45:49 +03:00
|
|
|
|
2021-03-09 00:32:34 +03:00
|
|
|
def _is_builtin(self, instance: object) -> bool:
|
|
|
|
return inspect.isbuiltin(instance)
|
|
|
|
|
2021-02-27 17:45:49 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
def wire( # noqa: C901
|
2020-10-09 22:16:27 +03:00
|
|
|
container: Container,
|
|
|
|
*,
|
|
|
|
modules: Optional[Iterable[ModuleType]] = None,
|
|
|
|
packages: Optional[Iterable[ModuleType]] = None,
|
|
|
|
) -> None:
|
|
|
|
"""Wire container providers with provided packages and modules."""
|
2021-09-30 22:03:19 +03:00
|
|
|
modules = [*modules] if modules else []
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
if packages:
|
|
|
|
for package in packages:
|
|
|
|
modules.extend(_fetch_modules(package))
|
|
|
|
|
|
|
|
providers_map = ProvidersMap(container)
|
|
|
|
|
|
|
|
for module in modules:
|
2021-03-01 05:07:50 +03:00
|
|
|
for member_name, member in inspect.getmembers(module):
|
|
|
|
if _inspect_filter.is_excluded(member):
|
2021-02-27 17:45:49 +03:00
|
|
|
continue
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
if _is_marker(member):
|
|
|
|
_patch_attribute(module, member_name, member, providers_map)
|
|
|
|
elif inspect.isfunction(member):
|
|
|
|
_patch_fn(module, member_name, member, providers_map)
|
|
|
|
elif inspect.isclass(member):
|
|
|
|
cls = member
|
2021-04-27 05:07:48 +03:00
|
|
|
try:
|
|
|
|
cls_members = inspect.getmembers(cls)
|
|
|
|
except Exception: # noqa
|
|
|
|
# Hotfix, see: https://github.com/ets-labs/python-dependency-injector/issues/441
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
for cls_member_name, cls_member in cls_members:
|
|
|
|
if _is_marker(cls_member):
|
|
|
|
_patch_attribute(cls, cls_member_name, cls_member, providers_map)
|
|
|
|
elif _is_method(cls_member):
|
|
|
|
_patch_method(cls, cls_member_name, cls_member, providers_map)
|
2021-03-01 05:07:50 +03:00
|
|
|
|
|
|
|
for patched in _patched_registry.get_callables_from_module(module):
|
2020-11-16 00:06:42 +03:00
|
|
|
_bind_injections(patched, providers_map)
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
def unwire( # noqa: C901
|
2020-10-09 22:16:27 +03:00
|
|
|
*,
|
|
|
|
modules: Optional[Iterable[ModuleType]] = None,
|
|
|
|
packages: Optional[Iterable[ModuleType]] = None,
|
|
|
|
) -> None:
|
|
|
|
"""Wire provided packages and modules with previous wired providers."""
|
2021-09-30 22:03:19 +03:00
|
|
|
modules = [*modules] if modules else []
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
if packages:
|
|
|
|
for package in packages:
|
|
|
|
modules.extend(_fetch_modules(package))
|
|
|
|
|
|
|
|
for module in modules:
|
|
|
|
for name, member in inspect.getmembers(module):
|
|
|
|
if inspect.isfunction(member):
|
2020-11-03 23:59:02 +03:00
|
|
|
_unpatch(module, name, member)
|
2020-10-09 22:16:27 +03:00
|
|
|
elif inspect.isclass(member):
|
|
|
|
for method_name, method in inspect.getmembers(member, inspect.isfunction):
|
2020-11-03 23:59:02 +03:00
|
|
|
_unpatch(member, method_name, method)
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
for patched in _patched_registry.get_callables_from_module(module):
|
2020-11-16 00:06:42 +03:00
|
|
|
_unbind_injections(patched)
|
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
for patched_attribute in _patched_registry.get_attributes_from_module(module):
|
|
|
|
_unpatch_attribute(patched_attribute)
|
|
|
|
_patched_registry.clear_module_attributes(module)
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
|
|
|
|
def inject(fn: F) -> F:
|
|
|
|
"""Decorate callable with injecting decorator."""
|
|
|
|
reference_injections, reference_closing = _fetch_reference_injections(fn)
|
|
|
|
patched = _get_patched(fn, reference_injections, reference_closing)
|
2021-03-01 05:07:50 +03:00
|
|
|
_patched_registry.add_callable(patched)
|
2020-11-16 00:06:42 +03:00
|
|
|
return cast(F, patched)
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
def _patch_fn(
|
|
|
|
module: ModuleType,
|
|
|
|
name: str,
|
|
|
|
fn: Callable[..., Any],
|
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> None:
|
2020-11-16 00:06:42 +03:00
|
|
|
if not _is_patched(fn):
|
|
|
|
reference_injections, reference_closing = _fetch_reference_injections(fn)
|
|
|
|
if not reference_injections:
|
|
|
|
return
|
|
|
|
fn = _get_patched(fn, reference_injections, reference_closing)
|
2021-03-01 05:07:50 +03:00
|
|
|
_patched_registry.add_callable(fn)
|
2020-11-16 00:06:42 +03:00
|
|
|
|
|
|
|
_bind_injections(fn, providers_map)
|
|
|
|
|
|
|
|
setattr(module, name, fn)
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
|
2020-11-03 23:59:02 +03:00
|
|
|
def _patch_method(
|
|
|
|
cls: Type,
|
|
|
|
name: str,
|
|
|
|
method: Callable[..., Any],
|
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> None:
|
2022-01-17 04:32:42 +03:00
|
|
|
if hasattr(cls, "__dict__") \
|
2020-11-03 23:59:02 +03:00
|
|
|
and name in cls.__dict__ \
|
|
|
|
and isinstance(cls.__dict__[name], (classmethod, staticmethod)):
|
|
|
|
method = cls.__dict__[name]
|
2020-11-16 00:06:42 +03:00
|
|
|
fn = method.__func__
|
2020-11-03 23:59:02 +03:00
|
|
|
else:
|
2020-11-16 00:06:42 +03:00
|
|
|
fn = method
|
2020-11-03 23:59:02 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
if not _is_patched(fn):
|
|
|
|
reference_injections, reference_closing = _fetch_reference_injections(fn)
|
|
|
|
if not reference_injections:
|
|
|
|
return
|
|
|
|
fn = _get_patched(fn, reference_injections, reference_closing)
|
2021-03-01 05:07:50 +03:00
|
|
|
_patched_registry.add_callable(fn)
|
2020-11-03 23:59:02 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
_bind_injections(fn, providers_map)
|
2020-11-03 23:59:02 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
if isinstance(method, (classmethod, staticmethod)):
|
|
|
|
fn = type(method)(fn)
|
|
|
|
|
|
|
|
setattr(cls, name, fn)
|
2020-11-03 23:59:02 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _unpatch(
|
2020-10-09 22:16:27 +03:00
|
|
|
module: ModuleType,
|
|
|
|
name: str,
|
|
|
|
fn: Callable[..., Any],
|
|
|
|
) -> None:
|
2022-01-17 04:32:42 +03:00
|
|
|
if hasattr(module, "__dict__") \
|
2020-11-16 00:06:42 +03:00
|
|
|
and name in module.__dict__ \
|
|
|
|
and isinstance(module.__dict__[name], (classmethod, staticmethod)):
|
|
|
|
method = module.__dict__[name]
|
|
|
|
fn = method.__func__
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
if not _is_patched(fn):
|
|
|
|
return
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
_unbind_injections(fn)
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
def _patch_attribute(
|
|
|
|
member: Any,
|
|
|
|
name: str,
|
2022-01-17 04:32:42 +03:00
|
|
|
marker: "_Marker",
|
2021-03-01 05:07:50 +03:00
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> None:
|
|
|
|
provider = providers_map.resolve_provider(marker.provider, marker.modifier)
|
|
|
|
if provider is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
_patched_registry.add_attribute(PatchedAttribute(member, name, marker))
|
|
|
|
|
|
|
|
if isinstance(marker, Provide):
|
|
|
|
instance = provider()
|
|
|
|
setattr(member, name, instance)
|
|
|
|
elif isinstance(marker, Provider):
|
|
|
|
setattr(member, name, provider)
|
|
|
|
else:
|
2022-01-17 04:32:42 +03:00
|
|
|
raise Exception(f"Unknown type of marker {marker}")
|
2021-03-01 05:07:50 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _unpatch_attribute(patched: PatchedAttribute) -> None:
|
|
|
|
setattr(patched.member, patched.name, patched.marker)
|
|
|
|
|
|
|
|
|
2021-03-09 00:32:34 +03:00
|
|
|
def _fetch_reference_injections( # noqa: C901
|
2020-10-30 05:55:09 +03:00
|
|
|
fn: Callable[..., Any],
|
2020-10-30 23:40:27 +03:00
|
|
|
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
2021-02-16 01:47:03 +03:00
|
|
|
# Hotfix, see:
|
|
|
|
# - https://github.com/ets-labs/python-dependency-injector/issues/362
|
|
|
|
# - https://github.com/ets-labs/python-dependency-injector/issues/398
|
|
|
|
if GenericAlias and any((
|
|
|
|
fn is GenericAlias,
|
2022-01-17 04:32:42 +03:00
|
|
|
getattr(fn, "__func__", None) is GenericAlias
|
2021-02-16 01:47:03 +03:00
|
|
|
)):
|
2021-01-19 04:49:56 +03:00
|
|
|
fn = fn.__init__
|
|
|
|
|
2021-03-09 00:32:34 +03:00
|
|
|
try:
|
|
|
|
signature = inspect.signature(fn)
|
|
|
|
except ValueError as exception:
|
2022-01-17 04:32:42 +03:00
|
|
|
if "no signature found" in str(exception):
|
2021-03-09 00:32:34 +03:00
|
|
|
return {}, {}
|
2022-01-17 04:32:42 +03:00
|
|
|
elif "not supported by signature" in str(exception):
|
2021-03-09 00:32:34 +03:00
|
|
|
return {}, {}
|
|
|
|
else:
|
|
|
|
raise exception
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
injections = {}
|
2020-10-30 23:40:27 +03:00
|
|
|
closing = {}
|
2020-10-09 22:16:27 +03:00
|
|
|
for parameter_name, parameter in signature.parameters.items():
|
2020-11-18 07:44:32 +03:00
|
|
|
if not isinstance(parameter.default, _Marker) \
|
|
|
|
and not _is_fastapi_depends(parameter.default):
|
2020-10-09 22:16:27 +03:00
|
|
|
continue
|
2020-11-18 07:44:32 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
marker = parameter.default
|
|
|
|
|
2020-11-18 07:44:32 +03:00
|
|
|
if _is_fastapi_depends(marker):
|
|
|
|
marker = marker.dependency
|
|
|
|
|
2020-12-06 05:40:51 +03:00
|
|
|
if not isinstance(marker, _Marker):
|
2020-12-05 04:11:21 +03:00
|
|
|
continue
|
|
|
|
|
2020-10-30 05:55:09 +03:00
|
|
|
if isinstance(marker, Closing):
|
|
|
|
marker = marker.provider
|
2020-11-16 00:06:42 +03:00
|
|
|
closing[parameter_name] = marker
|
2020-10-30 05:55:09 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
injections[parameter_name] = marker
|
|
|
|
return injections, closing
|
|
|
|
|
|
|
|
|
|
|
|
def _bind_injections(fn: Callable[..., Any], providers_map: ProvidersMap) -> None:
|
|
|
|
for injection, marker in fn.__reference_injections__.items():
|
2021-02-21 18:34:28 +03:00
|
|
|
provider = providers_map.resolve_provider(marker.provider, marker.modifier)
|
2020-11-16 00:06:42 +03:00
|
|
|
|
2020-10-28 20:44:11 +03:00
|
|
|
if provider is None:
|
|
|
|
continue
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
if isinstance(marker, Provide):
|
2020-11-16 00:06:42 +03:00
|
|
|
fn.__injections__[injection] = provider
|
2020-10-09 22:16:27 +03:00
|
|
|
elif isinstance(marker, Provider):
|
2021-09-25 22:36:48 +03:00
|
|
|
if isinstance(provider, providers.Delegate):
|
|
|
|
fn.__injections__[injection] = provider
|
|
|
|
else:
|
|
|
|
fn.__injections__[injection] = provider.provider
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
if injection in fn.__reference_closing__:
|
|
|
|
fn.__closing__[injection] = provider
|
|
|
|
|
|
|
|
|
|
|
|
def _unbind_injections(fn: Callable[..., Any]) -> None:
|
|
|
|
fn.__injections__ = {}
|
|
|
|
fn.__closing__ = {}
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _fetch_modules(package):
|
2020-10-21 00:48:54 +03:00
|
|
|
modules = [package]
|
2022-01-17 04:32:42 +03:00
|
|
|
if not hasattr(package, "__path__") or not hasattr(package, "__name__"):
|
2021-08-06 22:56:24 +03:00
|
|
|
return modules
|
2020-11-05 20:20:09 +03:00
|
|
|
for module_info in pkgutil.walk_packages(
|
2020-10-09 22:16:27 +03:00
|
|
|
path=package.__path__,
|
2022-01-17 04:32:42 +03:00
|
|
|
prefix=package.__name__ + ".",
|
2020-10-09 22:16:27 +03:00
|
|
|
):
|
2020-11-05 20:20:09 +03:00
|
|
|
module = importlib.import_module(module_info.name)
|
2020-10-09 22:16:27 +03:00
|
|
|
modules.append(module)
|
|
|
|
return modules
|
|
|
|
|
|
|
|
|
2020-10-28 20:11:07 +03:00
|
|
|
def _is_method(member):
|
|
|
|
return inspect.ismethod(member) or inspect.isfunction(member)
|
|
|
|
|
|
|
|
|
2021-03-01 05:07:50 +03:00
|
|
|
def _is_marker(member):
|
|
|
|
return isinstance(member, _Marker)
|
|
|
|
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
def _get_patched(fn, reference_injections, reference_closing):
|
2020-10-09 22:16:27 +03:00
|
|
|
if inspect.iscoroutinefunction(fn):
|
2020-11-16 00:06:42 +03:00
|
|
|
patched = _get_async_patched(fn)
|
2020-10-09 22:16:27 +03:00
|
|
|
else:
|
2020-11-16 00:06:42 +03:00
|
|
|
patched = _get_sync_patched(fn)
|
|
|
|
|
|
|
|
patched.__wired__ = True
|
|
|
|
patched.__original__ = fn
|
|
|
|
patched.__injections__ = {}
|
|
|
|
patched.__reference_injections__ = reference_injections
|
|
|
|
patched.__closing__ = {}
|
|
|
|
patched.__reference_closing__ = reference_closing
|
|
|
|
|
|
|
|
return patched
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
|
2022-03-28 01:15:54 +03:00
|
|
|
from ._cwiring import _get_sync_patched
|
|
|
|
|
|
|
|
# def _get_sync_patched(fn):
|
|
|
|
# @functools.wraps(fn)
|
|
|
|
# def _patched(*args, **kwargs):
|
|
|
|
# to_inject = kwargs.copy()
|
|
|
|
# for injection, provider in _patched.__injections__.items():
|
|
|
|
# if injection not in kwargs \
|
|
|
|
# or _is_fastapi_default_arg_injection(injection, kwargs):
|
|
|
|
# to_inject[injection] = provider()
|
|
|
|
#
|
|
|
|
# result = fn(*args, **to_inject)
|
|
|
|
#
|
|
|
|
# for injection, provider in _patched.__closing__.items():
|
|
|
|
# if injection in kwargs \
|
|
|
|
# and not _is_fastapi_default_arg_injection(injection, kwargs):
|
|
|
|
# continue
|
|
|
|
# if not isinstance(provider, providers.Resource):
|
|
|
|
# continue
|
|
|
|
# provider.shutdown()
|
|
|
|
#
|
|
|
|
# return result
|
|
|
|
# return _patched
|
2020-10-30 23:47:26 +03:00
|
|
|
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
def _get_async_patched(fn):
|
2020-10-30 23:47:26 +03:00
|
|
|
@functools.wraps(fn)
|
|
|
|
async def _patched(*args, **kwargs):
|
|
|
|
to_inject = kwargs.copy()
|
2021-01-11 03:26:15 +03:00
|
|
|
to_inject_await = []
|
|
|
|
to_close_await = []
|
2020-11-16 00:06:42 +03:00
|
|
|
for injection, provider in _patched.__injections__.items():
|
2020-11-12 23:54:49 +03:00
|
|
|
if injection not in kwargs \
|
|
|
|
or _is_fastapi_default_arg_injection(injection, kwargs):
|
2021-01-11 03:26:15 +03:00
|
|
|
provide = provider()
|
|
|
|
if inspect.isawaitable(provide):
|
|
|
|
to_inject_await.append((injection, provide))
|
|
|
|
else:
|
|
|
|
to_inject[injection] = provide
|
|
|
|
|
|
|
|
async_to_inject = await asyncio.gather(*[provide for _, provide in to_inject_await])
|
|
|
|
for provide, (injection, _) in zip(async_to_inject, to_inject_await):
|
|
|
|
to_inject[injection] = provide
|
2020-10-30 23:47:26 +03:00
|
|
|
|
|
|
|
result = await fn(*args, **to_inject)
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
for injection, provider in _patched.__closing__.items():
|
2020-11-12 23:54:49 +03:00
|
|
|
if injection in kwargs \
|
|
|
|
and not _is_fastapi_default_arg_injection(injection, kwargs):
|
2020-10-30 23:47:26 +03:00
|
|
|
continue
|
|
|
|
if not isinstance(provider, providers.Resource):
|
|
|
|
continue
|
2021-01-11 03:26:15 +03:00
|
|
|
shutdown = provider.shutdown()
|
|
|
|
if inspect.isawaitable(shutdown):
|
|
|
|
to_close_await.append(shutdown)
|
|
|
|
|
|
|
|
await asyncio.gather(*to_close_await)
|
2020-10-30 23:47:26 +03:00
|
|
|
|
|
|
|
return result
|
|
|
|
return _patched
|
|
|
|
|
|
|
|
|
2020-11-12 23:54:49 +03:00
|
|
|
def _is_fastapi_default_arg_injection(injection, kwargs):
|
|
|
|
"""Check if injection is FastAPI injection of the default argument."""
|
|
|
|
return injection in kwargs and isinstance(kwargs[injection], _Marker)
|
|
|
|
|
|
|
|
|
2020-11-18 07:44:32 +03:00
|
|
|
def _is_fastapi_depends(param: Any) -> bool:
|
2021-02-27 17:45:49 +03:00
|
|
|
return fastapi and isinstance(param, fastapi.params.Depends)
|
2020-11-18 07:44:32 +03:00
|
|
|
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
def _is_patched(fn):
|
2022-01-17 04:32:42 +03:00
|
|
|
return getattr(fn, "__wired__", False) is True
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
|
2021-01-11 16:18:02 +03:00
|
|
|
def _is_declarative_container(instance: Any) -> bool:
|
|
|
|
return (isinstance(instance, type)
|
2022-01-17 04:32:42 +03:00
|
|
|
and getattr(instance, "__IS_CONTAINER__", False) is True
|
|
|
|
and getattr(instance, "declarative_parent", None) is None)
|
2021-01-11 16:18:02 +03:00
|
|
|
|
|
|
|
|
2022-03-27 21:18:46 +03:00
|
|
|
def _safe_is_subclass(instance: Any, cls: Type) -> bool:
|
|
|
|
try:
|
|
|
|
return issubclass(instance, cls)
|
|
|
|
except TypeError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2021-02-21 18:34:28 +03:00
|
|
|
class Modifier:
|
|
|
|
|
|
|
|
def modify(
|
|
|
|
self,
|
|
|
|
provider: providers.ConfigurationOption,
|
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> providers.Provider:
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
class TypeModifier(Modifier):
|
|
|
|
|
|
|
|
def __init__(self, type_: Type):
|
|
|
|
self.type_ = type_
|
|
|
|
|
|
|
|
def modify(
|
|
|
|
self,
|
|
|
|
provider: providers.ConfigurationOption,
|
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> providers.Provider:
|
|
|
|
return provider.as_(self.type_)
|
|
|
|
|
|
|
|
|
|
|
|
def as_int() -> TypeModifier:
|
|
|
|
"""Return int type modifier."""
|
|
|
|
return TypeModifier(int)
|
|
|
|
|
|
|
|
|
|
|
|
def as_float() -> TypeModifier:
|
|
|
|
"""Return float type modifier."""
|
|
|
|
return TypeModifier(float)
|
|
|
|
|
|
|
|
|
|
|
|
def as_(type_: Type) -> TypeModifier:
|
|
|
|
"""Return custom type modifier."""
|
|
|
|
return TypeModifier(type_)
|
|
|
|
|
|
|
|
|
|
|
|
class RequiredModifier(Modifier):
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.type_modifier = None
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
def as_int(self) -> "RequiredModifier":
|
2021-02-21 18:34:28 +03:00
|
|
|
self.type_modifier = TypeModifier(int)
|
|
|
|
return self
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
def as_float(self) -> "RequiredModifier":
|
2021-02-21 18:34:28 +03:00
|
|
|
self.type_modifier = TypeModifier(float)
|
|
|
|
return self
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
def as_(self, type_: Type) -> "RequiredModifier":
|
2021-02-21 18:34:28 +03:00
|
|
|
self.type_modifier = TypeModifier(type_)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def modify(
|
|
|
|
self,
|
|
|
|
provider: providers.ConfigurationOption,
|
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> providers.Provider:
|
|
|
|
provider = provider.required()
|
|
|
|
if self.type_modifier:
|
|
|
|
provider = provider.as_(self.type_modifier.type_)
|
|
|
|
return provider
|
|
|
|
|
|
|
|
|
|
|
|
def required() -> RequiredModifier:
|
|
|
|
"""Return required modifier."""
|
|
|
|
return RequiredModifier()
|
|
|
|
|
|
|
|
|
|
|
|
class InvariantModifier(Modifier):
|
|
|
|
|
|
|
|
def __init__(self, id: str) -> None:
|
|
|
|
self.id = id
|
|
|
|
|
|
|
|
def modify(
|
|
|
|
self,
|
|
|
|
provider: providers.ConfigurationOption,
|
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> providers.Provider:
|
|
|
|
invariant_segment = providers_map.resolve_provider(self.id)
|
|
|
|
return provider[invariant_segment]
|
|
|
|
|
|
|
|
|
|
|
|
def invariant(id: str) -> InvariantModifier:
|
|
|
|
"""Return invariant modifier."""
|
|
|
|
return InvariantModifier(id)
|
|
|
|
|
|
|
|
|
|
|
|
class ProvidedInstance(Modifier):
|
|
|
|
|
2022-01-17 04:32:42 +03:00
|
|
|
TYPE_ATTRIBUTE = "attr"
|
|
|
|
TYPE_ITEM = "item"
|
|
|
|
TYPE_CALL = "call"
|
2021-02-21 18:34:28 +03:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.segments = []
|
|
|
|
|
|
|
|
def __getattr__(self, item):
|
|
|
|
self.segments.append((self.TYPE_ATTRIBUTE, item))
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __getitem__(self, item):
|
|
|
|
self.segments.append((self.TYPE_ITEM, item))
|
|
|
|
return self
|
|
|
|
|
|
|
|
def call(self):
|
|
|
|
self.segments.append((self.TYPE_CALL, None))
|
|
|
|
return self
|
|
|
|
|
|
|
|
def modify(
|
|
|
|
self,
|
2021-03-20 20:16:51 +03:00
|
|
|
provider: providers.Provider,
|
2021-02-21 18:34:28 +03:00
|
|
|
providers_map: ProvidersMap,
|
|
|
|
) -> providers.Provider:
|
|
|
|
provider = provider.provided
|
|
|
|
for type_, value in self.segments:
|
|
|
|
if type_ == ProvidedInstance.TYPE_ATTRIBUTE:
|
|
|
|
provider = getattr(provider, value)
|
|
|
|
elif type_ == ProvidedInstance.TYPE_ITEM:
|
|
|
|
provider = provider[value]
|
|
|
|
elif type_ == ProvidedInstance.TYPE_CALL:
|
|
|
|
provider = provider.call()
|
|
|
|
return provider
|
|
|
|
|
|
|
|
|
|
|
|
def provided() -> ProvidedInstance:
|
|
|
|
"""Return provided instance modifier."""
|
|
|
|
return ProvidedInstance()
|
|
|
|
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
class ClassGetItemMeta(GenericMeta):
|
|
|
|
def __getitem__(cls, item):
|
|
|
|
# Spike for Python 3.6
|
2021-02-21 18:34:28 +03:00
|
|
|
if isinstance(item, tuple):
|
|
|
|
return cls(*item)
|
2020-10-09 22:16:27 +03:00
|
|
|
return cls(item)
|
|
|
|
|
|
|
|
|
|
|
|
class _Marker(Generic[T], metaclass=ClassGetItemMeta):
|
|
|
|
|
2022-03-28 01:15:54 +03:00
|
|
|
__IS_MARKER__ = True
|
|
|
|
|
2021-02-21 18:34:28 +03:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
provider: Union[providers.Provider, Container, str],
|
|
|
|
modifier: Optional[Modifier] = None,
|
|
|
|
) -> None:
|
2021-01-11 16:18:02 +03:00
|
|
|
if _is_declarative_container(provider):
|
|
|
|
provider = provider.__self__
|
2021-02-21 18:34:28 +03:00
|
|
|
self.provider = provider
|
|
|
|
self.modifier = modifier
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
def __class_getitem__(cls, item) -> T:
|
2021-02-21 18:34:28 +03:00
|
|
|
if isinstance(item, tuple):
|
|
|
|
return cls(*item)
|
2020-10-09 22:16:27 +03:00
|
|
|
return cls(item)
|
|
|
|
|
2020-11-18 07:44:32 +03:00
|
|
|
def __call__(self) -> T:
|
|
|
|
return self
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
|
|
|
|
class Provide(_Marker):
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
class Provider(_Marker):
|
|
|
|
...
|
2020-10-30 05:55:09 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Closing(_Marker):
|
|
|
|
...
|
2021-01-29 03:49:24 +03:00
|
|
|
|
|
|
|
|
|
|
|
class AutoLoader:
|
|
|
|
"""Auto-wiring module loader.
|
|
|
|
|
|
|
|
Automatically wire containers when modules are imported.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.containers = []
|
|
|
|
self._path_hook = None
|
|
|
|
|
|
|
|
def register_containers(self, *containers):
|
|
|
|
self.containers.extend(containers)
|
|
|
|
|
|
|
|
if not self.installed:
|
|
|
|
self.install()
|
|
|
|
|
|
|
|
def unregister_containers(self, *containers):
|
|
|
|
for container in containers:
|
|
|
|
self.containers.remove(container)
|
|
|
|
|
|
|
|
if not self.containers:
|
|
|
|
self.uninstall()
|
|
|
|
|
|
|
|
def wire_module(self, module):
|
|
|
|
for container in self.containers:
|
|
|
|
container.wire(modules=[module])
|
|
|
|
|
|
|
|
@property
|
|
|
|
def installed(self):
|
2021-03-20 20:16:51 +03:00
|
|
|
return self._path_hook in sys.path_hooks
|
2021-01-29 03:49:24 +03:00
|
|
|
|
|
|
|
def install(self):
|
|
|
|
if self.installed:
|
|
|
|
return
|
|
|
|
|
|
|
|
loader = self
|
|
|
|
|
|
|
|
class SourcelessFileLoader(importlib.machinery.SourcelessFileLoader):
|
|
|
|
def exec_module(self, module):
|
|
|
|
super().exec_module(module)
|
|
|
|
loader.wire_module(module)
|
|
|
|
|
|
|
|
class SourceFileLoader(importlib.machinery.SourceFileLoader):
|
|
|
|
def exec_module(self, module):
|
|
|
|
super().exec_module(module)
|
|
|
|
loader.wire_module(module)
|
|
|
|
|
2021-03-09 00:32:34 +03:00
|
|
|
class ExtensionFileLoader(importlib.machinery.ExtensionFileLoader):
|
|
|
|
...
|
|
|
|
|
2021-01-29 03:49:24 +03:00
|
|
|
loader_details = [
|
|
|
|
(SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES),
|
|
|
|
(SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES),
|
2021-03-09 00:32:34 +03:00
|
|
|
(ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES),
|
2021-01-29 03:49:24 +03:00
|
|
|
]
|
|
|
|
|
|
|
|
self._path_hook = importlib.machinery.FileFinder.path_hook(*loader_details)
|
|
|
|
|
|
|
|
sys.path_hooks.insert(0, self._path_hook)
|
|
|
|
sys.path_importer_cache.clear()
|
|
|
|
importlib.invalidate_caches()
|
|
|
|
|
|
|
|
def uninstall(self):
|
|
|
|
if not self.installed:
|
|
|
|
return
|
|
|
|
|
|
|
|
sys.path_hooks.remove(self._path_hook)
|
|
|
|
sys.path_importer_cache.clear()
|
|
|
|
importlib.invalidate_caches()
|
|
|
|
|
|
|
|
|
|
|
|
def register_loader_containers(*containers: Container) -> None:
|
|
|
|
"""Register containers in auto-wiring module loader."""
|
|
|
|
_loader.register_containers(*containers)
|
|
|
|
|
|
|
|
|
|
|
|
def unregister_loader_containers(*containers: Container) -> None:
|
|
|
|
"""Unregister containers from auto-wiring module loader."""
|
|
|
|
_loader.unregister_containers(*containers)
|
|
|
|
|
|
|
|
|
|
|
|
def install_loader() -> None:
|
|
|
|
"""Install auto-wiring module loader hook."""
|
|
|
|
_loader.install()
|
|
|
|
|
|
|
|
|
|
|
|
def uninstall_loader() -> None:
|
|
|
|
"""Uninstall auto-wiring module loader hook."""
|
|
|
|
_loader.uninstall()
|
|
|
|
|
|
|
|
|
|
|
|
def is_loader_installed() -> bool:
|
|
|
|
"""Check if auto-wiring module loader hook is installed."""
|
|
|
|
return _loader.installed
|
2021-03-01 05:07:50 +03:00
|
|
|
|
|
|
|
|
|
|
|
_patched_registry = PatchedRegistry()
|
|
|
|
_inspect_filter = InspectFilter()
|
|
|
|
_loader = AutoLoader()
|