Update quotes in Cython and Python modules

This commit is contained in:
Roman Mogylatov 2022-01-16 20:32:42 -05:00
parent a38ca647c3
commit 8dc3dd2f09
8 changed files with 8553 additions and 8681 deletions

File diff suppressed because it is too large Load Diff

View File

@ -28,10 +28,10 @@ if sys.version_info[:2] >= (3, 6):
from .wiring import wire, unwire
else:
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):
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):
warnings.warn(
@ -137,17 +137,17 @@ class DynamicContainer(Container):
If value of attribute is provider, it will be added into providers
dictionary.
:param name: Attribute's name
:param name: Attribute name
:type name: object
:param value: Attribute's value
:param value: Attribute value
:type value: object
:rtype: None
"""
if isinstance(value, providers.Provider) \
and not isinstance(value, providers.Self) \
and name != 'parent':
and name != "parent":
_check_provider_type(self, value)
self.providers[name] = value
@ -163,7 +163,7 @@ class DynamicContainer(Container):
If value of attribute is provider, it will be deleted from providers
dictionary.
:param name: Attribute's name
:param name: Attribute name
:type name: object
:rtype: None
@ -229,8 +229,8 @@ class DynamicContainer(Container):
:rtype: None
"""
if overriding is self:
raise errors.Error('Container {0} could not be overridden '
'with itself'.format(self))
raise errors.Error("Container {0} could not be overridden "
"with itself".format(self))
self.overridden += (overriding,)
@ -262,7 +262,7 @@ class DynamicContainer(Container):
:rtype: None
"""
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]
@ -364,7 +364,7 @@ class DynamicContainer(Container):
while any(resource.initialized for resource in resources):
resources_to_shutdown = list(_independent_resources(resources))
if not resources_to_shutdown:
raise RuntimeError('Unable to resolve resources shutdown order')
raise RuntimeError("Unable to resolve resources shutdown order")
futures = []
for resource in resources_to_shutdown:
result = resource.shutdown()
@ -376,7 +376,7 @@ class DynamicContainer(Container):
while any(resource.initialized for resource in resources):
resources_to_shutdown = list(_independent_resources(resources))
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:
resource.shutdown()
@ -393,7 +393,7 @@ class DynamicContainer(Container):
config.load()
def apply_container_providers_overridings(self):
"""Apply container providers' overridings."""
"""Apply container providers overridings."""
for provider in self.traverse(types=[providers.Container]):
provider.apply_overridings()
@ -419,12 +419,12 @@ class DynamicContainer(Container):
container_name = self.parent_name if self.parent_name else self.__class__.__name__
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
]
raise errors.Error(
f'Container "{container_name}" has undefined dependencies: '
f'{", ".join(undefined_names)}',
f"Container \"{container_name}\" has undefined dependencies: "
f"{', '.join(undefined_names)}",
)
def from_schema(self, schema):
@ -441,9 +441,9 @@ class DynamicContainer(Container):
"""
if yaml is None:
raise errors.Error(
'Unable to load yaml schema - PyYAML is not installed. '
'Install PyYAML or install Dependency Injector with yaml extras: '
'"pip install dependency-injector[yaml]"'
"Unable to load yaml schema - PyYAML is not installed. "
"Install PyYAML or install Dependency Injector with yaml extras: "
"\"pip install dependency-injector[yaml]\""
)
if loader is None:
@ -466,7 +466,7 @@ class DynamicContainer(Container):
if container_provider is provider:
return provider_name
else:
raise errors.Error(f'Can not resolve name for provider "{provider}"')
raise errors.Error(f"Can not resolve name for provider \"{provider}\"")
@property
def parent_name(self):
@ -525,11 +525,11 @@ class DeclarativeContainerMetaClass(type):
"instead got {0}".format(wiring_config)
)
attributes['containers'] = containers
attributes['inherited_providers'] = inherited_providers
attributes['cls_providers'] = cls_providers
attributes['providers'] = all_providers
attributes['wiring_config'] = wiring_config
attributes["containers"] = containers
attributes["inherited_providers"] = inherited_providers
attributes["cls_providers"] = cls_providers
attributes["providers"] = all_providers
attributes["wiring_config"] = wiring_config
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
dictionary.
:param name: Attribute's name
:param name: Attribute name
:type name: object
:param value: Attribute's value
:param value: Attribute value
:type value: object
:rtype: None
"""
if isinstance(value, providers.Provider) and name != '__self__':
if isinstance(value, providers.Provider) and name != "__self__":
_check_provider_type(cls, value)
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
dictionary.
:param name: Attribute's name
:param name: Attribute name
:type name: object
:rtype: None
@ -611,7 +611,7 @@ class DeclarativeContainerMetaClass(type):
if container_provider is provider:
return provider_name
else:
raise errors.Error(f'Can not resolve name for provider "{provider}"')
raise errors.Error(f"Can not resolve name for provider \"{provider}\"")
@property
def parent_name(cls):
@ -628,9 +628,9 @@ class DeclarativeContainerMetaClass(type):
continue
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)
self = value
@ -727,8 +727,8 @@ class DeclarativeContainer(Container):
container.wiring_config = copy_module.deepcopy(cls.wiring_config)
container.declarative_parent = cls
copied_providers = providers.deepcopy({ **cls.providers, **{'@@self@@': cls.__self__}})
copied_self = copied_providers.pop('@@self@@')
copied_providers = providers.deepcopy({ **cls.providers, **{"@@self@@": cls.__self__}})
copied_self = copied_providers.pop("@@self@@")
copied_self.set_container(container)
container.__self__ = copied_self
@ -762,8 +762,8 @@ class DeclarativeContainer(Container):
:rtype: None
"""
if issubclass(cls, overriding):
raise errors.Error('Container {0} could not be overridden '
'with itself or its subclasses'.format(cls))
raise errors.Error("Container {0} could not be overridden "
"with itself or its subclasses".format(cls))
cls.overridden += (overriding,)
@ -780,7 +780,7 @@ class DeclarativeContainer(Container):
:rtype: None
"""
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]
@ -833,7 +833,7 @@ def override(object container):
container.
:type container: :py:class:`DeclarativeContainer`
:return: Declarative container's overriding decorator.
:return: Declarative container overriding decorator.
:rtype: callable(:py:class:`DeclarativeContainer`)
"""
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.
:type base_container: :py:class:`DeclarativeContainer`
:return: Declarative container's copying decorator.
:return: Declarative container copying decorator.
:rtype: callable(:py:class:`DeclarativeContainer`)
"""
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]
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)
memo.update(sub_memo)
return memo
@ -892,13 +892,13 @@ cpdef bint is_container(object instance):
: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):
if not isinstance(provider, container.provider_type):
raise errors.Error('{0} can contain only {1} '
'instances'.format(container, container.provider_type))
raise errors.Error("{0} can contain only {1} "
"instances".format(container, container.provider_type))
cpdef bint _any_relative_string_imports_in(object modules):

