PK,mN~%lagom/__init__.py"""Lagom, a type based dependency injection container""" from .version import __version__ from .definitions import Singleton, Construction, Alias from .container import Container from .decorators import bind_to_container PKpO7yylagom/container.pyimport functools import inspect from typing import Dict, Type, Union, Any, TypeVar, Callable from lagom.util.functional import arity from .exceptions import UnresolvableType, InvalidDependencyDefinition from .definitions import Resolver, Construction, Singleton, Alias, DEFINITION_TYPES UNRESOLVABLE_TYPES = [str, int, float, bool] X = TypeVar("X") DepDefinition = Any class Container: _registered_types: Dict[Type, Resolver] = {} def define(self, dep: Union[Type[X], Type], resolver: DepDefinition) -> None: self._registered_types[dep] = self._normalise(resolver) def resolve(self, dep_type: Type[X], suppress_error=False) -> X: try: if dep_type in UNRESOLVABLE_TYPES: raise UnresolvableType(f"Cannot construct type {dep_type}") registered_type = self._registered_types.get(dep_type, dep_type) return self._build(registered_type) except UnresolvableType as inner_error: if not suppress_error: raise UnresolvableType( f"Cannot construct type {dep_type.__name__}" ) from inner_error return None # type: ignore def partial(self, func: Callable[..., X], keys_to_skip=None) -> Callable[..., X]: spec = inspect.getfullargspec(func) bindable_deps = self._infer_dependencies( spec, suppress_error=True, keys_to_skip=keys_to_skip or [] ) return functools.partial(func, **bindable_deps) def __getitem__(self, dep: Type[X]) -> X: return self.resolve(dep) def __setitem__(self, dep: Type, resolver: DepDefinition): self.define(dep, resolver) def _normalise(self, resolver: DepDefinition) -> Resolver: if type(resolver) in DEFINITION_TYPES: return resolver elif inspect.isfunction(resolver): return self._build_lambda_constructor(resolver) elif not inspect.isclass(resolver): return Singleton(lambda: resolver) # type: ignore else: return Alias(resolver) def _build_lambda_constructor(self, resolver: Callable) -> Construction: artiy = arity(resolver) if artiy == 0: return Construction(resolver) if artiy == 1: return Construction(functools.partial(resolver, self)) raise InvalidDependencyDefinition(f"Arity {arity} functions are not supported") def _build(self, dep_type: Any) -> Any: if isinstance(dep_type, Alias): return self.resolve(dep_type.alias_type) if isinstance(dep_type, Construction): return dep_type.construct() if isinstance(dep_type, Singleton): return self._load_singleton(dep_type) return self._reflection_build(dep_type) def _reflection_build(self, dep_type: Type[X]) -> X: spec = inspect.getfullargspec(dep_type.__init__) sub_deps = self._infer_dependencies(spec) return dep_type(**sub_deps) # type: ignore def _infer_dependencies( self, spec: inspect.FullArgSpec, suppress_error=False, keys_to_skip=[] ): sub_deps = { key: self.resolve(sub_dep_type, suppress_error=suppress_error) for (key, sub_dep_type) in spec.annotations.items() if key != "return" and sub_dep_type != Any and key not in keys_to_skip } filtered_deps = {key: dep for (key, dep) in sub_deps.items() if dep is not None} return filtered_deps def _load_singleton(self, singleton: Singleton): if singleton.has_instance: return singleton.instance return singleton.set_instance(self._build(singleton.singleton_type)) PKqO샦lagom/decorators.pyfrom .container import Container def bind_to_container(container: Container): def decorator(func): return container.partial(func) return decorator PKANƂlagom/definitions.pyfrom dataclasses import dataclass from typing import Generic, Union, Type, Optional, Callable, TypeVar X = TypeVar("X") @dataclass class Construction(Generic[X]): constructor: Callable[[], X] def construct(self): call = self.constructor return call() @dataclass class Alias(Generic[X]): alias_type: Type[X] class Singleton(Generic[X]): singleton_type: Union[Type[X], Construction[X]] _instance: Optional[X] def __init__(self, singleton_type: Union[Type[X], Construction[X]]): self.singleton_type = singleton_type self._instance = None @property def instance(self): return self._instance @property def has_instance(self): return self._instance is not None def set_instance(self, instance: X): self._instance = instance return instance DEFINITION_TYPES = [Alias, Construction, Singleton] Resolver = Union[Construction[X], Singleton[X], Alias[X]] PKNӑ"gglagom/exceptions.pyclass UnresolvableType(ValueError): pass class InvalidDependencyDefinition(ValueError): pass PKNlagom/py.typedPKqOT IIlagom/version.py__version__ = "0.3.2" if __name__ == "__main__": print(__version__) PKnNlagom/util/__init__.pyPKvN/lagom/util/functional.pyimport inspect from typing import Callable def arity(func: Callable) -> int: return len(inspect.signature(func).parameters) PKN88lagom-0.3.2.dist-info/LICENSEThe MIT License (MIT) Copyright (c) 2019 Steve Brazier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HMuSalagom-0.3.2.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!H\pV1&lagom-0.3.2.dist-info/METADATAWnF}WLd j"vcy0 yEyR2[3)v4L-gz赴"V ڨ"qCp*2Q*E/*˄#zoIKIsadB,e B=Qk9-&s F~Uez\)ҝ  z#r&rx`X]ΪrRR[CL+8m}i&R犛 ˕.eIN=*<^ *P4P˨Te*| xI#=BIsf B;LޗCJ?{j1M=d2cvӾ//)B7_> γ3R$cNub6{# 9VQ Xy&E#siȵ+N!?~JҘ[8 QMG>/KW*} j`f(4zeQZ3[SqHsRvlPـ9h?(&~lPTT!'9&QA; ?{kX;<Zfϐ<(LbtmT?T_aO"݈ڸ8ipnytOYD" 1%BPQ˜^"5wi%kV! z9FMcd+Pps_KwTY/ip#nX;9q8E 6 {L?XeTLq>>?ZeaѱRl!^ PK!Hⲽ:Llagom-0.3.2.dist-info/RECORDɒ@{? , 9, ,6*| cb2/ş8G{MG ODW ܮ8Xn^݈S;VQ:qmu5H!~;C)jlEJoTkNuux]ɠ*f`ǦEҽXj۔^6O4>8:qjoAa{i R)ӨyB7UrߺQ?^(QéDWZi ẔC4' OȊ+A{1m: 9}tO5gX+A=^Ϙ