Module Dependency Injection

Consider a module, for example. some_modulethat different modules use in the same interpreter process. This module will have one context. For methods to some_modulework, it must receive an injection of the dependencies of the class instance.

What would be a python and elegant way to embed dependencies on a module?

+5
source share
3 answers

Use global module.

import some_module
some_module.classinstance = MyClass()

some_modulemay have code to install the default instance if it is not received, or just install classinstanceon Noneand make sure it is installed when calling the methods.

+2
source

IMHo , Dependency Injection , Java, python , , injection

class DefaultLogger(object):
   def log(self, line):
      print line

_features = {
   'logger': DefaultLogger
   }

def set_feature(name, feature):
   _features[name] = feature

def get_feature(name):
   return _features[name]()

class Whatever(object):

   def dosomething(self):
      feature = get_feature('logger')

      for i in range(5):
         feature.log("task %s"%i)

if __name__ == "__main__":
   class MyLogger(object):
      def log(sef, line):
         print "Cool",line

   set_feature('logger', MyLogger)

   Whatever().dosomething()

:

Cool task 0
Cool task 1
Cool task 2
Cool task 3
Cool task 4

, - , .

+1

You can use dependenciespackage to achieve your goal.

0
source

All Articles