Skip to main content

Default template for PDM package

Project description

NestDI

NestDI is a lightweight and powerful Dependency Injection (DI) container for Python, heavily inspired by the architecture of NestJS. It allows you to organize your code into modules, making your applications easier to maintain, test, and scale.

🚀 Features

  • Decorator-based: Use @Module(), @Injectable(), and @Controller() to define your structure.
  • Scope Management: Support for SINGLETON, TRANSIENT, and REQUEST scopes.
  • Automatic Injection: Automatic dependency resolution through type hints in constructors.
  • Module System: Encapsulation and reuse of logic through imports and exports.
  • Flexible Providers: Support for classes, constant values, and factories.
  • Circular Dependency Detection: Throws clear exceptions when cycles are detected.
  • Strongly Typed: Full support for MyPy and Pyright with .typed.

📦 Installation

Since this project uses PDM, you can install it via:

pdm add nestdi

Or via pip (if published):

pip install nestdi

🛠️ Usage Guide

1. Defining Providers

Mark your classes with @Injectable() so NestDI can instantiate and inject them.

from nestdi import Injectable

@Injectable()
class LoggingService:
    def log(self, message: str):
        print(f"[LOG]: {message}")

@Injectable()
class UserService:
    def __init__(self, logger: LoggingService):
        self.logger = logger

    def get_user(self):
        self.logger.log("Fetching user...")
        return {"id": 1, "name": "John Doe"}

2. Creating Modules

Modules organize related components.

from nestdi import Module

@Module(
    providers=[LoggingService, UserService],
    exports=[UserService] # Export so other modules can use it
)
class UserModule:
    pass

3. Controllers and Root Container

Controllers are entry points for your logic.

from nestdi import Controller, Module

@Controller()
class UserController:
    def __init__(self, user_service: UserService):
        self.user_service = user_service

    def detail(self):
        return self.user_service.get_user()

@Module(
    imports=[UserModule],
    controllers=[UserController]
)
class AppModule:
    pass

4. Initialization and Usage

from nestdi import ModuleClass

# The @Module decorator returns a ModuleClass instance
app: ModuleClass = AppModule

# Getting the resolved controller
user_controller = app.get(UserController)
print(user_controller.detail())

🌍 Global Modules

If you want a module's providers to be available throughout the application without needing to import it in every module, use the @Global() decorator.

from nestdi import Module, Global, Injectable

@Injectable()
class GlobalService:
    pass

@Global()
@Module(
    providers=[GlobalService],
    exports=[GlobalService]
)
class CommonModule:
    pass

📐 Provider Scopes

You can define how instances are created:

  • ProviderScope.SINGLETON (Default): A single instance is created and shared across the entire application.
  • ProviderScope.TRANSIENT: A new instance is created every time the provider is requested.
  • ProviderScope.REQUEST: A new instance is created for each "request" (useful in web contexts).
from nestdi import Injectable, ProviderScope

@Injectable(scope=ProviderScope.TRANSIENT)
class GeneratorService:
    pass

🏭 Factory Providers

from nestdi import Provider, Module

def connection_factory(config_service: ConfigService):
    return DatabaseConnection(config_service.db_url)

@Module(
    providers=[
        Provider(
            provide="DATABASE_CONNECTION",
            use_factory=connection_factory,
            inject=[ConfigService]
        )
    ]
)
class DatabaseModule:
    pass

📝 License

This project is licensed under the MIT License.

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

nestdi-0.1.0.tar.gz (4.6 kB view details)

Uploaded Source

Built Distribution

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

nestdi-0.1.0-py3-none-any.whl (5.2 kB view details)

Uploaded Python 3

File details

Details for the file nestdi-0.1.0.tar.gz.

File metadata

  • Download URL: nestdi-0.1.0.tar.gz
  • Upload date:
  • Size: 4.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.25.5 CPython/3.12.2 Linux/6.6.87.2-microsoft-standard-WSL2

File hashes

Hashes for nestdi-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1fb88dda28b8d896f0706c52308b1c952df30c5f26b516f754ac84e4ce37f33d
MD5 384a2a22f84fa96341bdb809e336123a
BLAKE2b-256 d28811d103f1b38a9e22b2e7a9356015b7ee0b9753307967055975c2f3ef6447

See more details on using hashes here.

File details

Details for the file nestdi-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: nestdi-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 5.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.25.5 CPython/3.12.2 Linux/6.6.87.2-microsoft-standard-WSL2

File hashes

Hashes for nestdi-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b7c86a9e7bccbd691982d27657532988624d76427f032133998b2b6bcc9de725
MD5 83aae70fd3f1a05399d3c361456cef31
BLAKE2b-256 77615960262fffe696156301b2d13123a6e05fb7fc94e3aa728877192d556189

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