File diff suppressed because it is too large Load Diff

View File

@ -363,11 +363,11 @@ cdef inline tuple __separate_prefixed_kwargs(dict kwargs):
cdef dict prefixed_kwargs = {}
for key, value in kwargs.items():
if '__' not in key:
if "__" not in key:
plain_kwargs[key] = value
continue
index = key.index('__')
index = key.index("__")
prefix, name = key[:index], key[index+2:]
if prefix not in prefixed_kwargs:

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@ import abc
from typing import TypeVar, Generic, Optional
T = TypeVar('T')
T = TypeVar("T")
class Resource(Generic[T], metaclass=abc.ABCMeta):

View File

@ -19,8 +19,8 @@ class SchemaProcessorV1:
def process(self):
"""Process schema."""
self._create_providers(self._schema['container'])
self._setup_injections(self._schema['container'])
self._create_providers(self._schema["container"])
self._setup_injections(self._schema["container"])
def get_providers(self):
"""Return providers."""
@ -36,11 +36,11 @@ class SchemaProcessorV1:
for provider_name, data in provider_schema.items():
provider = None
if 'provider' in data:
provider_type = _get_provider_cls(data['provider'])
if "provider" in data:
provider_type = _get_provider_cls(data["provider"])
args = []
# provides = data.get('provides')
# provides = data.get("provides")
# if provides:
# provides = _import_string(provides)
# if provides:
@ -69,38 +69,38 @@ class SchemaProcessorV1:
args = []
kwargs = {}
provides = data.get('provides')
provides = data.get("provides")
if provides:
if isinstance(provides, str) and provides.startswith('container.'):
provides = self._resolve_provider(provides[len('container.'):])
if isinstance(provides, str) and provides.startswith("container."):
provides = self._resolve_provider(provides[len("container."):])
else:
provides = _import_string(provides)
provider.set_provides(provides)
arg_injections = data.get('args')
arg_injections = data.get("args")
if arg_injections:
for arg in arg_injections:
injection = None
if isinstance(arg, str) and arg.startswith('container.'):
injection = self._resolve_provider(arg[len('container.'):])
if isinstance(arg, str) and arg.startswith("container."):
injection = self._resolve_provider(arg[len("container."):])
# TODO: refactoring
if isinstance(arg, dict):
provider_args = []
provider_type = _get_provider_cls(arg.get('provider'))
provides = arg.get('provides')
provider_type = _get_provider_cls(arg.get("provider"))
provides = arg.get("provides")
if provides:
if isinstance(provides, str) and provides.startswith('container.'):
provides = self._resolve_provider(provides[len('container.'):])
if isinstance(provides, str) and provides.startswith("container."):
provides = self._resolve_provider(provides[len("container."):])
else:
provides = _import_string(provides)
provider_args.append(provides)
for provider_arg in arg.get('args', []):
for provider_arg in arg.get("args", []):
if isinstance(provider_arg, str) \
and provider_arg.startswith('container.'):
and provider_arg.startswith("container."):
provider_args.append(
self._resolve_provider(provider_arg[len('container.'):]),
self._resolve_provider(provider_arg[len("container."):]),
)
injection = provider_type(*provider_args)
@ -111,30 +111,30 @@ class SchemaProcessorV1:
if args:
provider.add_args(*args)
kwarg_injections = data.get('kwargs')
kwarg_injections = data.get("kwargs")
if kwarg_injections:
for name, arg in kwarg_injections.items():
injection = None
if isinstance(arg, str) and arg.startswith('container.'):
injection = self._resolve_provider(arg[len('container.'):])
if isinstance(arg, str) and arg.startswith("container."):
injection = self._resolve_provider(arg[len("container."):])
# TODO: refactoring
if isinstance(arg, dict):
provider_args = []
provider_type = _get_provider_cls(arg.get('provider'))
provides = arg.get('provides')
provider_type = _get_provider_cls(arg.get("provider"))
provides = arg.get("provides")
if provides:
if isinstance(provides, str) and provides.startswith('container.'):
provides = self._resolve_provider(provides[len('container.'):])
if isinstance(provides, str) and provides.startswith("container."):
provides = self._resolve_provider(provides[len("container."):])
else:
provides = _import_string(provides)
provider_args.append(provides)
for provider_arg in arg.get('args', []):
for provider_arg in arg.get("args", []):
if isinstance(provider_arg, str) \
and provider_arg.startswith('container.'):
and provider_arg.startswith("container."):
provider_args.append(
self._resolve_provider(provider_arg[len('container.'):]),
self._resolve_provider(provider_arg[len("container."):]),
)
injection = provider_type(*provider_args)
@ -149,17 +149,17 @@ class SchemaProcessorV1:
self._setup_injections(provider_schema=data, container=provider)
def _resolve_provider(self, name: str) -> Optional[providers.Provider]:
segments = name.split('.')
segments = name.split(".")
try:
provider = getattr(self._container, segments[0])
except AttributeError:
return None
for segment in segments[1:]:
parentheses = ''
if '(' in segment and ')' in segment:
parentheses = segment[segment.find('('):segment.rfind(')')+1]
segment = segment.replace(parentheses, '')
parentheses = ""
if "(" in segment and ")" in segment:
parentheses = segment[segment.find("("):segment.rfind(")")+1]
segment = segment.replace(parentheses, "")
try:
provider = getattr(provider, segment)
@ -190,7 +190,7 @@ def _get_provider_cls(provider_cls_name: str) -> Type[providers.Provider]:
if 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]]:
@ -201,24 +201,24 @@ def _import_provider_cls(provider_cls_name: str) -> Optional[Type[providers.Prov
try:
cls = _import_string(provider_cls_name)
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:
return None
else:
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
def _import_string(string_name: str) -> Optional[object]:
segments = string_name.split('.')
segments = string_name.split(".")
if len(segments) == 1:
member = getattr(builtins, segments[0], None)
if member:
return member
module_name = '.'.join(segments[:-1])
module_name = ".".join(segments[:-1])
if not module_name:
return None

View File

@ -68,27 +68,27 @@ if sys.version_info[:2] == (3, 5):
)
__all__ = (
'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',
"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",
)
T = TypeVar('T')
F = TypeVar('F', bound=Callable[..., Any])
T = TypeVar("T")
F = TypeVar("F", bound=Callable[..., Any])
Container = Any
@ -107,10 +107,10 @@ class PatchedRegistry:
continue
yield patched
def add_attribute(self, patched: 'PatchedAttribute'):
def add_attribute(self, patched: "PatchedAttribute"):
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:
if not attribute.is_in_module(module):
continue
@ -125,7 +125,7 @@ class PatchedRegistry:
class PatchedAttribute:
def __init__(self, member: Any, name: str, marker: '_Marker'):
def __init__(self, member: Any, name: str, marker: "_Marker"):
self.member = member
self.name = name
self.marker = marker
@ -143,7 +143,7 @@ class PatchedAttribute:
class ProvidersMap:
CONTAINER_STRING_ID = '<container>'
CONTAINER_STRING_ID = "<container>"
def __init__(self, container):
self._container = container
@ -159,7 +159,7 @@ class ProvidersMap:
def resolve_provider(
self,
provider: Union[providers.Provider, str],
modifier: Optional['Modifier'] = None,
modifier: Optional["Modifier"] = None,
) -> Optional[providers.Provider]:
if isinstance(provider, providers.Delegate):
return self._resolve_delegate(provider)
@ -182,13 +182,13 @@ class ProvidersMap:
def _resolve_string_id(
self,
id: str,
modifier: Optional['Modifier'] = None,
modifier: Optional["Modifier"] = None,
) -> Optional[providers.Provider]:
if id == self.CONTAINER_STRING_ID:
return self._container.__self__
provider = self._container
for segment in id.split('.'):
for segment in id.split("."):
try:
provider = getattr(provider, segment)
except AttributeError:
@ -282,10 +282,10 @@ class ProvidersMap:
original_container: Container,
) -> Dict[providers.Provider, providers.Provider]:
current_providers = current_container.providers
current_providers['__self__'] = current_container.__self__
current_providers["__self__"] = current_container.__self__
original_providers = original_container.providers
original_providers['__self__'] = original_container.__self__
original_providers["__self__"] = original_container.__self__
providers_map = {}
for provider_name, current_provider in current_providers.items():
@ -429,7 +429,7 @@ def _patch_method(
method: Callable[..., Any],
providers_map: ProvidersMap,
) -> None:
if hasattr(cls, '__dict__') \
if hasattr(cls, "__dict__") \
and name in cls.__dict__ \
and isinstance(cls.__dict__[name], (classmethod, staticmethod)):
method = cls.__dict__[name]
@ -457,7 +457,7 @@ def _unpatch(
name: str,
fn: Callable[..., Any],
) -> None:
if hasattr(module, '__dict__') \
if hasattr(module, "__dict__") \
and name in module.__dict__ \
and isinstance(module.__dict__[name], (classmethod, staticmethod)):
method = module.__dict__[name]
@ -472,7 +472,7 @@ def _unpatch(
def _patch_attribute(
member: Any,
name: str,
marker: '_Marker',
marker: "_Marker",
providers_map: ProvidersMap,
) -> None:
provider = providers_map.resolve_provider(marker.provider, marker.modifier)
@ -487,7 +487,7 @@ def _patch_attribute(
elif isinstance(marker, Provider):
setattr(member, name, provider)
else:
raise Exception(f'Unknown type of marker {marker}')
raise Exception(f"Unknown type of marker {marker}")
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
if GenericAlias and any((
fn is GenericAlias,
getattr(fn, '__func__', None) is GenericAlias
getattr(fn, "__func__", None) is GenericAlias
)):
fn = fn.__init__
try:
signature = inspect.signature(fn)
except ValueError as exception:
if 'no signature found' in str(exception):
if "no signature found" in str(exception):
return {}, {}
elif 'not supported by signature' in str(exception):
elif "not supported by signature" in str(exception):
return {}, {}
else:
raise exception
@ -565,11 +565,11 @@ def _unbind_injections(fn: Callable[..., Any]) -> None:
def _fetch_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
for module_info in pkgutil.walk_packages(
path=package.__path__,
prefix=package.__name__ + '.',
prefix=package.__name__ + ".",
):
module = importlib.import_module(module_info.name)
modules.append(module)
@ -670,13 +670,13 @@ def _is_fastapi_depends(param: Any) -> bool:
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:
return (isinstance(instance, type)
and getattr(instance, '__IS_CONTAINER__', False) is True
and getattr(instance, 'declarative_parent', None) is None)
and getattr(instance, "__IS_CONTAINER__", False) is True
and getattr(instance, "declarative_parent", None) is None)
class Modifier:
@ -722,15 +722,15 @@ class RequiredModifier(Modifier):
def __init__(self):
self.type_modifier = None
def as_int(self) -> 'RequiredModifier':
def as_int(self) -> "RequiredModifier":
self.type_modifier = TypeModifier(int)
return self
def as_float(self) -> 'RequiredModifier':
def as_float(self) -> "RequiredModifier":
self.type_modifier = TypeModifier(float)
return self
def as_(self, type_: Type) -> 'RequiredModifier':
def as_(self, type_: Type) -> "RequiredModifier":
self.type_modifier = TypeModifier(type_)
return self
@ -771,9 +771,9 @@ def invariant(id: str) -> InvariantModifier:
class ProvidedInstance(Modifier):
TYPE_ATTRIBUTE = 'attr'
TYPE_ITEM = 'item'
TYPE_CALL = 'call'
TYPE_ATTRIBUTE = "attr"
TYPE_ITEM = "item"
TYPE_CALL = "call"
def __init__(self):
self.segments = []