PK!pH H component_injector/__init__.pyimport contextvars import functools import inspect from types import TracebackType from typing import Any, Callable, Dict, Optional, Type, TypeVar, cast T = TypeVar("T") TypeMap = Dict[Type[T], T] UNSET = object() class Injector: class Context: def __init__(self, injector: "Injector") -> None: self.injector = injector self.registry = injector.registry def __enter__(self) -> None: self.token = self.registry.set(self.registry.get().copy()) def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[Exception], traceback: Optional[TracebackType], ) -> None: self.registry.reset(self.token) registry: contextvars.ContextVar def __init__(self) -> None: self.registry = contextvars.ContextVar("registry", default={}) def register( self, component: Any, *, bases: bool = True, overwrite_bases: bool = True ) -> None: registry: TypeMap = self.registry.get() type_ = type(component) registry[type_] = component if bases: types = type_.mro() for type_ in types: apply = overwrite_bases or type_ not in registry if inspect.isclass(type_) and apply: registry[type_] = component def get_component(self, type_: Type[T]) -> T: registry: TypeMap = self.registry.get() return cast(T, registry[type_]) def scope(self) -> "Injector.Context": return self.Context(self) def inject(self, f: Callable[..., T]) -> Callable[..., T]: sig = inspect.signature(f) @functools.wraps(f) def wrapper(*args: Any, **kwargs: Any) -> T: registry = self.registry.get() bound = sig.bind_partial(*args, **kwargs) for name, param in sig.parameters.items(): if ( param in bound.arguments or param.annotation is inspect.Parameter.empty ): continue component = registry.get(param.annotation, UNSET) if component is not UNSET: bound.arguments[name] = component bound.apply_defaults() return f(*bound.args, **bound.kwargs) return wrapper PK!HڽTU(component_injector-1.0.1.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!HN +component_injector-1.0.1.dist-info/METADATAVn6S,;[N4Hh t 1-6gTI*{=ɾCɲf݂̀I<9|dßښ1=KPcJmQZLjJuzA* 1Sa3FFRL_aa '/M;[a)hZ%s4^=ΙNP}z%+uc:5sE~B|L9qq>W)?WY̓Ԍ'G;= ҧ!}V=xJ}⾅>]T!Ƕh;'gR}=6F"7on`#G*}@x^vjF V\3IY[FN19Qk/G\Gnf'7=խmǦG Bc~6n9ܴ`` ץU HDUj;S>Rp 1ؿ݊ #*4. KyDYw'3G_D΂LN ^cGxinhc,cBfKجW%,K=D`yɺMQ<m2fuuV-V]_vt`/ē=;,wtd-Ju,X3uq?l6e f ږoVNO+"Mb7Ä.͇7IiJ`A]) S\ KHǵbZųN%jo1x3nP&]PoiUt-utOxq5-pMk[d( =2`45}yzi9 uQ8Ϋ B' PK!HE g<F)component_injector-1.0.1.dist-info/RECORD=s0ߒ`H CjXrh_o.n>n;*eT0zX󿔆sټr9ۀZ^4e0KQ=USў$eL^6lR}iXܛvP\Ʋs:jFm[&?ܼpgKh@ur0=d<64WƢ%MT.>G@gnPK!pH H component_injector/__init__.pyPK!HڽTU( component_injector-1.0.1.dist-info/WHEELPK!HN + component_injector-1.0.1.dist-info/METADATAPK!HE g<F)(component_injector-1.0.1.dist-info/RECORDPKRG