Use Case

In simple words IoC is giving your program a part a flow of control using a framework, for python it's here these helps to configure the application in multiple ways below are few examples of this

Decorators

Decorators are the way to invoke IoC with your application in python, common decorators we can use are @Bean, @Component and @Autowired these decorators can be used to configure and control most of the part of your code.

@Bean

@Bean is used in a method adding Bean decorator on a method automatically creates a lifecycle and automatic initialization of the bean in the App Context Below example demonstrate a Bean method that returns a Class Object of type TestBean Class.

@Bean()  # Bean Decorator
def getTestBean() -> TestBean:  # Return Type is required to be specified
    return TestBean("Test 123") # Bean Object

@Component

@Component is used to automatically initialize a class object into App Context, this decorator is only used on Class types. Below example shows a normal class as a component class in python

@Component  # Component Decorator
class TestComponentAnnotation:
    def __init__(self):
        print("Initialized")

Autowired

@Autowired is used to inject loaded beans and components into user defined object this requires a setter method to inject to object

@Autowired()  # Autowired Decorator
def setConfig(bean: TestBean, component: TestComponentAnnotation): # Parameter Type is required 
    global testBean, testComponent
    testBean = bean
    testComponent = component

How to Initialize IoC

AppInitializer class is responsible to handle bindings and for Dependency Injection it controls the bean initialization and bean context until all the beans/components are injected. Below two lines are the easiest lines to invoke dependency inject in your application

app = AppInitializer()  # Create AppInitializer object
app.run()               # Invoke Dependency Injection and Binding Configs