-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathinjector.py
1281 lines (990 loc) · 39.8 KB
/
injector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
#
# Copyright (C) 2010 Alec Thomas <[email protected]>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# Author: Alec Thomas <[email protected]>
"""Injector - Python dependency injection framework, inspired by Guice
:copyright: (c) 2012 by Alec Thomas
:license: BSD
"""
import functools
import inspect
import itertools
import logging
import sys
import threading
import types
import warnings
from abc import ABCMeta, abstractmethod
from collections import namedtuple
from typing import Any, Generic, get_type_hints, TypeVar, Union
TYPING353 = hasattr(Union[str, int], '__origin__')
__author__ = 'Alec Thomas <[email protected]>'
__version__ = '0.14.0'
__version_tag__ = ''
log = logging.getLogger('injector')
log.addHandler(logging.NullHandler())
if log.level == logging.NOTSET:
log.setLevel(logging.WARN)
def private(something):
something.__private__ = True
return something
def synchronized(lock):
def outside_wrapper(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
with lock:
return function(*args, **kwargs)
return wrapper
return outside_wrapper
lock = threading.RLock()
def reraise(original, exception, maximum_frames=1):
prev_cls, prev, tb = sys.exc_info()
frames = inspect.getinnerframes(tb)
if len(frames) > maximum_frames:
exception = original
raise exception.with_traceback(tb)
class Error(Exception):
"""Base exception."""
class UnsatisfiedRequirement(Error):
"""Requirement could not be satisfied."""
def __str__(self):
on = '%s has an ' % _describe(self.args[0]) if self.args[0] else ''
return '%sunsatisfied requirement on %s' % (
on, _describe(self.args[1].interface),)
class CallError(Error):
"""Call to callable object fails."""
def __str__(self):
if len(self.args) == 1:
return self.args[0]
instance, method, args, kwargs, original_error, stack = self.args
if hasattr(method, 'im_class'):
instance = method.__self__
method_name = method.__func__.__name__
else:
method_name = method.__name__
cls = instance.__class__.__name__ if instance is not None else ''
full_method = '.'.join((cls, method_name)).strip('.')
parameters = ', '.join(itertools.chain(
(repr(arg) for arg in args),
('%s=%r' % (key, value) for (key, value) in kwargs.items())
))
return 'Call to %s(%s) failed: %s (injection stack: %r)' % (
full_method, parameters, original_error, [level[0] for level in stack])
class CircularDependency(Error):
"""Circular dependency detected."""
class UnknownProvider(Error):
"""Tried to bind to a type whose provider couldn't be determined."""
class Provider:
"""Provides class instances."""
__metaclass__ = ABCMeta
@abstractmethod
def get(self, injector):
raise NotImplementedError
class ClassProvider(Provider):
"""Provides instances from a given class, created using an Injector."""
def __init__(self, cls):
self._cls = cls
def get(self, injector):
return injector.create_object(self._cls)
class CallableProvider(Provider):
"""Provides something using a callable.
The callable is called every time new value is requested from the provider.
::
>>> key = Key('key')
>>> def factory():
... print('providing')
... return []
...
>>> def configure(binder):
... binder.bind(key, to=CallableProvider(factory))
...
>>> injector = Injector(configure)
>>> injector.get(key) is injector.get(key)
providing
providing
False
"""
def __init__(self, callable):
self._callable = callable
def get(self, injector):
return injector.call_with_injection(self._callable)
def __repr__(self):
return '%s(%r)' % (type(self).__name__, self._callable)
class InstanceProvider(Provider):
"""Provide a specific instance.
::
>>> my_list = Key('my_list')
>>> def configure(binder):
... binder.bind(my_list, to=InstanceProvider([]))
...
>>> injector = Injector(configure)
>>> injector.get(my_list) is injector.get(my_list)
True
>>> injector.get(my_list).append('x')
>>> injector.get(my_list)
['x']
"""
def __init__(self, instance):
self._instance = instance
def get(self, injector):
return self._instance
def __repr__(self):
return '%s(%r)' % (type(self).__name__, self._instance)
@private
class ListOfProviders(Provider):
"""Provide a list of instances via other Providers."""
def __init__(self):
self._providers = []
def append(self, provider):
self._providers.append(provider)
def get(self, injector):
return [provider.get(injector) for provider in self._providers]
def __repr__(self):
return '%s(%r)' % (type(self).__name__, self._providers)
class MultiBindProvider(ListOfProviders):
"""Used by :meth:`Binder.multibind` to flatten results of providers that
return sequences."""
def get(self, injector):
return [i for provider in self._providers for i in provider.get(injector)]
class MapBindProvider(ListOfProviders):
"""A provider for map bindings."""
def get(self, injector):
map = {}
for provider in self._providers:
map.update(provider.get(injector))
return map
@private
class BindingKey(tuple):
"""A key mapping to a Binding."""
def __new__(cls, what):
if isinstance(what, list):
if len(what) != 1:
raise Error('list bindings must have a single interface '
'element')
what = (list, BindingKey(what[0]))
elif isinstance(what, dict):
if len(what) != 1:
raise Error('dictionary bindings must have a single interface '
'key and value')
what = (dict, BindingKey(list(what.items())[0]))
return tuple.__new__(cls, (what,))
@property
def interface(self):
return self[0]
_BindingBase = namedtuple('_BindingBase', 'interface provider scope')
@private
class Binding(_BindingBase):
"""A binding from an (interface,) to a provider in a scope."""
class Binder:
"""Bind interfaces to implementations.
.. note:: This class is instantiated internally for you and there's no need
to instantiate it on your own.
"""
@private
def __init__(self, injector, auto_bind=True, parent=None, scope=None):
"""Create a new Binder.
:param injector: Injector we are binding for.
:param auto_bind: Whether to automatically bind missing types.
:param parent: Parent binder.
:param scope: Default scope used, when no scope is provided
in :meth:`Binder.bind` method. :class:`NoScope` is used by default.
"""
self.injector = injector
self._auto_bind = auto_bind
self._bindings = {}
self.parent = parent
self.scope = scope or NoScope
def bind(self, interface, to=None, scope=None):
"""Bind an interface to an implementation.
:param interface: Interface or :func:`Key` to bind.
:param to: Instance or class to bind to, or an explicit
:class:`Provider` subclass.
:param scope: Optional :class:`Scope` in which to bind.
"""
if type(interface) is type and issubclass(interface, (BaseMappingKey, BaseSequenceKey)):
return self.multibind(interface, to, scope=scope)
key = BindingKey(interface)
self._bindings[key] = \
self.create_binding(interface, to, scope)
def bind_scope(self, scope):
"""Bind a Scope.
:param scope: Scope class.
"""
self.bind(scope, to=scope(self.injector))
def multibind(self, interface, to, scope=None):
"""Creates or extends a multi-binding.
A multi-binding maps from a key to a sequence, where each element in
the sequence is provided separately.
:param interface: :func:`MappingKey` or :func:`SequenceKey` to bind to.
:param to: Instance, class to bind to, or an explicit :class:`Provider`
subclass. Must provide a sequence.
:param scope: Optional Scope in which to bind.
"""
key = BindingKey(interface)
if key not in self._bindings:
if (
isinstance(interface, dict) or
isinstance(interface, type) and issubclass(interface, dict)):
provider = MapBindProvider()
else:
provider = MultiBindProvider()
binding = self.create_binding(interface, provider, scope)
self._bindings[key] = binding
else:
binding = self._bindings[key]
provider = binding.provider
assert isinstance(provider, ListOfProviders)
provider.append(self.provider_for(key.interface, to))
def install(self, module):
"""Install a module into this binder.
In this context the module is one of the following:
* function taking the :class:`Binder` as it's only parameter
::
def configure(binder):
bind(str, to='s')
binder.install(configure)
* instance of :class:`Module` (instance of it's subclass counts)
::
class MyModule(Module):
def configure(self, binder):
binder.bind(str, to='s')
binder.install(MyModule())
* subclass of :class:`Module` - the subclass needs to be instantiable so if it
expects any parameters they need to be injected
::
binder.install(MyModule)
"""
if (
hasattr(module, '__bindings__') or
hasattr(getattr(module, 'configure', None), '__bindings__') or
hasattr(getattr(module, '__init__', None), '__bindings__')
):
warnings.warn(
'Injector Modules (ie. %s) constructors and their configure methods should '
'not have injectable parameters. This can result in non-deterministic '
'initialization. If you need injectable objects in order to provide something '
' you can use @provider-decorated methods. \n'
' This feature will be removed in next Injector release.' %
module.__name__ if hasattr(module, '__name__') else module.__class__.__name__,
RuntimeWarning,
stacklevel=3,
)
if type(module) is type and issubclass(module, Module):
instance = self.injector.create_object(module)
instance(self)
else:
self.injector.call_with_injection(
callable=module,
self_=None,
args=(self,),
)
def create_binding(self, interface, to=None, scope=None):
provider = self.provider_for(interface, to)
scope = scope or getattr(to or interface, '__scope__', self.scope)
if isinstance(scope, ScopeDecorator):
scope = scope.scope
return Binding(interface, provider, scope)
def provider_for(self, interface, to=None):
if interface is Any:
raise TypeError('Injecting Any is not supported')
elif _is_specialization(interface, ProviderOf):
(target,) = interface.__args__
if to is not None:
raise Exception('ProviderOf cannot be bound to anything')
return InstanceProvider(ProviderOf(self.injector, target))
elif isinstance(to, Provider):
return to
elif isinstance(interface, Provider):
return interface
elif isinstance(to, (types.FunctionType, types.LambdaType,
types.MethodType, types.BuiltinFunctionType,
types.BuiltinMethodType)):
return CallableProvider(to)
elif issubclass(type(to), type):
return ClassProvider(to)
elif isinstance(interface, BoundKey):
def proxy(**kwargs):
return interface.interface(**kwargs)
proxy.__annotations__ = interface.kwargs.copy()
return CallableProvider(inject(proxy))
elif _is_specialization(interface, AssistedBuilder):
(target,) = interface.__args__
builder = interface(self.injector, target)
return InstanceProvider(builder)
elif (
isinstance(interface, (tuple, type)) and
interface is not Any and
isinstance(to, interface)
):
return InstanceProvider(to)
elif issubclass(type(interface), type) or isinstance(interface, (tuple, list)):
if to is not None:
return InstanceProvider(to)
return ClassProvider(interface)
elif hasattr(interface, '__call__'):
raise TypeError('Injecting partially applied functions is no longer supported.')
else:
raise UnknownProvider('couldn\'t determine provider for %r to %r' %
(interface, to))
def _get_binding(self, key):
binding = self._bindings.get(key)
if not binding and self.parent:
binding = self.parent._get_binding(key)
if not binding:
raise KeyError
return binding
def get_binding(self, cls, key):
try:
return self._get_binding(key)
except (KeyError, UnsatisfiedRequirement):
# The special interface is added here so that requesting a special
# interface with auto_bind disabled works
if self._auto_bind or self._is_special_interface(key.interface):
binding = self.create_binding(key.interface)
self._bindings[key] = binding
return binding
raise UnsatisfiedRequirement(cls, key)
def _is_special_interface(self, interface):
# "Special" interfaces are ones that you cannot bind yourself but
# you can request them (for example you cannot bind ProviderOf(SomeClass)
# to anything but you can inject ProviderOf(SomeClass) just fine
return any(
_is_specialization(interface, cls)
for cls in [AssistedBuilder, ProviderOf]
)
if TYPING353:
def _is_specialization(cls, generic_class):
# Starting with typing 3.5.3/Python 3.6 it is no longer necessarily true that
# issubclass(SomeGeneric[X], SomeGeneric) so we need some other way to
# determine whether a particular object is a generic class with type parameters
# provided. Fortunately there seems to be __origin__ attribute that's useful here.
if not hasattr(cls, '__origin__'):
return False
origin = cls.__origin__
if not inspect.isclass(generic_class):
generic_class = type(generic_class)
if not inspect.isclass(origin):
origin = type(origin)
# __origin__ is generic_class is a special case to handle Union as
# Union cannot be used in issubclass() check (it raises an exception
# by design).
return origin is generic_class or issubclass(origin, generic_class)
else:
# To maintain compatibility we fall back to an issubclass check.
def _is_specialization(cls, generic_class):
return isinstance(cls, type) and cls is not Any and issubclass(cls, generic_class)
class Scope:
"""A Scope looks up the Provider for a binding.
By default (ie. :class:`NoScope` ) this simply returns the default
:class:`Provider` .
"""
__metaclass__ = ABCMeta
def __init__(self, injector):
self.injector = injector
self.configure()
def configure(self):
"""Configure the scope."""
@abstractmethod
def get(self, key, provider):
"""Get a :class:`Provider` for a key.
:param key: The key to return a provider for.
:param provider: The default Provider associated with the key.
:returns: A Provider instance that can provide an instance of key.
"""
raise NotImplementedError
class ScopeDecorator:
def __init__(self, scope):
self.scope = scope
def __call__(self, cls):
cls.__scope__ = self.scope
binding = getattr(cls, '__binding__', None)
if binding:
new_binding = Binding(interface=binding.interface,
provider=binding.provider,
scope=self.scope)
setattr(cls, '__binding__', new_binding)
return cls
def __repr__(self):
return 'ScopeDecorator(%s)' % self.scope.__name__
class NoScope(Scope):
"""An unscoped provider."""
def __init__(self, injector=None):
super(NoScope, self).__init__(injector)
def get(self, unused_key, provider):
return provider
noscope = ScopeDecorator(NoScope)
class SingletonScope(Scope):
"""A :class:`Scope` that returns a per-Injector instance for a key.
:data:`singleton` can be used as a convenience class decorator.
>>> class A: pass
>>> injector = Injector()
>>> provider = ClassProvider(A)
>>> singleton = SingletonScope(injector)
>>> a = singleton.get(A, provider)
>>> b = singleton.get(A, provider)
>>> a is b
True
"""
def configure(self):
self._context = {}
@synchronized(lock)
def get(self, key, provider):
try:
return self._context[key]
except KeyError:
provider = InstanceProvider(provider.get(self.injector))
self._context[key] = provider
return provider
singleton = ScopeDecorator(SingletonScope)
class ThreadLocalScope(Scope):
"""A :class:`Scope` that returns a per-thread instance for a key."""
def configure(self):
self._locals = threading.local()
def get(self, key, provider):
try:
return getattr(self._locals, repr(key))
except AttributeError:
provider = InstanceProvider(provider.get(self.injector))
setattr(self._locals, repr(key), provider)
return provider
threadlocal = ScopeDecorator(ThreadLocalScope)
class Module:
"""Configures injector and providers."""
def __call__(self, binder):
"""Configure the binder."""
self.__injector__ = binder.injector
for unused_name, function in inspect.getmembers(self, inspect.ismethod):
binding = None
if hasattr(function, '__binding__'):
binding = function.__binding__
binder.bind(
binding.interface,
to=types.MethodType(binding.provider, self),
scope=binding.scope,
)
self.configure(binder)
def configure(self, binder):
"""Override to configure bindings."""
class Injector:
"""
:param modules: Optional - a configuration module or iterable of configuration modules.
Each module will be installed in current :class:`Binder` using :meth:`Binder.install`.
Consult :meth:`Binder.install` documentation for the details.
:param auto_bind: Whether to automatically bind missing types.
:param parent: Parent injector.
:param scope: Scope of created objects, if no scope provided.
Default scope is :class:`NoScope`.
For child injectors parent's scope is used if no scope
provided.
If you use Python 3 you can make Injector use constructor parameter annotations to
determine class dependencies. The following code::
class B:
@inject
def __init__(self, a: A):
self.a = a
can now be written as::
class B:
def __init__(self, a:A):
self.a = a
.. versionadded:: 0.7.5
``use_annotations`` parameter
.. versionchanged:: 0.13.0
``use_annotations`` parameter is removed
.. versionchanged:: 0.14.0
``scope`` parameter added
"""
def __init__(self, modules=None, auto_bind=True, parent=None, scope=None):
# Stack of keys currently being injected. Used to detect circular
# dependencies.
self._stack = ()
self.parent = parent
if not scope and parent:
scope = parent.scope
self.scope = scope
# Binder
self.binder = Binder(self, auto_bind=auto_bind,
parent=parent and parent.binder, scope=scope)
if not modules:
modules = []
elif not hasattr(modules, '__iter__'):
modules = [modules]
if not parent:
# Bind scopes
self.binder.bind_scope(NoScope)
self.binder.bind_scope(SingletonScope)
self.binder.bind_scope(ThreadLocalScope)
# Bind some useful types
self.binder.bind(Injector, to=self)
self.binder.bind(Binder, to=self.binder)
# Initialise modules
for module in modules:
self.binder.install(module)
@property
def _log_prefix(self):
return '>' * (len(self._stack) + 1) + ' '
def get(self, interface, scope=None):
"""Get an instance of the given interface.
.. note::
Although this method is part of :class:`Injector`'s public interface
it's meant to be used in limited set of circumstances.
For example, to create some kind of root object (application object)
of your application (note that only one `get` call is needed,
inside the `Application` class and any of its dependencies
:func:`inject` can and should be used):
.. code-block:: python
class Application:
@inject
def __init__(self, dep1: Dep1, dep2: Dep2):
self.dep1 = dep1
self.dep2 = dep2
def run(self):
self.dep1.something()
injector = Injector(configuration)
application = injector.get(Application)
application.run()
:param interface: Interface whose implementation we want.
:param scope: Class of the Scope in which to resolve.
:returns: An implementation of interface.
"""
key = BindingKey(interface)
binding = self.binder.get_binding(None, key)
scope = scope or binding.scope
if isinstance(scope, ScopeDecorator):
scope = scope.scope
# Fetch the corresponding Scope instance from the Binder.
scope_key = BindingKey(scope)
try:
scope_binding = self.binder.get_binding(None, scope_key)
scope_instance = scope_binding.provider.get(self)
except UnsatisfiedRequirement as e:
raise Error('%s; scopes must be explicitly bound '
'with Binder.bind_scope(scope_cls)' % e)
log.debug('%sInjector.get(%r, scope=%r) using %r',
self._log_prefix, interface, scope, binding.provider)
result = scope_instance.get(key, binding.provider).get(self)
log.debug('%s -> %r', self._log_prefix, result)
return result
def create_child_injector(self, *args, **kwargs):
return Injector(*args, parent=self, **kwargs)
def create_object(self, cls, additional_kwargs=None):
"""Create a new instance, satisfying any dependencies on cls."""
additional_kwargs = additional_kwargs or {}
log.debug('%sCreating %r object with %r', self._log_prefix, cls, additional_kwargs)
try:
instance = cls.__new__(cls)
except TypeError as e:
reraise(e, CallError(
cls,
getattr(cls.__new__, '__func__', cls.__new__),
(), {}, e, self._stack,),
maximum_frames=2)
try:
self.install_into(instance)
installed = True
except AttributeError:
installed = False
if hasattr(instance, '__slots__'):
raise Error('Can\'t create an instance of type %r due to presence of __slots__, '
'remove __slots__ to fix that' % (cls,))
# Else do nothing - some builtin types can not be modified.
try:
try:
init = cls.__init__
init(instance, **additional_kwargs)
except TypeError as e:
# The reason why getattr() fallback is used here is that
# __init__.__func__ apparently doesn't exist for Key-type objects
reraise(e, CallError(
instance,
getattr(instance.__init__, '__func__', instance.__init__),
(), additional_kwargs, e, self._stack,)
)
return instance
finally:
if installed:
self._uninstall_from(instance)
def install_into(self, instance):
"""Put injector reference in given object.
This method has, in general, two applications:
* Injector internal use (not documented here)
* Making it possible to inject into methods of an object that wasn't created
using Injector. Usually it's because you either don't control the instantiation
process, it'd generate unnecessary boilerplate or it's just easier this way.
For example, in application main script::
from injector import Injector
class Main:
def __init__(self):
def configure(binder):
binder.bind(str, to='Hello!')
injector = Injector(configure)
injector.install_into(self)
@inject
def run(self, s: str):
print(s)
if __name__ == '__main__':
main = Main()
main.run()
.. note:: You don't need to use this method if the object is created using `Injector`.
.. warning:: Using `install_into` to install :class:`Injector` reference into an object
created by different :class:`Injector` instance may very likely result in unexpected
behaviour of that object immediately or in the future.
"""
instance.__injector__ = self
def _uninstall_from(self, instance):
del instance.__injector__
def call_with_injection(self, callable, self_=None, args=(), kwargs={}):
"""Call a callable and provide it's dependencies if needed.
:param self_: Instance of a class callable belongs to if it's a method,
None otherwise.
:param args: Arguments to pass to callable.
:param kwargs: Keyword arguments to pass to callable.
:type callable: callable
:type args: tuple of objects
:type kwargs: dict of string -> object
:return: Value returned by callable.
"""
def _get_callable_bindings(callable):
if not hasattr(callable, '__bindings__'):
return {}
if callable.__bindings__ == 'deferred':
callable.__read_and_store_bindings__(_infer_injected_bindings(callable))
del callable.__read_and_store_bindings__
return callable.__bindings__
bindings = _get_callable_bindings(callable)
noninjectables = getattr(callable, '__noninjectables__', set())
needed = dict(
(k, v) for (k, v) in bindings.items()
if k not in kwargs and k not in noninjectables
)
dependencies = self.args_to_inject(
function=callable,
bindings=needed,
owner_key=self_.__class__ if self_ is not None else callable.__module__,
)
dependencies.update(kwargs)
try:
return callable(
*((self_,) if self_ is not None else ()) + tuple(args),
**dependencies)
except TypeError as e:
reraise(e, CallError(self_, callable, args, dependencies, e, self._stack))
@private
@synchronized(lock)
def args_to_inject(self, function, bindings, owner_key):
"""Inject arguments into a function.
:param function: The function.
:param bindings: Map of argument name to binding key to inject.
:param owner_key: A key uniquely identifying the *scope* of this function.
For a method this will be the owning class.
:returns: Dictionary of resolved arguments.
"""
dependencies = {}
key = (owner_key, function, tuple(sorted(bindings.items())))
def repr_key(k):
owner_key, function, bindings = k
return '%s.%s(injecting %s)' % (tuple(map(_describe, k[:2])) + (dict(k[2]),))
log.debug('%sProviding %r for %r', self._log_prefix, bindings, function)
if key in self._stack:
raise CircularDependency(
'circular dependency detected: %s -> %s' %
(' -> '.join(map(repr_key, self._stack)), repr_key(key))
)
self._stack += (key,)
try:
for arg, key in bindings.items():
try:
instance = self.get(key.interface)
except UnsatisfiedRequirement as e:
if not e.args[0]:
e = UnsatisfiedRequirement(owner_key, e.args[1])
raise e
dependencies[arg] = instance
finally:
self._stack = tuple(self._stack[:-1])
return dependencies
class _BindingNotYetAvailable(Exception):
pass
def _infer_injected_bindings(callable):
spec = inspect.getfullargspec(callable)
try:
bindings = get_type_hints(callable)
except NameError as e:
raise _BindingNotYetAvailable(e)
# We don't care about the return value annotation as it doesn't matter
# injection-wise.
bindings.pop('return', None)
# variadic arguments aren't supported at the moment (this may change
# in the future if someone has a good idea how to utilize them)
bindings.pop(spec.varargs, None)
bindings.pop(spec.varkw, None)
for k, v in list(bindings.items()):
if _is_specialization(v, Union):
# We don't treat Optional parameters in any special way at the moment.
if TYPING353:
union_members = v.__args__
else:
union_members = v.__union_params__
new_members = tuple(set(union_members) - {type(None)})
new_union = Union[new_members]
bindings[k] = new_union
return bindings
def with_injector(*injector_args, **injector_kwargs):
"""Decorator for a method. Installs Injector object which the method
belongs to before the decorated method is executed.
Parameters are the same as for :class:`Injector` constructor.
"""
def wrapper(f):
@functools.wraps(f)
def setup(self_, *args, **kwargs):
injector = Injector(*injector_args, **injector_kwargs)
injector.install_into(self_)
return f(self_, *args, **kwargs)
return setup
return wrapper
def provider(function):
"""Decorator for :class:`Module` methods, registering a provider of a type.
>>> class MyModule(Module):
... @provider
... def provide_name(self) -> str:
... return 'Bob'
@provider-decoration implies @inject so you can omit it and things will
work just the same:
>>> class MyModule2(Module):
... def configure(self, binder):
... binder.bind(int, to=654)
...
... @provider
... def provide_str(self, i: int) -> str:
... return str(i)
...
>>> injector = Injector(MyModule2)
>>> injector.get(str)
'654'
.. note:: This function works only on Python 3
"""
scope_ = getattr(function, '__scope__', None)
annotations = inspect.getfullargspec(function).annotations
return_type = annotations['return']
function.__binding__ = Binding(return_type, inject(function), scope_)