Skip to main content

A lightweight dependency injection module for Python.

Project description

LIGHT DI

Dependency Injection Module for Python

LightDI is a lightweight, framework-agnostic dependency injection module for Python.

Features

  • Automatic dependency resolution
  • Support for qualifiers
  • Abstract class inference

Usage

Example 1: Basic Usage

from abc import ABC, abstractmethod

from lightdi import implementation, inject


class PaymentProcessor(ABC):
    @abstractmethod
    def process_payment(self, amount: int) -> str:
        pass

@implementation(qualifier="credit_card")
class CreditCardProcessor(PaymentProcessor):
    def process_payment(self, amount: int) -> str:
        return f"Processed {amount} via Credit Card."

@implementation(qualifier="paypal", primary=True)
class PayPalProcessor(PaymentProcessor):
    def process_payment(self, amount: int) -> str:
        return f"Processed {amount} via PayPal."

class LogTransactionRepository(ABC):
    @abstractmethod
    def save(self, amount: int) -> None:
        pass

@implementation(qualifier="in_memory")
class InMemoryLogTransactionRepository(LogTransactionRepository):
    def save(self, amount: int):
        self._write_to_file(f"Transaction saved: {amount}")

    def _write_to_file(self, message) -> None:
        with open("transactions.txt", "a") as file:
            file.write(message + "\n")

@inject
class CheckoutService:
    def __init__(self, payment_processor: PaymentProcessor):
        self.payment_processor = payment_processor

    def checkout(self, amount) -> str:
        return self.payment_processor.process_payment(amount)

@inject
class PaymentController:
    def __init__(self, checkout_service: CheckoutService, log_transaction_repository: LogTransactionRepository):
        self.checkout_service = checkout_service
        self.log_transaction_repository = log_transaction_repository

    def process_checkout(self, amount) -> str:
        self.log_transaction_repository.save(amount)
        return self.checkout_service.checkout(amount)

if __name__ == "__main__":
    controller = PaymentController()
    print(controller.process_checkout(100))

Example 2: Wire repositories to variables

from abc import ABC, abstractmethod

from lightdi import implementation, wire


class LogRepository(ABC):
    @abstractmethod
    def log(self, message):
        pass

@implementation(qualifier="console")
class ConsoleLogRepository(LogRepository):
    def log(self, message):
        print(message)

@implementation(qualifier="timestamp", primary=True)
class TimeStampLogRepository(LogRepository):
    def log(self, message):
        print(f"{__import__('datetime').datetime.now()}: {message}")

if __name__ == "__main__":
    logger = wire(LogRepository)
    logger.log("message to be logged")

    console_logger = wire(LogRepository, qualifier="console")
    console_logger.log("message to be logged")

Examples

  • Example 1: Basic Usage | link
  • Example 2: Wire repositories to variable | link
  • Example 3: Multi-file usage | link

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

light-dependency-injection-0.1.2.tar.gz (8.0 kB view details)

Uploaded Source

Built Distribution

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

light_dependency_injection-0.1.2-py3-none-any.whl (8.9 kB view details)

Uploaded Python 3

File details

Details for the file light-dependency-injection-0.1.2.tar.gz.

File metadata

File hashes

Hashes for light-dependency-injection-0.1.2.tar.gz
Algorithm Hash digest
SHA256 8926bcac09cc81f03f4bb4747928feb5073a98c75b424d0e3b14e741bcbfc8e8
MD5 ade87d84263d64bc06f02a46ddcd34a3
BLAKE2b-256 03b6ce8814bec1fa967b20356aa0b282fe8d24dfa49249816b4439300fe93882

See more details on using hashes here.

Provenance

The following attestation bundles were made for light-dependency-injection-0.1.2.tar.gz:

Publisher: publish.yml on PabloSanchi/light-di

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file light_dependency_injection-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for light_dependency_injection-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ff4f5559c0f4d964af88c48824a895a581e136c171c4c2db88fb8948bffa8410
MD5 9182bfe1c6ce620a95ebf4b3c1c42cbe
BLAKE2b-256 55452d4c664274a34edf43c2fa38fcba01d5b24513c5bb193e10c29f54ea52e2

See more details on using hashes here.

Provenance

The following attestation bundles were made for light_dependency_injection-0.1.2-py3-none-any.whl:

Publisher: publish.yml on PabloSanchi/light-di

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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