Package: python-simple-di
python-simple-diis a simple dependency injection container implementation. With its help you can create instances and its dependencies on runtime.ContentsChanges1.7.01.6.01.5.2InstallConfigurationArgument ResolversReferenceResolverRelationResolverModuleResoverFactoryResolverAttributeResolverEventsUsageResolve LazyChild ContainerDecoratorsRegister by decoratorInject with decoratorInject many with decoratorChanges1.7.0Loosely coupledinjectandinject_manydecorator. (WARNING:inject_manyusesresolve_manythat makes use of the unsorteditemsdict-method. So there is no garanty that the first instance is the first registered instance.)resolvealso accepts a type as parameternameand will return the first instance subclassing that type (first result ofresolve_many). (WARNING:resolve_manythat makes use of the unsorteditemsdict-method. So there is no garanty that the first instance is the first registered instance.)1.6.0resolve many: the new methodsresolve_manyandresolve_many_lazygives you the possibility to resolve multiple objects depending on their class.alias names: you can provide a list of alias names within the object configuration.constructor/factory (kw)argument overridies: resolve methods noch accepts args and kwargs that will can be used instead of args configurations.register decorator:registercan be used as decorator now.use as contextmanager: the container can be used as context manager to temporarily override settings inwithblock.mixin support: new optionsmixinscan container a list or a type of types that will be used to create the new type.1.5.2copy settings in DIContainer.__init__.InstallYou can install it via pip:pip install python-simple-dior via easy_install:easy_install -U python-simple-diConfigurationTo configure thedi.DIContaineryou need to pass a dict with the needed configuration in it. Alternativly you can use an instance ofdi.DIConfigwhich is used internal anyway.
Define the objects name askeyto access it at runtime. Thevalueneeds to be the configuration to create the instance.type(required): This option defines the type with its complete python dotted path or the python type instance. You can add a path that will dynamicly become added to thesys.pathif the instance is requested.Examples:'type':'path.to.my.Type''type':path.to.my.Type# or'type':'/add/to/sys/path:add.to.sys.path.Type'args(optional): The args can either be alistof values to pass as Arguments or adictto pass as Keyword Arguments. To mix both, you can define a dictionary with an empty string or None as key and a list as value.Examples:'args':['first',3,'third']# or'args':{'one':'1','two':'two'}# or'args':{'':[1,'two'],'three':3}lazy(optional): This option defines whether the instance will be created on runtime or on container initialization.Example:'lazy':False# default: Truesingleton(optional, default: True): If this option is set toTrue, the created instance will be saved inside the container. Next time the same instance will be returned. If this value is set toFalsea new instance will be created every time.properties(optional): This option is similar to theargsoption. After an instance was created a buildup is called. This buildup fills the given properties with the given values in this dictionary.Examples:{'type':'some.Person','propeties':{'first_name':'John','last_name':'Doe'}}assert_type(optional): Checks weather the created type has the given base_type.'type':'path.to.implementet.Type','assert_type':'path.to.parent.Type'factory_method(optional): This options can be used to create an instance by a classmethod which creates the wanted instance. For example this can be used to create a class based views in django at runtime.Example:'type':'myapp.views.ClassBasedView','factory_method':'as_view'mixins(optional): This options allows you to mix the given types into the configured type to create complete new type.Argument ResolversWith the help of the resolver the magic comes into play. Thanks to this small classes it is possible to trigger the dependencies of a type at runtime.The following resolver be brought by the default package. Individual resolver can be implemented by extending the base classdi.Resolver.ReferenceResolverThe ReferenceResolver offers the possibility to an attribute within the python path to refer. This must be the path and the object, as a Python dotted path.Example:{'args':{'output_stream':ReferenceResolver('sys.stdout')}}dialso provides some shortcuts for this name:di.ref('sys.stdout')as shortcut for type.di.reference('sys.stdout')as shortcut for the type.'ref:sys.stdout'as prefix of the configured type to lazy use the resolver.RelationResolverThe RelationResolver allows the resolution of an object of this container at runtime.Example:{'object_a':{'type':'some.ClassName'},'object_b':{'type':'some.other.ClassName','args':[RelationResolver('object_a')]},}dialso provides some shortcuts for this name:di.rel('object_a')as shortcut for type.di.relation('object_a')as shortcut for the type.'rel:object_a'as prefix of the configured type to lazy use the resolver.ModuleResoverSometimes it may be necessary to pass an entire module as a parameter. For this purpose the ModuleResolver available.Example:{'type':'some.ClassName','args':{'serializer':ModuleResolver('json')}}Di also provides some shortcuts for this name.di.mod('json')as shortcut for type.di.module('json')as shortcut for the type.'mod:json'as prefix of the configured type to lazy use the resolver.FactoryResolverWith the help of FactoryResolver the return value of a function as an argument can be passed to the specified type.Example.{'type':'some.ClassName','args':[FactoryResolver('path.to.the.factory_method')]}Di also provides some shortcuts for this name.di.fac('path.to.the.factory_method')as shortcut for type.di.factory('path.to.the.factory_method')as shortcut for the type.'factory:path.to.the.factory_method'as prefix of the configured type to lazy use the resolver.AttributeResolverWith the Resolver an attribute of an instance can be passed as an argument. This can be very useful if you are using the django web framework and want to pass a settings value as an argument fo an instance.Example:{'type':'some.ClassName':'args':{'debug':AttributeResolver('django.conf.settings.DEBUG')}}Di also provides some shortcuts for this name.di.attr('django.conf.settings.DEBUG')as shortcut for type.di.attribute('django.conf.settings.DEBUG')as shortcut for the type.'attr:django.conf.settings.DEBUG'as prefix of the configured type to lazy use the resolver.EventsYou can pass an EventDispatcher into the DiContainer. This Dispatcher will be called if anything interesting happens inside the Container. BaseType isdi.DIEventDispatcher.UsageSimply create a dictionary with your type configuration and pass it as settings argument to theDIContainer. The Dictionarys key is the type key to resolve the instance.# create the containercontainer=DIContainer(config)# resolve the instanceinstance=container.resolve('instance_key')# resolve the instance type onlytype_of_instance_key=container.resolve_type('instance_key')Resolve LazySometimes it may be necessary to create an instance at its first useage. So there are the following two messages, that returns adi.Proxyinstance at first.To use this Feature you need to provide aproxy_type_nameand install the specific package for this. I recommendlazy-object-proxywith its typeProxy. Which is the default value for this argument. It is not shipped with this package because of the many different other implementations and thier different licence.
If you use this in combination with django you can usedjango.utils.functional.SimpleLazyObject.But at this moment the ``resolve_type_lazy`` is not working properly with ``SimpleLazyObject``.# create the containercontainer=DIContainer(config,proxy_type_name='lazy_object_proxy.Proxy')# lazy resolves the instanceinstance=container.resolve_lazy('instance_key')# lazy resolves the instance type onlytype_of_instance_key=container.resolve_type_lazy('instance_key')Child ContainerIf you need the same container but override some settings you can create a child container and pass the deviant settings into it.This is the unittest that explains this function at its best.container=DIContainer({'one':{'type':'mock.Mock','properties':{'source':'parent'}},'two':{'type':'mock.Mock','properties':{'source':'parent'}}})self.assertEqual(container.one.source,'parent')self.assertEqual(container.two.source,'parent')child_container=container.create_child_container({'two':{'type':'mock.Mock','properties':{'source':'child'}}})self.assertEqual(child_container.one.source,'parent')self.assertEqual(child_container.two.source,'child')self.assertEqual(container.one.source,'parent')self.assertEqual(container.two.source,'parent')DecoratorsSome method of thedi.DIContainercan be used as decorator zu register or inject instances within your code.Register by decoratorThe methodregistercan be used as decorator for classes or factory methods. With this
you do not need to provide the instances configuration at container creation.Passing the settings is optional.@container.register("my_service",dict(args={'init_arg':'test'}))classMyService(object):def__init__(self,init_arg):self.init_arg=init_argdefget_data(self,args):passInject with decoratorThe methodinjectgives you the possibility to inject instances into a
method if a keyword argument was not provided. that makes the loosely coupeling
and testing very easy:@container.inject(service='some_service')defsome_method(value,service):service.do_work(value)some_method("hello world")some_method("hello world",ExplicitService())Inject many with decoratorThe methodinject_manygives you the possibility to inject multiple instances depending on
their type.@container.inject_many(hooks=SomeHookClass)defmethod(data,hook_instances):forhookinhook_instance:hook.hook(data)# ...