IoC module provides a framework to dynamically inject dependencies in applications. This intends to reduce coupling between application and infrastructure, and application and third-party libraries.
pip install git+https://github.com/HassaanSaleem/python_ioc.gitRequires Python 3.11 or later.
The module loads dependencies listed in a yaml file with different configuration options. The yaml file should have two top level attributes:
- parameters: For variables. A value written as
${ENV_VAR}is substituted with the value of the environment variable at build time. - services: For instances.
Each service can be configured using the following options:
- class: Path to the class of dependency.
- scope: Can be one of these ['singleton', 'transient']. Defaults to 'singleton'.
- construct: Boolean value that defines whether an instance should be constructed or just the class should be returned. Defaults to true.
- kwargs: Keyword arguments to inject in the dependency. To inject another service or parameter prefix its name with '@'. References are also resolved inside lists, and inside dicts for singleton services.
Example yaml file:
parameters:
bullets: 10
services:
gun:
class: examples.dependencies.Gun
scope: transient
kwargs:
bullets: '@bullets'Load dependencies by building container.
container = python_ioc.build(['./examples/config.yml'])
gun = container.get('gun')
gun.fire()build accepts a list of yaml files, so configuration can be split across multiple files. container.get returns None for names that were never registered.
pip install -e ".[dev]"
pytest