mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2024-11-22 09:36:48 +03:00
Update quotes in Cython and Python modules
This commit is contained in:
parent
a38ca647c3
commit
8dc3dd2f09
File diff suppressed because it is too large
Load Diff
|
@ -28,10 +28,10 @@ if sys.version_info[:2] >= (3, 6):
|
||||||
from .wiring import wire, unwire
|
from .wiring import wire, unwire
|
||||||
else:
|
else:
|
||||||
def wire(*args, **kwargs):
|
def wire(*args, **kwargs):
|
||||||
raise NotImplementedError('Wiring requires Python 3.6 or above')
|
raise NotImplementedError("Wiring requires Python 3.6 or above")
|
||||||
|
|
||||||
def unwire(*args, **kwargs):
|
def unwire(*args, **kwargs):
|
||||||
raise NotImplementedError('Wiring requires Python 3.6 or above')
|
raise NotImplementedError("Wiring requires Python 3.6 or above")
|
||||||
|
|
||||||
if sys.version_info[:2] == (3, 5):
|
if sys.version_info[:2] == (3, 5):
|
||||||
warnings.warn(
|
warnings.warn(
|
||||||
|
@ -137,17 +137,17 @@ class DynamicContainer(Container):
|
||||||
If value of attribute is provider, it will be added into providers
|
If value of attribute is provider, it will be added into providers
|
||||||
dictionary.
|
dictionary.
|
||||||
|
|
||||||
:param name: Attribute's name
|
:param name: Attribute name
|
||||||
:type name: object
|
:type name: object
|
||||||
|
|
||||||
:param value: Attribute's value
|
:param value: Attribute value
|
||||||
:type value: object
|
:type value: object
|
||||||
|
|
||||||
:rtype: None
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if isinstance(value, providers.Provider) \
|
if isinstance(value, providers.Provider) \
|
||||||
and not isinstance(value, providers.Self) \
|
and not isinstance(value, providers.Self) \
|
||||||
and name != 'parent':
|
and name != "parent":
|
||||||
_check_provider_type(self, value)
|
_check_provider_type(self, value)
|
||||||
|
|
||||||
self.providers[name] = value
|
self.providers[name] = value
|
||||||
|
@ -163,7 +163,7 @@ class DynamicContainer(Container):
|
||||||
If value of attribute is provider, it will be deleted from providers
|
If value of attribute is provider, it will be deleted from providers
|
||||||
dictionary.
|
dictionary.
|
||||||
|
|
||||||
:param name: Attribute's name
|
:param name: Attribute name
|
||||||
:type name: object
|
:type name: object
|
||||||
|
|
||||||
:rtype: None
|
:rtype: None
|
||||||
|
@ -229,8 +229,8 @@ class DynamicContainer(Container):
|
||||||
:rtype: None
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if overriding is self:
|
if overriding is self:
|
||||||
raise errors.Error('Container {0} could not be overridden '
|
raise errors.Error("Container {0} could not be overridden "
|
||||||
'with itself'.format(self))
|
"with itself".format(self))
|
||||||
|
|
||||||
self.overridden += (overriding,)
|
self.overridden += (overriding,)
|
||||||
|
|
||||||
|
@ -262,7 +262,7 @@ class DynamicContainer(Container):
|
||||||
:rtype: None
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if not self.overridden:
|
if not self.overridden:
|
||||||
raise errors.Error('Container {0} is not overridden'.format(self))
|
raise errors.Error("Container {0} is not overridden".format(self))
|
||||||
|
|
||||||
self.overridden = self.overridden[:-1]
|
self.overridden = self.overridden[:-1]
|
||||||
|
|
||||||
|
@ -364,7 +364,7 @@ class DynamicContainer(Container):
|
||||||
while any(resource.initialized for resource in resources):
|
while any(resource.initialized for resource in resources):
|
||||||
resources_to_shutdown = list(_independent_resources(resources))
|
resources_to_shutdown = list(_independent_resources(resources))
|
||||||
if not resources_to_shutdown:
|
if not resources_to_shutdown:
|
||||||
raise RuntimeError('Unable to resolve resources shutdown order')
|
raise RuntimeError("Unable to resolve resources shutdown order")
|
||||||
futures = []
|
futures = []
|
||||||
for resource in resources_to_shutdown:
|
for resource in resources_to_shutdown:
|
||||||
result = resource.shutdown()
|
result = resource.shutdown()
|
||||||
|
@ -376,7 +376,7 @@ class DynamicContainer(Container):
|
||||||
while any(resource.initialized for resource in resources):
|
while any(resource.initialized for resource in resources):
|
||||||
resources_to_shutdown = list(_independent_resources(resources))
|
resources_to_shutdown = list(_independent_resources(resources))
|
||||||
if not resources_to_shutdown:
|
if not resources_to_shutdown:
|
||||||
raise RuntimeError('Unable to resolve resources shutdown order')
|
raise RuntimeError("Unable to resolve resources shutdown order")
|
||||||
for resource in resources_to_shutdown:
|
for resource in resources_to_shutdown:
|
||||||
resource.shutdown()
|
resource.shutdown()
|
||||||
|
|
||||||
|
@ -393,7 +393,7 @@ class DynamicContainer(Container):
|
||||||
config.load()
|
config.load()
|
||||||
|
|
||||||
def apply_container_providers_overridings(self):
|
def apply_container_providers_overridings(self):
|
||||||
"""Apply container providers' overridings."""
|
"""Apply container providers overridings."""
|
||||||
for provider in self.traverse(types=[providers.Container]):
|
for provider in self.traverse(types=[providers.Container]):
|
||||||
provider.apply_overridings()
|
provider.apply_overridings()
|
||||||
|
|
||||||
|
@ -419,12 +419,12 @@ class DynamicContainer(Container):
|
||||||
|
|
||||||
container_name = self.parent_name if self.parent_name else self.__class__.__name__
|
container_name = self.parent_name if self.parent_name else self.__class__.__name__
|
||||||
undefined_names = [
|
undefined_names = [
|
||||||
f'"{dependency.parent_name if dependency.parent_name else dependency}"'
|
f"\"{dependency.parent_name if dependency.parent_name else dependency}\""
|
||||||
for dependency in undefined
|
for dependency in undefined
|
||||||
]
|
]
|
||||||
raise errors.Error(
|
raise errors.Error(
|
||||||
f'Container "{container_name}" has undefined dependencies: '
|
f"Container \"{container_name}\" has undefined dependencies: "
|
||||||
f'{", ".join(undefined_names)}',
|
f"{', '.join(undefined_names)}",
|
||||||
)
|
)
|
||||||
|
|
||||||
def from_schema(self, schema):
|
def from_schema(self, schema):
|
||||||
|
@ -441,9 +441,9 @@ class DynamicContainer(Container):
|
||||||
"""
|
"""
|
||||||
if yaml is None:
|
if yaml is None:
|
||||||
raise errors.Error(
|
raise errors.Error(
|
||||||
'Unable to load yaml schema - PyYAML is not installed. '
|
"Unable to load yaml schema - PyYAML is not installed. "
|
||||||
'Install PyYAML or install Dependency Injector with yaml extras: '
|
"Install PyYAML or install Dependency Injector with yaml extras: "
|
||||||
'"pip install dependency-injector[yaml]"'
|
"\"pip install dependency-injector[yaml]\""
|
||||||
)
|
)
|
||||||
|
|
||||||
if loader is None:
|
if loader is None:
|
||||||
|
@ -466,7 +466,7 @@ class DynamicContainer(Container):
|
||||||
if container_provider is provider:
|
if container_provider is provider:
|
||||||
return provider_name
|
return provider_name
|
||||||
else:
|
else:
|
||||||
raise errors.Error(f'Can not resolve name for provider "{provider}"')
|
raise errors.Error(f"Can not resolve name for provider \"{provider}\"")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def parent_name(self):
|
def parent_name(self):
|
||||||
|
@ -525,11 +525,11 @@ class DeclarativeContainerMetaClass(type):
|
||||||
"instead got {0}".format(wiring_config)
|
"instead got {0}".format(wiring_config)
|
||||||
)
|
)
|
||||||
|
|
||||||
attributes['containers'] = containers
|
attributes["containers"] = containers
|
||||||
attributes['inherited_providers'] = inherited_providers
|
attributes["inherited_providers"] = inherited_providers
|
||||||
attributes['cls_providers'] = cls_providers
|
attributes["cls_providers"] = cls_providers
|
||||||
attributes['providers'] = all_providers
|
attributes["providers"] = all_providers
|
||||||
attributes['wiring_config'] = wiring_config
|
attributes["wiring_config"] = wiring_config
|
||||||
|
|
||||||
cls = <type>type.__new__(mcs, class_name, bases, attributes)
|
cls = <type>type.__new__(mcs, class_name, bases, attributes)
|
||||||
|
|
||||||
|
@ -551,15 +551,15 @@ class DeclarativeContainerMetaClass(type):
|
||||||
If value of attribute is provider, it will be added into providers
|
If value of attribute is provider, it will be added into providers
|
||||||
dictionary.
|
dictionary.
|
||||||
|
|
||||||
:param name: Attribute's name
|
:param name: Attribute name
|
||||||
:type name: object
|
:type name: object
|
||||||
|
|
||||||
:param value: Attribute's value
|
:param value: Attribute value
|
||||||
:type value: object
|
:type value: object
|
||||||
|
|
||||||
:rtype: None
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if isinstance(value, providers.Provider) and name != '__self__':
|
if isinstance(value, providers.Provider) and name != "__self__":
|
||||||
_check_provider_type(cls, value)
|
_check_provider_type(cls, value)
|
||||||
|
|
||||||
if isinstance(value, providers.CHILD_PROVIDERS):
|
if isinstance(value, providers.CHILD_PROVIDERS):
|
||||||
|
@ -575,7 +575,7 @@ class DeclarativeContainerMetaClass(type):
|
||||||
If value of attribute is provider, it will be deleted from providers
|
If value of attribute is provider, it will be deleted from providers
|
||||||
dictionary.
|
dictionary.
|
||||||
|
|
||||||
:param name: Attribute's name
|
:param name: Attribute name
|
||||||
:type name: object
|
:type name: object
|
||||||
|
|
||||||
:rtype: None
|
:rtype: None
|
||||||
|
@ -611,7 +611,7 @@ class DeclarativeContainerMetaClass(type):
|
||||||
if container_provider is provider:
|
if container_provider is provider:
|
||||||
return provider_name
|
return provider_name
|
||||||
else:
|
else:
|
||||||
raise errors.Error(f'Can not resolve name for provider "{provider}"')
|
raise errors.Error(f"Can not resolve name for provider \"{provider}\"")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def parent_name(cls):
|
def parent_name(cls):
|
||||||
|
@ -628,9 +628,9 @@ class DeclarativeContainerMetaClass(type):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if self is not None and value is not self:
|
if self is not None and value is not self:
|
||||||
raise errors.Error('Container can have only one "Self" provider')
|
raise errors.Error("Container can have only one \"Self\" provider")
|
||||||
|
|
||||||
if name != '__self__':
|
if name != "__self__":
|
||||||
alt_names.append(name)
|
alt_names.append(name)
|
||||||
|
|
||||||
self = value
|
self = value
|
||||||
|
@ -727,8 +727,8 @@ class DeclarativeContainer(Container):
|
||||||
container.wiring_config = copy_module.deepcopy(cls.wiring_config)
|
container.wiring_config = copy_module.deepcopy(cls.wiring_config)
|
||||||
container.declarative_parent = cls
|
container.declarative_parent = cls
|
||||||
|
|
||||||
copied_providers = providers.deepcopy({ **cls.providers, **{'@@self@@': cls.__self__}})
|
copied_providers = providers.deepcopy({ **cls.providers, **{"@@self@@": cls.__self__}})
|
||||||
copied_self = copied_providers.pop('@@self@@')
|
copied_self = copied_providers.pop("@@self@@")
|
||||||
copied_self.set_container(container)
|
copied_self.set_container(container)
|
||||||
|
|
||||||
container.__self__ = copied_self
|
container.__self__ = copied_self
|
||||||
|
@ -762,8 +762,8 @@ class DeclarativeContainer(Container):
|
||||||
:rtype: None
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if issubclass(cls, overriding):
|
if issubclass(cls, overriding):
|
||||||
raise errors.Error('Container {0} could not be overridden '
|
raise errors.Error("Container {0} could not be overridden "
|
||||||
'with itself or its subclasses'.format(cls))
|
"with itself or its subclasses".format(cls))
|
||||||
|
|
||||||
cls.overridden += (overriding,)
|
cls.overridden += (overriding,)
|
||||||
|
|
||||||
|
@ -780,7 +780,7 @@ class DeclarativeContainer(Container):
|
||||||
:rtype: None
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if not cls.overridden:
|
if not cls.overridden:
|
||||||
raise errors.Error('Container {0} is not overridden'.format(cls))
|
raise errors.Error("Container {0} is not overridden".format(cls))
|
||||||
|
|
||||||
cls.overridden = cls.overridden[:-1]
|
cls.overridden = cls.overridden[:-1]
|
||||||
|
|
||||||
|
@ -833,7 +833,7 @@ def override(object container):
|
||||||
container.
|
container.
|
||||||
:type container: :py:class:`DeclarativeContainer`
|
:type container: :py:class:`DeclarativeContainer`
|
||||||
|
|
||||||
:return: Declarative container's overriding decorator.
|
:return: Declarative container overriding decorator.
|
||||||
:rtype: callable(:py:class:`DeclarativeContainer`)
|
:rtype: callable(:py:class:`DeclarativeContainer`)
|
||||||
"""
|
"""
|
||||||
def _decorator(object overriding_container):
|
def _decorator(object overriding_container):
|
||||||
|
@ -853,7 +853,7 @@ def copy(object base_container):
|
||||||
:param base_container: Container that should be copied by decorated container.
|
:param base_container: Container that should be copied by decorated container.
|
||||||
:type base_container: :py:class:`DeclarativeContainer`
|
:type base_container: :py:class:`DeclarativeContainer`
|
||||||
|
|
||||||
:return: Declarative container's copying decorator.
|
:return: Declarative container copying decorator.
|
||||||
:rtype: callable(:py:class:`DeclarativeContainer`)
|
:rtype: callable(:py:class:`DeclarativeContainer`)
|
||||||
"""
|
"""
|
||||||
def _get_memo_for_matching_names(new_providers, base_providers):
|
def _get_memo_for_matching_names(new_providers, base_providers):
|
||||||
|
@ -864,7 +864,7 @@ def copy(object base_container):
|
||||||
source_provider = base_providers[new_provider_name]
|
source_provider = base_providers[new_provider_name]
|
||||||
memo[id(source_provider)] = new_provider
|
memo[id(source_provider)] = new_provider
|
||||||
|
|
||||||
if hasattr(new_provider, 'providers') and hasattr(source_provider, 'providers'):
|
if hasattr(new_provider, "providers") and hasattr(source_provider, "providers"):
|
||||||
sub_memo = _get_memo_for_matching_names(new_provider.providers, source_provider.providers)
|
sub_memo = _get_memo_for_matching_names(new_provider.providers, source_provider.providers)
|
||||||
memo.update(sub_memo)
|
memo.update(sub_memo)
|
||||||
return memo
|
return memo
|
||||||
|
@ -892,13 +892,13 @@ cpdef bint is_container(object instance):
|
||||||
|
|
||||||
:rtype: bool
|
:rtype: bool
|
||||||
"""
|
"""
|
||||||
return getattr(instance, '__IS_CONTAINER__', False) is True
|
return getattr(instance, "__IS_CONTAINER__", False) is True
|
||||||
|
|
||||||
|
|
||||||
cpdef object _check_provider_type(object container, object provider):
|
cpdef object _check_provider_type(object container, object provider):
|
||||||
if not isinstance(provider, container.provider_type):
|
if not isinstance(provider, container.provider_type):
|
||||||
raise errors.Error('{0} can contain only {1} '
|
raise errors.Error("{0} can contain only {1} "
|
||||||
'instances'.format(container, container.provider_type))
|
"instances".format(container, container.provider_type))
|
||||||
|
|
||||||
|
|
||||||
cpdef bint _any_relative_string_imports_in(object modules):
|
cpdef bint _any_relative_string_imports_in(object modules):
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -363,11 +363,11 @@ cdef inline tuple __separate_prefixed_kwargs(dict kwargs):
|
||||||
cdef dict prefixed_kwargs = {}
|
cdef dict prefixed_kwargs = {}
|
||||||
|
|
||||||
for key, value in kwargs.items():
|
for key, value in kwargs.items():
|
||||||
if '__' not in key:
|
if "__" not in key:
|
||||||
plain_kwargs[key] = value
|
plain_kwargs[key] = value
|
||||||
continue
|
continue
|
||||||
|
|
||||||
index = key.index('__')
|
index = key.index("__")
|
||||||
prefix, name = key[:index], key[index+2:]
|
prefix, name = key[:index], key[index+2:]
|
||||||
|
|
||||||
if prefix not in prefixed_kwargs:
|
if prefix not in prefixed_kwargs:
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -4,7 +4,7 @@ import abc
|
||||||
from typing import TypeVar, Generic, Optional
|
from typing import TypeVar, Generic, Optional
|
||||||
|
|
||||||
|
|
||||||
T = TypeVar('T')
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
class Resource(Generic[T], metaclass=abc.ABCMeta):
|
class Resource(Generic[T], metaclass=abc.ABCMeta):
|
||||||
|
|
|
@ -19,8 +19,8 @@ class SchemaProcessorV1:
|
||||||
|
|
||||||
def process(self):
|
def process(self):
|
||||||
"""Process schema."""
|
"""Process schema."""
|
||||||
self._create_providers(self._schema['container'])
|
self._create_providers(self._schema["container"])
|
||||||
self._setup_injections(self._schema['container'])
|
self._setup_injections(self._schema["container"])
|
||||||
|
|
||||||
def get_providers(self):
|
def get_providers(self):
|
||||||
"""Return providers."""
|
"""Return providers."""
|
||||||
|
@ -36,11 +36,11 @@ class SchemaProcessorV1:
|
||||||
for provider_name, data in provider_schema.items():
|
for provider_name, data in provider_schema.items():
|
||||||
provider = None
|
provider = None
|
||||||
|
|
||||||
if 'provider' in data:
|
if "provider" in data:
|
||||||
provider_type = _get_provider_cls(data['provider'])
|
provider_type = _get_provider_cls(data["provider"])
|
||||||
args = []
|
args = []
|
||||||
|
|
||||||
# provides = data.get('provides')
|
# provides = data.get("provides")
|
||||||
# if provides:
|
# if provides:
|
||||||
# provides = _import_string(provides)
|
# provides = _import_string(provides)
|
||||||
# if provides:
|
# if provides:
|
||||||
|
@ -69,38 +69,38 @@ class SchemaProcessorV1:
|
||||||
args = []
|
args = []
|
||||||
kwargs = {}
|
kwargs = {}
|
||||||
|
|
||||||
provides = data.get('provides')
|
provides = data.get("provides")
|
||||||
if provides:
|
if provides:
|
||||||
if isinstance(provides, str) and provides.startswith('container.'):
|
if isinstance(provides, str) and provides.startswith("container."):
|
||||||
provides = self._resolve_provider(provides[len('container.'):])
|
provides = self._resolve_provider(provides[len("container."):])
|
||||||
else:
|
else:
|
||||||
provides = _import_string(provides)
|
provides = _import_string(provides)
|
||||||
provider.set_provides(provides)
|
provider.set_provides(provides)
|
||||||
|
|
||||||
arg_injections = data.get('args')
|
arg_injections = data.get("args")
|
||||||
if arg_injections:
|
if arg_injections:
|
||||||
for arg in arg_injections:
|
for arg in arg_injections:
|
||||||
injection = None
|
injection = None
|
||||||
|
|
||||||
if isinstance(arg, str) and arg.startswith('container.'):
|
if isinstance(arg, str) and arg.startswith("container."):
|
||||||
injection = self._resolve_provider(arg[len('container.'):])
|
injection = self._resolve_provider(arg[len("container."):])
|
||||||
|
|
||||||
# TODO: refactoring
|
# TODO: refactoring
|
||||||
if isinstance(arg, dict):
|
if isinstance(arg, dict):
|
||||||
provider_args = []
|
provider_args = []
|
||||||
provider_type = _get_provider_cls(arg.get('provider'))
|
provider_type = _get_provider_cls(arg.get("provider"))
|
||||||
provides = arg.get('provides')
|
provides = arg.get("provides")
|
||||||
if provides:
|
if provides:
|
||||||
if isinstance(provides, str) and provides.startswith('container.'):
|
if isinstance(provides, str) and provides.startswith("container."):
|
||||||
provides = self._resolve_provider(provides[len('container.'):])
|
provides = self._resolve_provider(provides[len("container."):])
|
||||||
else:
|
else:
|
||||||
provides = _import_string(provides)
|
provides = _import_string(provides)
|
||||||
provider_args.append(provides)
|
provider_args.append(provides)
|
||||||
for provider_arg in arg.get('args', []):
|
for provider_arg in arg.get("args", []):
|
||||||
if isinstance(provider_arg, str) \
|
if isinstance(provider_arg, str) \
|
||||||
and provider_arg.startswith('container.'):
|
and provider_arg.startswith("container."):
|
||||||
provider_args.append(
|
provider_args.append(
|
||||||
self._resolve_provider(provider_arg[len('container.'):]),
|
self._resolve_provider(provider_arg[len("container."):]),
|
||||||
)
|
)
|
||||||
injection = provider_type(*provider_args)
|
injection = provider_type(*provider_args)
|
||||||
|
|
||||||
|
@ -111,30 +111,30 @@ class SchemaProcessorV1:
|
||||||
if args:
|
if args:
|
||||||
provider.add_args(*args)
|
provider.add_args(*args)
|
||||||
|
|
||||||
kwarg_injections = data.get('kwargs')
|
kwarg_injections = data.get("kwargs")
|
||||||
if kwarg_injections:
|
if kwarg_injections:
|
||||||
for name, arg in kwarg_injections.items():
|
for name, arg in kwarg_injections.items():
|
||||||
injection = None
|
injection = None
|
||||||
|
|
||||||
if isinstance(arg, str) and arg.startswith('container.'):
|
if isinstance(arg, str) and arg.startswith("container."):
|
||||||
injection = self._resolve_provider(arg[len('container.'):])
|
injection = self._resolve_provider(arg[len("container."):])
|
||||||
|
|
||||||
# TODO: refactoring
|
# TODO: refactoring
|
||||||
if isinstance(arg, dict):
|
if isinstance(arg, dict):
|
||||||
provider_args = []
|
provider_args = []
|
||||||
provider_type = _get_provider_cls(arg.get('provider'))
|
provider_type = _get_provider_cls(arg.get("provider"))
|
||||||
provides = arg.get('provides')
|
provides = arg.get("provides")
|
||||||
if provides:
|
if provides:
|
||||||
if isinstance(provides, str) and provides.startswith('container.'):
|
if isinstance(provides, str) and provides.startswith("container."):
|
||||||
provides = self._resolve_provider(provides[len('container.'):])
|
provides = self._resolve_provider(provides[len("container."):])
|
||||||
else:
|
else:
|
||||||
provides = _import_string(provides)
|
provides = _import_string(provides)
|
||||||
provider_args.append(provides)
|
provider_args.append(provides)
|
||||||
for provider_arg in arg.get('args', []):
|
for provider_arg in arg.get("args", []):
|
||||||
if isinstance(provider_arg, str) \
|
if isinstance(provider_arg, str) \
|
||||||
and provider_arg.startswith('container.'):
|
and provider_arg.startswith("container."):
|
||||||
provider_args.append(
|
provider_args.append(
|
||||||
self._resolve_provider(provider_arg[len('container.'):]),
|
self._resolve_provider(provider_arg[len("container."):]),
|
||||||
)
|
)
|
||||||
injection = provider_type(*provider_args)
|
injection = provider_type(*provider_args)
|
||||||
|
|
||||||
|
@ -149,17 +149,17 @@ class SchemaProcessorV1:
|
||||||
self._setup_injections(provider_schema=data, container=provider)
|
self._setup_injections(provider_schema=data, container=provider)
|
||||||
|
|
||||||
def _resolve_provider(self, name: str) -> Optional[providers.Provider]:
|
def _resolve_provider(self, name: str) -> Optional[providers.Provider]:
|
||||||
segments = name.split('.')
|
segments = name.split(".")
|
||||||
try:
|
try:
|
||||||
provider = getattr(self._container, segments[0])
|
provider = getattr(self._container, segments[0])
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
for segment in segments[1:]:
|
for segment in segments[1:]:
|
||||||
parentheses = ''
|
parentheses = ""
|
||||||
if '(' in segment and ')' in segment:
|
if "(" in segment and ")" in segment:
|
||||||
parentheses = segment[segment.find('('):segment.rfind(')')+1]
|
parentheses = segment[segment.find("("):segment.rfind(")")+1]
|
||||||
segment = segment.replace(parentheses, '')
|
segment = segment.replace(parentheses, "")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
provider = getattr(provider, segment)
|
provider = getattr(provider, segment)
|
||||||
|
@ -190,7 +190,7 @@ def _get_provider_cls(provider_cls_name: str) -> Type[providers.Provider]:
|
||||||
if custom_provider_type:
|
if custom_provider_type:
|
||||||
return custom_provider_type
|
return custom_provider_type
|
||||||
|
|
||||||
raise SchemaError(f'Undefined provider class "{provider_cls_name}"')
|
raise SchemaError(f"Undefined provider class \"{provider_cls_name}\"")
|
||||||
|
|
||||||
|
|
||||||
def _fetch_provider_cls_from_std(provider_cls_name: str) -> Optional[Type[providers.Provider]]:
|
def _fetch_provider_cls_from_std(provider_cls_name: str) -> Optional[Type[providers.Provider]]:
|
||||||
|
@ -201,24 +201,24 @@ def _import_provider_cls(provider_cls_name: str) -> Optional[Type[providers.Prov
|
||||||
try:
|
try:
|
||||||
cls = _import_string(provider_cls_name)
|
cls = _import_string(provider_cls_name)
|
||||||
except (ImportError, ValueError) as exception:
|
except (ImportError, ValueError) as exception:
|
||||||
raise SchemaError(f'Can not import provider "{provider_cls_name}"') from exception
|
raise SchemaError(f"Can not import provider \"{provider_cls_name}\"") from exception
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
if isinstance(cls, type) and not issubclass(cls, providers.Provider):
|
if isinstance(cls, type) and not issubclass(cls, providers.Provider):
|
||||||
raise SchemaError(f'Provider class "{cls}" is not a subclass of providers base class')
|
raise SchemaError(f"Provider class \"{cls}\" is not a subclass of providers base class")
|
||||||
return cls
|
return cls
|
||||||
|
|
||||||
|
|
||||||
def _import_string(string_name: str) -> Optional[object]:
|
def _import_string(string_name: str) -> Optional[object]:
|
||||||
segments = string_name.split('.')
|
segments = string_name.split(".")
|
||||||
|
|
||||||
if len(segments) == 1:
|
if len(segments) == 1:
|
||||||
member = getattr(builtins, segments[0], None)
|
member = getattr(builtins, segments[0], None)
|
||||||
if member:
|
if member:
|
||||||
return member
|
return member
|
||||||
|
|
||||||
module_name = '.'.join(segments[:-1])
|
module_name = ".".join(segments[:-1])
|
||||||
if not module_name:
|
if not module_name:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
|
@ -68,27 +68,27 @@ if sys.version_info[:2] == (3, 5):
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = (
|
__all__ = (
|
||||||
'wire',
|
"wire",
|
||||||
'unwire',
|
"unwire",
|
||||||
'inject',
|
"inject",
|
||||||
'as_int',
|
"as_int",
|
||||||
'as_float',
|
"as_float",
|
||||||
'as_',
|
"as_",
|
||||||
'required',
|
"required",
|
||||||
'invariant',
|
"invariant",
|
||||||
'provided',
|
"provided",
|
||||||
'Provide',
|
"Provide",
|
||||||
'Provider',
|
"Provider",
|
||||||
'Closing',
|
"Closing",
|
||||||
'register_loader_containers',
|
"register_loader_containers",
|
||||||
'unregister_loader_containers',
|
"unregister_loader_containers",
|
||||||
'install_loader',
|
"install_loader",
|
||||||
'uninstall_loader',
|
"uninstall_loader",
|
||||||
'is_loader_installed',
|
"is_loader_installed",
|
||||||
)
|
)
|
||||||
|
|
||||||
T = TypeVar('T')
|
T = TypeVar("T")
|
||||||
F = TypeVar('F', bound=Callable[..., Any])
|
F = TypeVar("F", bound=Callable[..., Any])
|
||||||
Container = Any
|
Container = Any
|
||||||
|
|
||||||
|
|
||||||
|
@ -107,10 +107,10 @@ class PatchedRegistry:
|
||||||
continue
|
continue
|
||||||
yield patched
|
yield patched
|
||||||
|
|
||||||
def add_attribute(self, patched: 'PatchedAttribute'):
|
def add_attribute(self, patched: "PatchedAttribute"):
|
||||||
self._attributes.add(patched)
|
self._attributes.add(patched)
|
||||||
|
|
||||||
def get_attributes_from_module(self, module: ModuleType) -> Iterator['PatchedAttribute']:
|
def get_attributes_from_module(self, module: ModuleType) -> Iterator["PatchedAttribute"]:
|
||||||
for attribute in self._attributes:
|
for attribute in self._attributes:
|
||||||
if not attribute.is_in_module(module):
|
if not attribute.is_in_module(module):
|
||||||
continue
|
continue
|
||||||
|
@ -125,7 +125,7 @@ class PatchedRegistry:
|
||||||
|
|
||||||
class PatchedAttribute:
|
class PatchedAttribute:
|
||||||
|
|
||||||
def __init__(self, member: Any, name: str, marker: '_Marker'):
|
def __init__(self, member: Any, name: str, marker: "_Marker"):
|
||||||
self.member = member
|
self.member = member
|
||||||
self.name = name
|
self.name = name
|
||||||
self.marker = marker
|
self.marker = marker
|
||||||
|
@ -143,7 +143,7 @@ class PatchedAttribute:
|
||||||
|
|
||||||
class ProvidersMap:
|
class ProvidersMap:
|
||||||
|
|
||||||
CONTAINER_STRING_ID = '<container>'
|
CONTAINER_STRING_ID = "<container>"
|
||||||
|
|
||||||
def __init__(self, container):
|
def __init__(self, container):
|
||||||
self._container = container
|
self._container = container
|
||||||
|
@ -159,7 +159,7 @@ class ProvidersMap:
|
||||||
def resolve_provider(
|
def resolve_provider(
|
||||||
self,
|
self,
|
||||||
provider: Union[providers.Provider, str],
|
provider: Union[providers.Provider, str],
|
||||||
modifier: Optional['Modifier'] = None,
|
modifier: Optional["Modifier"] = None,
|
||||||
) -> Optional[providers.Provider]:
|
) -> Optional[providers.Provider]:
|
||||||
if isinstance(provider, providers.Delegate):
|
if isinstance(provider, providers.Delegate):
|
||||||
return self._resolve_delegate(provider)
|
return self._resolve_delegate(provider)
|
||||||
|
@ -182,13 +182,13 @@ class ProvidersMap:
|
||||||
def _resolve_string_id(
|
def _resolve_string_id(
|
||||||
self,
|
self,
|
||||||
id: str,
|
id: str,
|
||||||
modifier: Optional['Modifier'] = None,
|
modifier: Optional["Modifier"] = None,
|
||||||
) -> Optional[providers.Provider]:
|
) -> Optional[providers.Provider]:
|
||||||
if id == self.CONTAINER_STRING_ID:
|
if id == self.CONTAINER_STRING_ID:
|
||||||
return self._container.__self__
|
return self._container.__self__
|
||||||
|
|
||||||
provider = self._container
|
provider = self._container
|
||||||
for segment in id.split('.'):
|
for segment in id.split("."):
|
||||||
try:
|
try:
|
||||||
provider = getattr(provider, segment)
|
provider = getattr(provider, segment)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
|
@ -282,10 +282,10 @@ class ProvidersMap:
|
||||||
original_container: Container,
|
original_container: Container,
|
||||||
) -> Dict[providers.Provider, providers.Provider]:
|
) -> Dict[providers.Provider, providers.Provider]:
|
||||||
current_providers = current_container.providers
|
current_providers = current_container.providers
|
||||||
current_providers['__self__'] = current_container.__self__
|
current_providers["__self__"] = current_container.__self__
|
||||||
|
|
||||||
original_providers = original_container.providers
|
original_providers = original_container.providers
|
||||||
original_providers['__self__'] = original_container.__self__
|
original_providers["__self__"] = original_container.__self__
|
||||||
|
|
||||||
providers_map = {}
|
providers_map = {}
|
||||||
for provider_name, current_provider in current_providers.items():
|
for provider_name, current_provider in current_providers.items():
|
||||||
|
@ -429,7 +429,7 @@ def _patch_method(
|
||||||
method: Callable[..., Any],
|
method: Callable[..., Any],
|
||||||
providers_map: ProvidersMap,
|
providers_map: ProvidersMap,
|
||||||
) -> None:
|
) -> None:
|
||||||
if hasattr(cls, '__dict__') \
|
if hasattr(cls, "__dict__") \
|
||||||
and name in cls.__dict__ \
|
and name in cls.__dict__ \
|
||||||
and isinstance(cls.__dict__[name], (classmethod, staticmethod)):
|
and isinstance(cls.__dict__[name], (classmethod, staticmethod)):
|
||||||
method = cls.__dict__[name]
|
method = cls.__dict__[name]
|
||||||
|
@ -457,7 +457,7 @@ def _unpatch(
|
||||||
name: str,
|
name: str,
|
||||||
fn: Callable[..., Any],
|
fn: Callable[..., Any],
|
||||||
) -> None:
|
) -> None:
|
||||||
if hasattr(module, '__dict__') \
|
if hasattr(module, "__dict__") \
|
||||||
and name in module.__dict__ \
|
and name in module.__dict__ \
|
||||||
and isinstance(module.__dict__[name], (classmethod, staticmethod)):
|
and isinstance(module.__dict__[name], (classmethod, staticmethod)):
|
||||||
method = module.__dict__[name]
|
method = module.__dict__[name]
|
||||||
|
@ -472,7 +472,7 @@ def _unpatch(
|
||||||
def _patch_attribute(
|
def _patch_attribute(
|
||||||
member: Any,
|
member: Any,
|
||||||
name: str,
|
name: str,
|
||||||
marker: '_Marker',
|
marker: "_Marker",
|
||||||
providers_map: ProvidersMap,
|
providers_map: ProvidersMap,
|
||||||
) -> None:
|
) -> None:
|
||||||
provider = providers_map.resolve_provider(marker.provider, marker.modifier)
|
provider = providers_map.resolve_provider(marker.provider, marker.modifier)
|
||||||
|
@ -487,7 +487,7 @@ def _patch_attribute(
|
||||||
elif isinstance(marker, Provider):
|
elif isinstance(marker, Provider):
|
||||||
setattr(member, name, provider)
|
setattr(member, name, provider)
|
||||||
else:
|
else:
|
||||||
raise Exception(f'Unknown type of marker {marker}')
|
raise Exception(f"Unknown type of marker {marker}")
|
||||||
|
|
||||||
|
|
||||||
def _unpatch_attribute(patched: PatchedAttribute) -> None:
|
def _unpatch_attribute(patched: PatchedAttribute) -> None:
|
||||||
|
@ -502,16 +502,16 @@ def _fetch_reference_injections( # noqa: C901
|
||||||
# - https://github.com/ets-labs/python-dependency-injector/issues/398
|
# - https://github.com/ets-labs/python-dependency-injector/issues/398
|
||||||
if GenericAlias and any((
|
if GenericAlias and any((
|
||||||
fn is GenericAlias,
|
fn is GenericAlias,
|
||||||
getattr(fn, '__func__', None) is GenericAlias
|
getattr(fn, "__func__", None) is GenericAlias
|
||||||
)):
|
)):
|
||||||
fn = fn.__init__
|
fn = fn.__init__
|
||||||
|
|
||||||
try:
|
try:
|
||||||
signature = inspect.signature(fn)
|
signature = inspect.signature(fn)
|
||||||
except ValueError as exception:
|
except ValueError as exception:
|
||||||
if 'no signature found' in str(exception):
|
if "no signature found" in str(exception):
|
||||||
return {}, {}
|
return {}, {}
|
||||||
elif 'not supported by signature' in str(exception):
|
elif "not supported by signature" in str(exception):
|
||||||
return {}, {}
|
return {}, {}
|
||||||
else:
|
else:
|
||||||
raise exception
|
raise exception
|
||||||
|
@ -565,11 +565,11 @@ def _unbind_injections(fn: Callable[..., Any]) -> None:
|
||||||
|
|
||||||
def _fetch_modules(package):
|
def _fetch_modules(package):
|
||||||
modules = [package]
|
modules = [package]
|
||||||
if not hasattr(package, '__path__') or not hasattr(package, '__name__'):
|
if not hasattr(package, "__path__") or not hasattr(package, "__name__"):
|
||||||
return modules
|
return modules
|
||||||
for module_info in pkgutil.walk_packages(
|
for module_info in pkgutil.walk_packages(
|
||||||
path=package.__path__,
|
path=package.__path__,
|
||||||
prefix=package.__name__ + '.',
|
prefix=package.__name__ + ".",
|
||||||
):
|
):
|
||||||
module = importlib.import_module(module_info.name)
|
module = importlib.import_module(module_info.name)
|
||||||
modules.append(module)
|
modules.append(module)
|
||||||
|
@ -670,13 +670,13 @@ def _is_fastapi_depends(param: Any) -> bool:
|
||||||
|
|
||||||
|
|
||||||
def _is_patched(fn):
|
def _is_patched(fn):
|
||||||
return getattr(fn, '__wired__', False) is True
|
return getattr(fn, "__wired__", False) is True
|
||||||
|
|
||||||
|
|
||||||
def _is_declarative_container(instance: Any) -> bool:
|
def _is_declarative_container(instance: Any) -> bool:
|
||||||
return (isinstance(instance, type)
|
return (isinstance(instance, type)
|
||||||
and getattr(instance, '__IS_CONTAINER__', False) is True
|
and getattr(instance, "__IS_CONTAINER__", False) is True
|
||||||
and getattr(instance, 'declarative_parent', None) is None)
|
and getattr(instance, "declarative_parent", None) is None)
|
||||||
|
|
||||||
|
|
||||||
class Modifier:
|
class Modifier:
|
||||||
|
@ -722,15 +722,15 @@ class RequiredModifier(Modifier):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.type_modifier = None
|
self.type_modifier = None
|
||||||
|
|
||||||
def as_int(self) -> 'RequiredModifier':
|
def as_int(self) -> "RequiredModifier":
|
||||||
self.type_modifier = TypeModifier(int)
|
self.type_modifier = TypeModifier(int)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def as_float(self) -> 'RequiredModifier':
|
def as_float(self) -> "RequiredModifier":
|
||||||
self.type_modifier = TypeModifier(float)
|
self.type_modifier = TypeModifier(float)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def as_(self, type_: Type) -> 'RequiredModifier':
|
def as_(self, type_: Type) -> "RequiredModifier":
|
||||||
self.type_modifier = TypeModifier(type_)
|
self.type_modifier = TypeModifier(type_)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@ -771,9 +771,9 @@ def invariant(id: str) -> InvariantModifier:
|
||||||
|
|
||||||
class ProvidedInstance(Modifier):
|
class ProvidedInstance(Modifier):
|
||||||
|
|
||||||
TYPE_ATTRIBUTE = 'attr'
|
TYPE_ATTRIBUTE = "attr"
|
||||||
TYPE_ITEM = 'item'
|
TYPE_ITEM = "item"
|
||||||
TYPE_CALL = 'call'
|
TYPE_CALL = "call"
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.segments = []
|
self.segments = []
|
||||||
|
|
Loading…
Reference in New Issue
Block a user