inject 5.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
inject/__init__.py ADDED
@@ -0,0 +1,774 @@
1
+ """
2
+ Python dependency injection framework.
3
+
4
+ Usage:
5
+ - Create an optional configuration::
6
+ def my_config(binder):
7
+ binder.bind(Cache, RedisCache('localhost:1234'))
8
+ binder.bind_to_provider(CurrentUser, get_current_user)
9
+
10
+ - Create a shared injector::
11
+ inject.configure(my_config)
12
+
13
+ - Use `inject.instance`, `inject.attr` or `inject.param` to inject dependencies::
14
+ class User(object):
15
+ cache = inject.attr(Cache)
16
+
17
+ @classmethod
18
+ def load(cls, id):
19
+ return cls.cache.load('user', id)
20
+
21
+ def save(self):
22
+ self.cache.save(self)
23
+
24
+ def foo(bar):
25
+ cache = inject.instance(Cache)
26
+ cache.save('bar', bar)
27
+
28
+ @inject.params(cache=Cache)
29
+ def bar(foo, cache=None):
30
+ cache.save('foo', foo)
31
+
32
+ Binding types:
33
+ - Instance bindings configured via `bind(cls, instance) which always return the same instance.
34
+ - Constructor bindings `bind_to_constructor(cls, callable)` which create a singleton
35
+ on first access.
36
+ - Provider bindings `bind_to_provider(cls, callable)` which call the provider
37
+ for each injection.
38
+ - Runtime bindings which automatically create class singletons.
39
+
40
+ Thread-safety:
41
+ After configuration the injector is thread-safe and can be safely reused by multiple threads.
42
+
43
+ Unit testing:
44
+ In tests use `inject.clear_and_configure(callable)` to create a new injector on setup,
45
+ and `inject.clear()` to clean-up on tear down.
46
+
47
+ Runtime bindings greatly reduce the required configuration by automatically creating singletons
48
+ on first access. For example, below only the Config class requires binding configuration,
49
+ all other classes are runtime bindings::
50
+ class Cache(object):
51
+ config = inject.attr(Config)
52
+
53
+ def __init__(self):
54
+ self._redis = connect(self.config.redis_address)
55
+
56
+ class Db(object):
57
+ pass
58
+
59
+ class UserRepo(object):
60
+ cache = inject.attr(Cache)
61
+ db = inject.attr(Db)
62
+
63
+ def load(self, user_id):
64
+ return cache.load('user', user_id) or db.load('user', user_id)
65
+
66
+ class Config(object):
67
+ def __init__(self, redis_address):
68
+ self.redis_address = redis_address
69
+
70
+ def my_config(binder):
71
+ binder.bind(Config, load_config_file())
72
+
73
+ inject.configure(my_config)
74
+
75
+ """ # noqa: E501
76
+
77
+ from __future__ import annotations
78
+
79
+ import contextlib
80
+ import functools
81
+ import inspect
82
+ import logging
83
+ import sys
84
+ import threading
85
+ import typing as t
86
+
87
+ from inject._version import __version__ as __version__
88
+
89
+ # PEP 604
90
+ _HAS_PEP604_SUPPORT = sys.version_info[:3] >= (3, 10, 0)
91
+ # PEP 560
92
+ _HAS_PEP560_SUPPORT = _HAS_PEP604_SUPPORT or sys.version_info[:3] >= (3, 7, 0)
93
+
94
+ _RETURN = "return"
95
+ _MISSING = object()
96
+
97
+ if _HAS_PEP604_SUPPORT:
98
+ from types import UnionType
99
+ from typing import _GenericAlias # noqa: ICN003
100
+ elif _HAS_PEP560_SUPPORT:
101
+ from typing import _GenericAlias # noqa: ICN003, PLC2701
102
+ else:
103
+ from typing import _Union # noqa: ICN003, PLC2701
104
+
105
+ if t.TYPE_CHECKING:
106
+ from typing_extensions import ParamSpec
107
+
108
+ P = ParamSpec("P")
109
+ else:
110
+ P = object()
111
+
112
+ logger = logging.getLogger("inject")
113
+
114
+ _INJECTOR = None # Shared injector instance.
115
+ _INJECTOR_LOCK = threading.RLock() # Guards injector initialization.
116
+ _BINDING_LOCK = threading.RLock() # Guards runtime bindings.
117
+
118
+ Injectable = t.Union[object, t.Any]
119
+ T = t.TypeVar("T", bound=Injectable)
120
+ Binding = t.Union[type[Injectable], t.Hashable]
121
+ Constructor = t.Callable[
122
+ [],
123
+ t.Union[
124
+ Injectable,
125
+ contextlib.AbstractContextManager[Injectable],
126
+ contextlib.AbstractAsyncContextManager[Injectable],
127
+ ],
128
+ ]
129
+ Provider = Constructor
130
+ BinderCallable = t.Callable[["Binder"], t.Optional["Binder"]]
131
+
132
+
133
+ class ConstructorTypeError(TypeError):
134
+ def __init__(self, constructor: t.Callable, previous_error: TypeError) -> None:
135
+ super().__init__(f"{constructor} raised an error: {previous_error}")
136
+
137
+
138
+ class Binder:
139
+ _bindings: dict[Binding, Constructor]
140
+
141
+ def __init__(self, allow_override: bool = False) -> None: # noqa: FBT001, FBT002
142
+ self._bindings = {}
143
+ self.allow_override = allow_override
144
+
145
+ def install(self, config: BinderCallable) -> Binder:
146
+ """Install another callable configuration."""
147
+ config(self)
148
+ return self
149
+
150
+ def bind(self, cls: Binding, instance: T) -> Binder:
151
+ """Bind a class to an instance."""
152
+ self._check_class(cls)
153
+
154
+ b = lambda: instance # noqa: E731
155
+ self._bindings[cls] = b
156
+ self._maybe_bind_forward(cls, b)
157
+
158
+ logger.debug("Bound %s to an instance %s", cls, instance)
159
+ return self
160
+
161
+ def bind_to_constructor(self, cls: Binding, constructor: Constructor) -> Binder:
162
+ """
163
+ Bind a class to a callable singleton constructor.
164
+
165
+ Raises:
166
+ InjectorException: if no constructor
167
+
168
+ """
169
+ self._check_class(cls)
170
+ if constructor is None:
171
+ raise InjectorException(f"Constructor cannot be None, key={cls}")
172
+
173
+ b = _ConstructorBinding(constructor)
174
+ self._bindings[cls] = b
175
+ self._maybe_bind_forward(cls, b)
176
+
177
+ logger.debug("Bound %s to a constructor %s", cls, constructor)
178
+ return self
179
+
180
+ def bind_to_provider(self, cls: Binding, provider: Provider) -> Binder:
181
+ """
182
+ Bind a class to a callable instance provider executed for each injection.
183
+
184
+ A provider can be a normal function or a context manager.
185
+ Both sync and async are supported.
186
+
187
+ Raises:
188
+ InjectorException: if no provider
189
+
190
+ """
191
+ self._check_class(cls)
192
+ if provider is None:
193
+ raise InjectorException(f"Provider cannot be None, key={cls}")
194
+
195
+ b = provider
196
+ self._bindings[cls] = b
197
+ self._maybe_bind_forward(cls, b)
198
+
199
+ logger.debug("Bound %s to a provider %s", cls, provider)
200
+ return self
201
+
202
+ def _check_class(self, cls: Binding) -> None:
203
+ if cls is None:
204
+ raise InjectorException("Binding key cannot be None")
205
+
206
+ if not self.allow_override and cls in self._bindings:
207
+ raise InjectorException(f"Duplicate binding, key={cls}")
208
+
209
+ if self._is_forward_str(cls):
210
+ ref = t.ForwardRef(cls)
211
+ if not self.allow_override and ref in self._bindings:
212
+ msg = f'Duplicate forward binding, i.e. "int" and int, key={cls}'
213
+ raise InjectorException(msg)
214
+
215
+ def _maybe_bind_forward(self, cls: Binding, binding: t.Any) -> None: # noqa: ANN401
216
+ """Bind a string forward reference."""
217
+ if not _HAS_PEP560_SUPPORT:
218
+ return
219
+ if not isinstance(cls, str):
220
+ return
221
+
222
+ ref = t.ForwardRef(cls)
223
+ self._bindings[ref] = binding
224
+ logger.debug('Bound forward ref "%s"', cls)
225
+
226
+ @staticmethod
227
+ def _is_forward_str(kls: Binding) -> bool:
228
+ return _HAS_PEP560_SUPPORT and isinstance(kls, str)
229
+
230
+
231
+ class Injector:
232
+ _bindings: dict[Binding, Constructor]
233
+
234
+ def __init__(
235
+ self,
236
+ config: t.Optional[BinderCallable] = None,
237
+ # TODO(pyctrl): force following flags to be kwargs
238
+ bind_in_runtime: bool = True, # noqa: FBT001, FBT002
239
+ allow_override: bool = False, # noqa: FBT001, FBT002
240
+ ) -> None:
241
+ self._bind_in_runtime = bind_in_runtime
242
+ if config:
243
+ binder = Binder(allow_override)
244
+ config(binder)
245
+ self._bindings = binder._bindings # noqa: SLF001
246
+ else:
247
+ self._bindings = {}
248
+
249
+ # NOTE(pyctrl): only since 3.12
250
+ # @t.overload
251
+ # def get_instance(self, cls: type[T]) -> T: ...
252
+
253
+ @t.overload
254
+ def get_instance(self, cls: Binding) -> T: ...
255
+
256
+ @t.overload
257
+ def get_instance(self, cls: t.Hashable) -> Injectable: ...
258
+
259
+ def get_instance(self, cls: Binding) -> Injectable:
260
+ """
261
+ Return an instance for a class.
262
+
263
+ Raises:
264
+ InjectorException: on errors
265
+ ConstructorTypeError: over TypeError
266
+
267
+ """
268
+ binding = self._bindings.get(cls)
269
+ if binding:
270
+ return binding()
271
+
272
+ # Try to create a runtime binding.
273
+ with _BINDING_LOCK:
274
+ binding = self._bindings.get(cls)
275
+ if binding:
276
+ return binding()
277
+
278
+ if not self._bind_in_runtime:
279
+ msg = f"No binding was found for key={cls}"
280
+ raise InjectorException(msg)
281
+
282
+ if not callable(cls):
283
+ msg = (
284
+ "Cannot create a runtime binding, the key is not callable,"
285
+ f" key={cls}",
286
+ )
287
+ raise InjectorException(msg)
288
+
289
+ try:
290
+ instance = cls()
291
+ except TypeError as previous_error:
292
+ raise ConstructorTypeError(cls, previous_error) # noqa: B904
293
+
294
+ self._bindings[cls] = lambda: instance
295
+
296
+ msg = "Created a runtime binding for key=%s, instance=%s"
297
+ logger.debug(msg, cls, instance)
298
+ return instance
299
+
300
+
301
+ class InjectorException(Exception):
302
+ pass
303
+
304
+
305
+ class _ConstructorBinding(t.Generic[T]):
306
+ _instance: t.Optional[T]
307
+
308
+ def __init__(self, constructor: t.Callable[[], T]) -> None:
309
+ self._constructor = constructor
310
+ self._created = False
311
+ self._instance = None
312
+
313
+ def __call__(self) -> T:
314
+ if self._created and self._instance is not None:
315
+ return self._instance
316
+
317
+ with _BINDING_LOCK:
318
+ if self._created and self._instance is not None:
319
+ return self._instance
320
+ self._instance = self._constructor()
321
+ self._created = True
322
+ return self._instance
323
+
324
+
325
+ # NOTE(pyctrl): we MUST inherit `_AttributeInjection` from `property`
326
+ # 0. (personal opinion, based on a bunch of cases including this one)
327
+ # dataclasses are mess
328
+ # 1. dataclasses treat all non-`property` descriptors by the very specific logic
329
+ # https://docs.python.org/3/library/dataclasses.html#descriptor-typed-fields
330
+ # 2. and treat `property` descriptors in a special way — like we used to know:
331
+ # ```
332
+ # @dataclass
333
+ # class MyDataclass:
334
+ # @property
335
+ # def my_prop(self) -> int:
336
+ # return 42
337
+ # MyDataclass.my_prop # gives '<property at 0x73055337f150>' on class
338
+ # MyDataclass().my_prop # and on instance will show you '42'
339
+ # ```
340
+ # it behaves the same in the case of alternative notation:
341
+ # ```
342
+ # @dataclass
343
+ # class MyDataclass2:
344
+ # my_prop = property(fget=lambda _: 42)
345
+ # MyDataclass2.my_prop # gives '<property at 0x73055337ec00>' on class
346
+ # MyDataclass2().my_prop # and on instance will show you '42'
347
+ # ```
348
+ # which is more relevant to the `inject.attr` case
349
+ # 3. but the behavior around `property`-ies has an exception
350
+ # - you can't annotate `property` attribute when using the second notation
351
+ # (this one `my_prop: int = property(fget=lambda _: 42)` will fail)
352
+ # - so the type hinting the very matters
353
+ # - in this case dataclasses don't treat class member as property
354
+ # (even if it's inherited from `property` or used directly)
355
+ # - dataclasses behave greedy when discover their attributes
356
+ # and class member annotations are "must have" markers
357
+ # 4. so for `inject.attr`s case we should follow 2 rules:
358
+ # - `attr` implementation is inherited from `property`
359
+ # - `attr` class member is not annotated
360
+ class _AttributeInjection(property):
361
+ def __init__(self, cls: t.Union[type[T], t.Hashable]) -> None:
362
+ self._cls = cls
363
+ super().__init__(
364
+ fget=lambda _: instance(self._cls),
365
+ doc="Return an attribute injection",
366
+ )
367
+
368
+ def __set_name__(self, owner: type[T], name: str) -> None:
369
+ if self._cls is _MISSING:
370
+ self._cls = _unwrap_cls_annotation(owner, name)
371
+
372
+
373
+ class _ParameterInjection(t.Generic[T]):
374
+ __slots__ = ("_cls", "_name")
375
+
376
+ def __init__(self, name: str, cls: t.Optional[Binding] = None) -> None:
377
+ self._name = name
378
+ self._cls = cls
379
+
380
+ def __call__(
381
+ self, func: t.Callable[..., t.Union[T, t.Awaitable[T]]]
382
+ ) -> t.Callable[..., t.Union[T, t.Awaitable[T]]]:
383
+ if inspect.iscoroutinefunction(func):
384
+
385
+ @functools.wraps(func)
386
+ async def async_injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
387
+ if self._name not in kwargs:
388
+ kwargs[self._name] = instance(self._cls or self._name)
389
+ async_func = t.cast("t.Callable[..., t.Awaitable[T]]", func)
390
+ return await async_func(*args, **kwargs)
391
+
392
+ return async_injection_wrapper
393
+
394
+ @functools.wraps(func)
395
+ def injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
396
+ if self._name not in kwargs:
397
+ kwargs[self._name] = instance(self._cls or self._name)
398
+ sync_func = t.cast("t.Callable[..., T]", func)
399
+ return sync_func(*args, **kwargs)
400
+
401
+ return injection_wrapper
402
+
403
+
404
+ class _ParametersInjection(t.Generic[T]):
405
+ __slots__ = ("_params",)
406
+
407
+ def __init__(self, **kwargs: Binding) -> None:
408
+ self._params = kwargs
409
+
410
+ @staticmethod
411
+ def _aggregate_sync_stack(
412
+ sync_stack: contextlib.ExitStack,
413
+ provided_params: frozenset[str],
414
+ kwargs: dict[str, t.Any],
415
+ ) -> None:
416
+ """
417
+ Manage context stack.
418
+
419
+ Extracts context managers, aggregate them in an ExitStack
420
+ and swap out the param value with results of running `__enter__()`.
421
+ The result is equivalent to using `with` multiple times.
422
+ """
423
+ executed_kwargs = {
424
+ param: sync_stack.enter_context(inst)
425
+ for param, inst in kwargs.items()
426
+ if param not in provided_params
427
+ and isinstance(inst, contextlib.AbstractContextManager)
428
+ }
429
+ kwargs.update(executed_kwargs)
430
+
431
+ @staticmethod
432
+ async def _aggregate_async_stack(
433
+ async_stack: contextlib.AsyncExitStack,
434
+ provided_params: frozenset[str],
435
+ kwargs: dict[str, t.Any],
436
+ ) -> None:
437
+ """Similar to _aggregate_sync_stack, but for async context managers."""
438
+ executed_kwargs = {
439
+ param: await async_stack.enter_async_context(inst)
440
+ for param, inst in kwargs.items()
441
+ if param not in provided_params
442
+ and isinstance(inst, contextlib.AbstractAsyncContextManager)
443
+ }
444
+ kwargs.update(executed_kwargs)
445
+
446
+ def __call__(
447
+ self, func: t.Callable[..., t.Union[t.Awaitable[T], T]]
448
+ ) -> t.Callable[..., t.Union[t.Awaitable[T], T]]:
449
+ arg_names = inspect.getfullargspec(func).args
450
+ params_to_provide = self._params
451
+
452
+ if inspect.iscoroutinefunction(func):
453
+
454
+ @functools.wraps(func)
455
+ async def async_injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
456
+ provided_params = frozenset(arg_names[: len(args)]) | frozenset(
457
+ kwargs.keys()
458
+ )
459
+ for param, cls in params_to_provide.items():
460
+ if param not in provided_params:
461
+ kwargs[param] = instance(cls)
462
+ async_func = t.cast("t.Callable[..., t.Awaitable[T]]", func)
463
+ try:
464
+ with contextlib.ExitStack() as sync_stack:
465
+ async with contextlib.AsyncExitStack() as async_stack:
466
+ self._aggregate_sync_stack(
467
+ sync_stack, provided_params, kwargs
468
+ )
469
+ await self._aggregate_async_stack(
470
+ async_stack, provided_params, kwargs
471
+ )
472
+ return await async_func(*args, **kwargs)
473
+ except TypeError as previous_error:
474
+ raise ConstructorTypeError(func, previous_error) # noqa: B904
475
+
476
+ return async_injection_wrapper
477
+
478
+ @functools.wraps(func)
479
+ def injection_wrapper(*args: t.Any, **kwargs: t.Any) -> T: # noqa: ANN401
480
+ provided_params = frozenset(arg_names[: len(args)]) | frozenset(
481
+ kwargs.keys()
482
+ )
483
+ for param, cls in params_to_provide.items():
484
+ if param not in provided_params:
485
+ kwargs[param] = instance(cls)
486
+ sync_func = t.cast("t.Callable[..., T]", func)
487
+ try:
488
+ with contextlib.ExitStack() as sync_stack:
489
+ self._aggregate_sync_stack(sync_stack, provided_params, kwargs)
490
+ return sync_func(*args, **kwargs)
491
+ except TypeError as previous_error:
492
+ raise ConstructorTypeError(func, previous_error) # noqa: B904
493
+
494
+ return injection_wrapper
495
+
496
+
497
+ def configure(
498
+ config: t.Optional[BinderCallable] = None,
499
+ # TODO(pyctrl): force following flags to be kwargs
500
+ bind_in_runtime: bool = True, # noqa: FBT001, FBT002
501
+ allow_override: bool = False, # noqa: FBT001, FBT002
502
+ clear: bool = False, # noqa: FBT001, FBT002
503
+ once: bool = False, # noqa: FBT001, FBT002
504
+ ) -> Injector:
505
+ """
506
+ Create an injector using callable config.
507
+
508
+ Raises:
509
+ InjectorException: if already configured.
510
+
511
+ """
512
+ global _INJECTOR # noqa: PLW0603
513
+
514
+ if clear and once:
515
+ msg = "clear and once are mutually exclusive, only one can be True"
516
+ raise InjectorException(msg)
517
+
518
+ with _INJECTOR_LOCK:
519
+ if _INJECTOR:
520
+ if clear:
521
+ _clear_injector()
522
+ elif once:
523
+ return _INJECTOR
524
+ else:
525
+ raise InjectorException("Injector is already configured")
526
+
527
+ _INJECTOR = Injector(
528
+ config,
529
+ bind_in_runtime=bind_in_runtime,
530
+ allow_override=allow_override,
531
+ )
532
+ logger.debug("Created and configured an injector, config=%s", config)
533
+ return _INJECTOR
534
+
535
+
536
+ def configure_once(
537
+ config: t.Optional[BinderCallable] = None,
538
+ # TODO(pyctrl): force following flags to be kwargs
539
+ bind_in_runtime: bool = True, # noqa: FBT001, FBT002
540
+ allow_override: bool = False, # noqa: FBT001, FBT002
541
+ ) -> Injector:
542
+ """
543
+ Create an injector with a callable config if not present, otherwise, do nothing.
544
+
545
+ Deprecated, use `configure(once=True)` instead.
546
+ """
547
+ with _INJECTOR_LOCK:
548
+ if _INJECTOR:
549
+ return _INJECTOR
550
+
551
+ return configure(
552
+ config, bind_in_runtime=bind_in_runtime, allow_override=allow_override
553
+ )
554
+
555
+
556
+ def clear_and_configure(
557
+ config: t.Optional[BinderCallable] = None,
558
+ # TODO(pyctrl): force following flags to be kwargs
559
+ bind_in_runtime: bool = True, # noqa: FBT001, FBT002
560
+ allow_override: bool = False, # noqa: FBT001, FBT002
561
+ ) -> Injector:
562
+ """
563
+ Clear an existing injector and create another one with a callable config.
564
+
565
+ Deprecated, use configure(clear=True) instead.
566
+ """
567
+ with _INJECTOR_LOCK:
568
+ _clear_injector()
569
+ return configure(
570
+ config,
571
+ bind_in_runtime=bind_in_runtime,
572
+ allow_override=allow_override,
573
+ )
574
+
575
+
576
+ def is_configured() -> bool:
577
+ """Return true if an injector is already configured."""
578
+ with _INJECTOR_LOCK:
579
+ return _INJECTOR is not None
580
+
581
+
582
+ def clear() -> None:
583
+ """Clear an existing injector if present."""
584
+ _clear_injector()
585
+
586
+
587
+ def _clear_injector() -> None:
588
+ """Clear an existing injector if present."""
589
+ global _INJECTOR # noqa: PLW0603
590
+
591
+ with _INJECTOR_LOCK:
592
+ if _INJECTOR is None:
593
+ return
594
+
595
+ _INJECTOR = None
596
+ logger.debug("Cleared an injector")
597
+
598
+
599
+ @t.overload
600
+ def instance(cls: type[T]) -> T: ...
601
+
602
+
603
+ @t.overload
604
+ def instance(cls: t.Hashable) -> Injectable: ...
605
+
606
+
607
+ def instance(cls: Binding) -> Injectable:
608
+ """Inject an instance of a class."""
609
+ return get_injector_or_die().get_instance(cls)
610
+
611
+
612
+ @t.overload
613
+ def attr() -> Injectable: ...
614
+
615
+
616
+ @t.overload
617
+ def attr(cls: t.Hashable) -> Injectable: ...
618
+
619
+
620
+ @t.overload
621
+ def attr(cls: type[T]) -> T: ...
622
+
623
+
624
+ def attr(cls=_MISSING):
625
+ """Return an attribute injection (descriptor)."""
626
+ return _AttributeInjection(cls)
627
+
628
+
629
+ # Deprecated, use `attr`
630
+ attr_dc = attr
631
+
632
+
633
+ def param(name: str, cls: t.Optional[Binding] = None) -> t.Callable:
634
+ """
635
+ Return a decorator which injects an arg into a function.
636
+
637
+ Deprecated, use @inject.params.
638
+ """
639
+ return _ParameterInjection(name, cls)
640
+
641
+
642
+ def params(**args_to_classes: Binding) -> t.Callable:
643
+ """
644
+ Return a decorator which injects args into a function.
645
+
646
+ For example::
647
+
648
+ @inject.params(cache=RedisCache, db=DbInterface)
649
+ def sign_up(name, email, cache, db):
650
+ pass
651
+ """
652
+ return _ParametersInjection(**args_to_classes)
653
+
654
+
655
+ @t.overload
656
+ def autoparams(fn: t.Callable[P, T]) -> t.Callable[P, T]: ...
657
+
658
+
659
+ @t.overload
660
+ def autoparams(*selected: str) -> t.Callable[[T], T]: ...
661
+
662
+
663
+ def autoparams(*selected: t.Callable[P, T] | str) -> t.Callable[..., T]:
664
+ """
665
+ Return a decorator injecting args based on function type hints, only since 3.5.
666
+
667
+ For example::
668
+
669
+ @inject.autoparams
670
+ def refresh_cache(cache: RedisCache, db: DbInterface):
671
+ pass
672
+
673
+ There is an option to specify which arguments we want to
674
+ inject without attempts of injecting everything:
675
+
676
+ For example::
677
+
678
+ @inject.autoparams('cache', 'db')
679
+ def sign_up(name, email, cache: RedisCache, db: DbInterface):
680
+ pass
681
+ """
682
+ only_these: set[str] = set()
683
+
684
+ def autoparams_decorator(fn: t.Callable[..., T]) -> t.Callable[..., T]:
685
+ if inspect.isclass(fn):
686
+ types = t.get_type_hints(fn.__init__)
687
+ else:
688
+ types = t.get_type_hints(fn)
689
+
690
+ # Skip the return annotation.
691
+ types = {name: typ for name, typ in types.items() if name != _RETURN}
692
+
693
+ # Convert Union types into single types, i.e. Union[A, None] => A.
694
+ types = {name: _unwrap_union_arg(typ) for name, typ in types.items()}
695
+
696
+ # Filter types if selected args present.
697
+ if only_these:
698
+ types = {name: typ for name, typ in types.items() if name in only_these}
699
+
700
+ wrapper: _ParametersInjection[T] = _ParametersInjection(**types)
701
+ return wrapper(fn)
702
+
703
+ target = selected[0] if selected else None
704
+ if len(selected) == 1 and callable(target):
705
+ return autoparams_decorator(target)
706
+
707
+ only_these.update(selected)
708
+ return autoparams_decorator
709
+
710
+
711
+ def get_injector() -> t.Optional[Injector]:
712
+ """Return the current injector or None."""
713
+ return _INJECTOR
714
+
715
+
716
+ def get_injector_or_die() -> Injector:
717
+ """
718
+ Return the current injector or raise an InjectorException.
719
+
720
+ Raises:
721
+ InjectorException: If injector is not configured.
722
+
723
+ Returns:
724
+ Configured injector.
725
+
726
+ """
727
+ injector = _INJECTOR
728
+ if not injector:
729
+ raise InjectorException("No injector is configured")
730
+
731
+ return injector
732
+
733
+
734
+ def _unwrap_union_arg(typ: type) -> type:
735
+ """Return the first type A in typing.Union[A, B] or typ if not Union."""
736
+ if not _is_union_type(typ):
737
+ return typ
738
+ return typ.__args__[0]
739
+
740
+
741
+ def _is_union_type(typ: type) -> bool:
742
+ """
743
+ Test if the type is a union type.
744
+
745
+ Examples::
746
+ is_union_type(int) == False
747
+ is_union_type(Union) == True
748
+ is_union_type(Union[int, int]) == False
749
+ is_union_type(Union[T, int]) == True
750
+
751
+ Source: https://github.com/ilevkivskyi/typing_inspect/blob/master/typing_inspect.py
752
+ """
753
+ if _HAS_PEP604_SUPPORT:
754
+ return (
755
+ typ is t.Union
756
+ or isinstance(typ, UnionType)
757
+ or (isinstance(typ, _GenericAlias) and typ.__origin__ is t.Union)
758
+ )
759
+ if _HAS_PEP560_SUPPORT:
760
+ return typ is t.Union or (
761
+ isinstance(typ, _GenericAlias) and typ.__origin__ is t.Union
762
+ )
763
+ return type(typ) is _Union
764
+
765
+
766
+ def _unwrap_cls_annotation(cls: type, attr_name: str) -> type:
767
+ types = t.get_type_hints(cls)
768
+ try:
769
+ attr_type = types[attr_name]
770
+ except KeyError:
771
+ msg = f"Couldn't find type annotation for {attr_name}"
772
+ raise InjectorException(msg) from None
773
+
774
+ return _unwrap_union_arg(attr_type)
inject/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '5.4.0'
22
+ __version_tuple__ = version_tuple = (5, 4, 0)
23
+
24
+ __commit_id__ = commit_id = None
inject/py.typed ADDED
File without changes
@@ -0,0 +1,364 @@
1
+ Metadata-Version: 2.4
2
+ Name: inject
3
+ Version: 5.4.0
4
+ Summary: Python dependency injection framework.
5
+ Project-URL: homepage, https://github.com/ivankorobkov/python-inject
6
+ Project-URL: source, https://github.com/ivankorobkov/python-inject
7
+ Project-URL: issues, https://github.com/ivankorobkov/python-inject/issues
8
+ Author-email: Ivan Korobkov <ivan.korobkov@gmail.com>
9
+ Maintainer-email: Ivan Korobkov <ivan.korobkov@gmail.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+
28
+ # python-inject [![Build Status](https://travis-ci.org/ivankorobkov/python-inject.svg?branch=master)](https://travis-ci.org/ivankorobkov/python-inject)
29
+ Dependency injection the python way, the good way.
30
+
31
+ ## Key features
32
+ * Fast.
33
+ * Thread-safe.
34
+ * Simple to use.
35
+ * Does not steal class constructors.
36
+ * Does not try to manage your application object graph.
37
+ * Transparently integrates into tests.
38
+ * Autoparams leveraging type annotations.
39
+ * Supports type hinting in Python 3.5+.
40
+ * Supports Python 3.9+ (`v5.*`), 3.5-3.8 (`v4.*`) and Python 2.7–3.5 (`v3.*`).
41
+ * Supports context managers.
42
+
43
+ ## Python Support
44
+
45
+ | Python | Inject Version |
46
+ |---------|----------------|
47
+ | 3.9+ | 5.0+ |
48
+ | 3.6-3.8 | 4.1+, < 5.0 |
49
+ | 3.5 | 4.0 |
50
+ | < 3.5 | 3.* |
51
+
52
+
53
+ ## Installation
54
+ Use pip to install the lastest version:
55
+
56
+ ```bash
57
+ pip install inject
58
+ ```
59
+
60
+ ## Autoparams example
61
+ `@inject.autoparams` returns a decorator which automatically injects arguments into a function
62
+ that uses type annotations. This is supported only in Python >= 3.5.
63
+
64
+ ```python
65
+ @inject.autoparams
66
+ def refresh_cache(cache: RedisCache, db: DbInterface):
67
+ pass
68
+ ```
69
+
70
+ There is an option to specify which arguments we want to inject without attempts of
71
+ injecting everything:
72
+
73
+ ```python
74
+ @inject.autoparams('cache', 'db')
75
+ def sign_up(name, email, cache: RedisCache, db: DbInterface):
76
+ pass
77
+ ```
78
+
79
+ It is also acceptable to use explicit curly braces notation (`@inject.autoparams()`)
80
+ for non-parameterized decorations — it will be treated the same as `@inject.autoparams`.
81
+
82
+ ## Step-by-step example
83
+ ```python
84
+ # Import the inject module.
85
+ import inject
86
+
87
+
88
+ # `inject.instance` requests dependencies from the injector.
89
+ def foo(bar):
90
+ cache = inject.instance(Cache)
91
+ cache.save('bar', bar)
92
+
93
+
94
+ # `inject.params` injects dependencies as keyword arguments or positional argument.
95
+ # Also you can use @inject.autoparams in Python 3.5, see the example above.
96
+ @inject.params(cache=Cache, user=CurrentUser)
97
+ def baz(foo, cache=None, user=None):
98
+ cache.save('foo', foo, user)
99
+
100
+ # this can be called in different ways:
101
+ # with injected arguments
102
+ baz('foo')
103
+
104
+ # with positional arguments
105
+ baz('foo', my_cache)
106
+
107
+ # with keyword arguments
108
+ baz('foo', my_cache, user=current_user)
109
+
110
+
111
+ # `inject.param` is deprecated, use `inject.params` instead.
112
+ @inject.param('cache', Cache)
113
+ def bar(foo, cache=None):
114
+ cache.save('foo', foo)
115
+
116
+
117
+ # `inject.attr` creates properties (descriptors) which request dependencies on access.
118
+ class User(object):
119
+ cache = inject.attr(Cache)
120
+
121
+ def __init__(self, id):
122
+ self.id = id
123
+
124
+ def save(self):
125
+ self.cache.save('users', self)
126
+
127
+ @classmethod
128
+ def load(cls, id):
129
+ return cls.cache.load('users', id)
130
+
131
+
132
+ # Create an optional configuration.
133
+ def my_config(binder):
134
+ binder.bind(Cache, RedisCache('localhost:1234'))
135
+
136
+ # Configure a shared injector.
137
+ inject.configure(my_config)
138
+
139
+
140
+ # Instantiate User as a normal class. Its `cache` dependency is injected when accessed.
141
+ user = User(10)
142
+ user.save()
143
+
144
+ # Call the functions, the dependencies are automatically injected.
145
+ foo('Hello')
146
+ bar('world')
147
+ ```
148
+
149
+
150
+ ## Context managers
151
+ Binding a class to an instance of a context manager (through `bind` or `bind_to_constructor`)
152
+ or to a function decorated as a context manager leads to the context manager to be used as is,
153
+ not via with statement.
154
+
155
+ ```python
156
+ @contextlib.contextmanager
157
+ def get_file_sync():
158
+ obj = MockFile()
159
+ yield obj
160
+ obj.destroy()
161
+
162
+ @contextlib.asynccontextmanager
163
+ async def get_conn_async():
164
+ obj = MockConnection()
165
+ yield obj
166
+ obj.destroy()
167
+
168
+ def config(binder):
169
+ binder.bind_to_provider(MockFile, get_file_sync)
170
+ binder.bind(int, 100)
171
+ binder.bind_to_provider(str, lambda: "Hello")
172
+ binder.bind_to_provider(MockConnection, get_conn_sync)
173
+
174
+ inject.configure(config)
175
+
176
+ @inject.autoparams()
177
+ def example(conn: MockConnection, file: MockFile):
178
+ # Connection and file will be automatically destroyed on exit.
179
+ pass
180
+ ```
181
+
182
+
183
+ ## Usage with Django
184
+ Django can load some modules multiple times which can lead to
185
+ `InjectorException: Injector is already configured`. You can use `configure(once=True)` which
186
+ is guaranteed to run only once when the injector is absent:
187
+ ```python
188
+ import inject
189
+ inject.configure(my_config, once=True)
190
+ ```
191
+
192
+ ## Testing
193
+ In tests use `inject.configure(callable, clear=True)` to create a new injector on setup,
194
+ and optionally `inject.clear()` to clean up on tear down:
195
+ ```python
196
+ class MyTest(unittest.TestCase):
197
+ def setUp(self):
198
+ inject.configure(lambda binder: binder
199
+ .bind(Cache, MockCache()) \
200
+ .bind(Validator, TestValidator()),
201
+ clear=True)
202
+
203
+ def tearDown(self):
204
+ inject.clear()
205
+ ```
206
+
207
+ ## Composable configurations
208
+ You can reuse configurations and override already registered dependencies to fit the needs
209
+ in different environments or specific tests.
210
+ ```python
211
+ def base_config(binder):
212
+ # ... more dependencies registered here
213
+ binder.bind(Validator, RealValidator())
214
+ binder.bind(Cache, RedisCache('localhost:1234'))
215
+
216
+ def tests_config(binder):
217
+ # reuse existing configuration
218
+ binder.install(base_config)
219
+
220
+ # override only certain dependencies
221
+ binder.bind(Validator, TestValidator())
222
+ binder.bind(Cache, MockCache())
223
+
224
+ inject.configure(tests_config, allow_override=True, clear=True)
225
+
226
+ ```
227
+
228
+ ## Thread-safety
229
+ After configuration the injector is thread-safe and can be safely reused by multiple threads.
230
+
231
+ ## Binding types
232
+ **Instance** bindings always return the same instance:
233
+
234
+ ```python
235
+ redis = RedisCache(address='localhost:1234')
236
+ def config(binder):
237
+ binder.bind(Cache, redis)
238
+ ```
239
+
240
+ **Constructor** bindings create a singleton on injection:
241
+
242
+ ```python
243
+ def config(binder):
244
+ # Creates a redis cache singleton on first injection.
245
+ binder.bind_to_constructor(Cache, lambda: RedisCache(address='localhost:1234'))
246
+ ```
247
+
248
+ **Provider** bindings call the provider on injection:
249
+
250
+ ```python
251
+ def get_my_thread_local_cache():
252
+ pass
253
+
254
+ def config(binder):
255
+ # Executes the provider on each injection.
256
+ binder.bind_to_provider(Cache, get_my_thread_local_cache)
257
+ ```
258
+
259
+ **Runtime** bindings automatically create singletons on injection, require no configuration.
260
+ For example, only the `Config` class binding is present, other bindings are runtime:
261
+
262
+ ```python
263
+ class Config(object):
264
+ pass
265
+
266
+ class Cache(object):
267
+ config = inject.attr(Config)
268
+
269
+ class Db(object):
270
+ config = inject.attr(Config)
271
+
272
+ class User(object):
273
+ cache = inject.attr(Cache)
274
+ db = inject.attr(Db)
275
+
276
+ @classmethod
277
+ def load(cls, user_id):
278
+ return cls.cache.load('users', user_id) or cls.db.load('users', user_id)
279
+
280
+ inject.configure(lambda binder: binder.bind(Config, load_config_file()))
281
+ user = User.load(10)
282
+ ```
283
+ ## Disabling runtime binding
284
+ Sometimes runtime binding leads to unexpected behaviour. Say if you forget
285
+ to bind an instance to a class, `inject` will try to implicitly instantiate it.
286
+
287
+ If an instance is unintentionally created with default arguments it may lead to
288
+ hard-to-debug bugs. To disable runtime binding and make sure that only
289
+ explicitly bound instances are injected, pass `bind_in_runtime=False` to `inject.configure`.
290
+
291
+ In this case `inject` immediately raises `InjectorException` when the code
292
+ tries to get an unbound instance.
293
+
294
+ ## Keys
295
+ It is possible to use any hashable object as a binding key. For example:
296
+
297
+ ```python
298
+ import inject
299
+
300
+ inject.configure(lambda binder: \
301
+ binder.bind('host', 'localhost') \
302
+ binder.bind('port', 1234))
303
+ ```
304
+
305
+ ## Why no scopes?
306
+ I've used Guice and Spring in Java for a lot of years, and I don't like their scopes.
307
+ `python-inject` by default creates objects as singletons. It does not need a prototype scope
308
+ as in Spring or NO_SCOPE as in Guice because `python-inject` does not steal your class
309
+ constructors. Create instances the way you like and then inject dependencies into them.
310
+
311
+ Other scopes such as a request scope or a session scope are fragile, introduce high coupling,
312
+ and are difficult to test. In `python-inject` write custom providers which can be thread-local,
313
+ request-local, etc.
314
+
315
+ For example, a thread-local current user provider:
316
+
317
+ ```python
318
+ import inject
319
+ import threading
320
+
321
+ # Given a user class.
322
+ class User(object):
323
+ pass
324
+
325
+ # Create a thread-local current user storage.
326
+ _LOCAL = threading.local()
327
+
328
+ def get_current_user():
329
+ return getattr(_LOCAL, 'user', None)
330
+
331
+ def set_current_user(user):
332
+ _LOCAL.user = user
333
+
334
+ # Bind User to a custom provider.
335
+ inject.configure(lambda binder: binder.bind_to_provider(User, get_current_user))
336
+
337
+ # Inject the current user.
338
+ @inject.params(user=User)
339
+ def foo(user):
340
+ pass
341
+ ```
342
+
343
+ ## Links
344
+ * Project: https://github.com/ivankorobkov/python-inject
345
+
346
+ ## License
347
+ Apache License 2.0
348
+
349
+ ## Contributors
350
+ * Ivan Korobkov [@ivankorobkov](https://github.com/ivankorobkov)
351
+ * Jaime Wyant [@jaimewyant](https://github.com/jaimewyant)
352
+ * Sebastian Buczyński [@Enforcer](https://github.com/Enforcer)
353
+ * Oleksandr Fedorov [@Fedorof](https://github.com/Fedorof)
354
+ * cselvaraj [@cselvaraj](https://github.com/cselvaraj)
355
+ * 陆雨晴 [@SixExtreme](https://github.com/SixExtreme)
356
+ * Andrew William Borba [@andrewborba10](https://github.com/andrewborba10)
357
+ * jdmeyer3 [@jdmeyer3](https://github.com/jdmeyer3)
358
+ * Alex Grover [@ajgrover](https://github.com/ajgrover)
359
+ * Harro van der Kroft [@wisepotato](https://github.com/wisepotato)
360
+ * Samiur Rahman [@samiur](https://github.com/samiur)
361
+ * 45deg [@45deg](https://github.com/45deg)
362
+ * Alexander Nicholas Costas [@ancostas](https://github.com/ancostas)
363
+ * Dmitry Balabka [@dbalabka](https://github.com/dbalabka)
364
+ * Dima Burmistrov [@pyctrl](https://github.com/pyctrl)
@@ -0,0 +1,7 @@
1
+ inject/__init__.py,sha256=MuOsUjyTAP-tLLmGN5b-YwlC-WMKrgI2pv7NofNAxik,24292
2
+ inject/_version.py,sha256=rjYYiDuH70jBUooDgzK9RqknoeUzpbWyI0r8auWj3DI,520
3
+ inject/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ inject-5.4.0.dist-info/METADATA,sha256=hBf2pXd-plZgg88FWSz9UtCg0EUmk8p_84wbDLs4s50,10937
5
+ inject-5.4.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ inject-5.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
7
+ inject-5.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.