To answer the question that you explicitly asked: no, there is no built-in way in Python to automatically get the MyClass object from a parameter named my_class.
However, neither “binding your object creation to the framework” nor the example code you gave look awful Pythonic, and this question is generally quite confusing because DI in dynamic languages is not a big problem.
For general thoughts on DI in Python, I would say this presentation gives a pretty good overview of the various approaches. For your specific question, I will give two options based on what you can try to do.
If you are trying to add DI to your own classes, I would use parameters with default values in the constructor, as this presentation shows. For instance:
import time class Example(object): def __init__(self, sleep_func=time.sleep): self.sleep_func = sleep_func def foo(self): self.sleep_func(10) print('Done!')
And then you could just go through a dummy sleep function for testing or something else.
If you are trying to manipulate library classes through DI, (not what I really can imagine for use, but it looks like you're asking for), then I'm probably just a monkey to fix these classes to change all the necessary changes. For instance:
import test_module def dummy_sleep(*args, **kwargs): pass test_module.time.sleep = dummy_sleep e = test_module.Example() e.foo()
source share