PKrkN Թlagom/__init__.py"""Lagom, a type based dependency injection container""" __version__ = "0.1.0" from .definitions import Singleton, Construction, Alias from .container import Container from .decorators import bind_to_container PKVNN7@" lagom/container.pyimport functools import inspect from typing import Dict, Type, Union, Any, TypeVar, Callable from .exceptions import UnresolvableType from .definitions import Resolver, Construction, Singleton, Alias, DEFINITION_TYPES UNRESOLVABLE_TYPES = [str, int, float, bool] X = TypeVar("X") class Container: _registered_types: Dict[Type, Resolver] = {} def define(self, dep_type: Union[Type[X], Type], dep_resolver: Resolver) -> None: self._registered_types[dep_type] = dep_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) if isinstance(registered_type, Singleton): return self._load_singleton(registered_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) -> Callable: spec = inspect.getfullargspec(func) bindable_deps = self._infer_dependencies(spec, suppress_error=True) return functools.partial(func, **bindable_deps) def __getitem__(self, dep: Type[X]) -> X: return self.resolve(dep) def __setitem__(self, dep: Type, resolver): if type(resolver) in DEFINITION_TYPES: return self.define(dep, resolver) if inspect.isfunction(resolver): return self.define(dep, Construction(resolver)) if not inspect.isclass(resolver): return self.define(dep, Singleton(lambda: resolver)) # type: ignore return self.define(dep, Alias(resolver)) 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() 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): sub_deps = { key: self.resolve(sub_dep_type, suppress_error=suppress_error) for (key, sub_dep_type) in spec.annotations.items() } 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)) PKVN1**lagom/decorators.pyimport functools from .container import Container def bind_to_container(container: Container): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return container.partial(func)(*args, **kwargs) return wrapper return decorator PKY~NƂ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]] PKqNot--lagom/exceptions.pyclass UnresolvableType(ValueError): pass PKNlagom/py.typedPKN88lagom-0.1.0.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.1.0.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!H.lagom-0.1.0.dist-info/METADATAM90D{D@ DBV!ŋl'RnQ{YsꂘwL4l![zVOű(ibc8AFpj$PIy8DUlms6bg\>?|d:e MԪ\\ugqCʵWPK!Hǿ1Klagom-0.1.0.dist-info/RECORDuɎ@{ e"ˡ(Ȣ\K(P(|Lq( GѬe53:q/*ްi1z-AGJQ㪅cjܼ J+3qDK8GAe0EKbź`8gGr3c1bk*bo?TW:|2そAO'@.yH'=,xOa?5W>/2ΥJՍID4tCs&C;=]wⵥ[7>X+xA,,PK_gl>˪ѧ^ɖ+?}#S Uچ(D#ZQ"^M ;dxvG,[[d6:s857m0*K)!poDSDI'mӎnS9crq/o2%(:v$PKrkN Թlagom/__init__.pyPKVNN7@" lagom/container.pyPKVN1** lagom/decorators.pyPKY~NƂ@lagom/definitions.pyPKqNot--9lagom/exceptions.pyPKNlagom/py.typedPKN88lagom-0.1.0.dist-info/LICENSEPK!HMuSa6lagom-0.1.0.dist-info/WHEELPK!H.lagom-0.1.0.dist-info/METADATAPK!Hǿ1Klagom-0.1.0.dist-info/RECORDPK