Skip to main content

A dependency management tool for Python projects.

Project description

module-dependency

This repository contains experiments and examples for managing dependencies using dependency injection with class decorators in Python projects. The structures and patterns demonstrated here are flexible and can be adapted to suit various project needs.

Overview

The goal of this project is to showcase different approaches to dependency management, focusing on modularity, flexibility, and ease of use. While the provided examples are specific, the underlying concepts can be applied to a wide range of scenarios.

Core Components

The project is built around three components that implement different aspects of dependency management:

1. Module

  • Acts as a container for organizing and grouping related dependencies
  • Facilitates modular design and hierarchical structuring of application components
from dependency.core import Module, module

@module()
class SomeModule(Module):
    """This is a module class. Use this to group related components.
    """
    pass

2. Component

  • Defines abstract interfaces or contracts for dependencies
  • Promotes loose coupling and enables easier testing and maintenance
from abc import ABC, abstractmethod
from dependency.core import Component, component
from ...plugin.........module import SomeModule

class SomeService(ABC):
    """This is the interface for a new component.
    """
    @abstractmethod
    def method(self, ...) -> ...:
        pass

@component(
    module=SomeModule,     # Declares the module or plugin this component belongs to
    interface=SomeService, # Declares the interface used by the component
)
class SomeServiceComponent(Component):
    """This is the component class. A instance will be injected here.
       Components are only started when provided or bootstrapped.
    """
    pass

3. Instance

  • Delivers concrete implementations of Components
  • Manages the lifecycle and injection of dependency objects
from dependency.core import instance, providers
from ...plugin.........component import SomeService, SomeServiceComponent
from ...plugin...other_component import OtherService, OtherServiceComponent

@instance(
    component=SomeServiceComponent, # Declares the component to be provided
    imports=[OtherService, ...],    # List of dependencies (components) that are needed
    provider=providers.Singleton,   # Provider type (Singleton, Factory)
    bootstrap=False,                # Whether to bootstrap on application start
)
class ImplementedSomeService(SomeService):
    """This is a instance class. Here the component is implemented.
       Instances are injected into the respective components when provided.
    """
    def __init__(self) -> None:
        """Init method will be called when the instance is stared.
           This will happen once for singleton and every time for factories.
        """
        # Once declared, i can use the dependencies for the class.
        self.dependency: OtherService = OtherServiceComponent.provide()
    
    def method(self, ...) -> ...:
        """Methods declared in the interface must be implemented.
        """
        do_something()

These components work together to create a powerful and flexible dependency injection system, allowing for more maintainable and testable Python applications.

Extra Components

The project has additional components that enhance its functionality and organization. These components include:

1. Entrypoint

  • Represents a entry point for the application
  • Responsible for initializing and starting the application
from dependency.core import Entrypoint, Container
from ...plugin...... import SomePlugin

class SomeApplication(Entrypoint):
    """This is an application entry point.
       Plugins included here will be loaded and initialized.
    """
    def __init__(self) -> None:
        # Import the instances that will be used on the application
        # This will generate the internal provider structure
        import ...plugin.........component

        # This is the main container, it will hold all the providers
        container = Container.from_dict(config={...}, required=True)
        super().__init__(
            container,
            plugins=[
                SomePlugin,
                ...
            ])

    def main_loop(self) -> None:
        """Main application loop.
        """
        pass

2. Plugin

  • Represents a special module that can be included in the application
  • Provides additional functionality or features to the application
from pydantic import BaseModel
from dependency.core import Plugin, PluginMeta, module

class SomePluginConfig(BaseModel):
    """Include configuration options for the plugin.
    """
    pass

@module()
class SomePlugin(Plugin):
    """This is a plugin class. Plugins can be included in the application.
       Plugins are modules that provide additional functionality.
    """
    meta = PluginMeta(name="SomePlugin", version="0.0.1")

    @property
    def config(self) -> SomePluginConfig:
        """Plugins can have their own configuration options.
           Instantiates the model using the container config.
        """
        return SomePluginConfig(**self.container.config())

3. Dependent

  • Represents a class produced by a Provider that requires dependencies
  • Allows to provide standalone classes without the need to define new providers
from dependency.core import Dependent, dependent

@dependent(
    imports=[SomeComponent, ...], # List of dependencies (components) that are needed
)
class SomeDependent(Interface, Dependent):
    """This is the dependent class. This class will check for its dependencies.
       Dependents must be declared in some provider and can be instantiated as normal classes.
    """
    def method(self, ...) -> ...:
        pass

Usage Examples

This repository includes a practical example demonstrating how to use the framework. You can find this example in the example directory. It showcases the implementation of the core components and how they interact to manage dependencies effectively in a sample application.

Future Work

This project is a work in progress, and there are several improvements and enhancements planned for the future. Some of the areas that will be explored include:

  • Improve component registration and resolution mechanisms
  • Improve ways to handle module definitions and configurations
  • Explore more advanced dependency injection patterns and use cases
  • Enhance validation and error handling mechanisms of the framework

Aknowledgements

This project depends on dependency-injector. This library provides a robust and flexible framework for managing dependencies in Python projects.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

module_dependency-0.4.0.tar.gz (30.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

module_dependency-0.4.0-py3-none-any.whl (30.0 kB view details)

Uploaded Python 3

File details

Details for the file module_dependency-0.4.0.tar.gz.

File metadata

  • Download URL: module_dependency-0.4.0.tar.gz
  • Upload date:
  • Size: 30.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.28.1

File hashes

Hashes for module_dependency-0.4.0.tar.gz
Algorithm Hash digest
SHA256 fa3d244df6c4c23b3675235fab2669d9f88670da688929ea25a1936fdb80f596
MD5 4d0efb2b48ddc73678b2de0b8583d9f3
BLAKE2b-256 eed5042417aa78cd062117643c919c1a686ad8b498c861e557ca4e1a9c57cbca

See more details on using hashes here.

File details

Details for the file module_dependency-0.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for module_dependency-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 008f4ac717fe53804e1612409b5f8867d90288ceed97142a565f880eb80604b8
MD5 71eaae9172788751664d32b76636437b
BLAKE2b-256 681572e50fa70c571cc4c6a85c6a172f0de9c6124578778e9114ec9e1c38d86b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page