Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

python_ioc — IoC (Inversion of Control)

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.

Install

pip install git+https://github.com/HassaanSaleem/python_ioc.git

Requires Python 3.11 or later.

Usage

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.

Development

pip install -e ".[dev]"
pytest

About

YAML-driven IoC container for Python: services and parameters live in config, dependencies wire by @reference

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages