Reputation: 107092
Consider a module, e.g. some_module
, that various modules use in the same interpreter process. This module would have a single context. In order for some_module
methods to work, it must receive a dependency injection of a class instance.
What would be a pythonic and elegant way to inject the dependency to the module?
Upvotes: 5
Views: 3940
Reputation: 184191
Use a module global.
import some_module
some_module.classinstance = MyClass()
some_module
can have code to set up a default instance if one is not received, or just set classinstance
to None
and check to make sure it's set when the methods are invoked.
Upvotes: 3
Reputation: 88757
IMHo opinion full fledged Dependency Injection
with all jargon is better suited to statically typed languages like Java, in python you can accomplish that very easily e.g here is a bare bone 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()
output:
Cool task 0
Cool task 1
Cool task 2
Cool task 3
Cool task 4
If you think something is missing we can add that easily, its python.
Upvotes: 2