Skip to main content

A lightweight dependency injection library for Python

Project description

Simple Inject

中文 README

Simple Inject is a lightweight Python dependency injection library. It provides an easy-to-use interface for managing dependencies across different namespaces and scopes.

Features

  • Simple and intuitive dependency injection API
  • Supports multiple namespaces to isolate dependencies
  • Implements scoped dependencies using context managers or decorators
  • Supports nested scopes for fine-grained control
  • Supports automatic dependency injection through parameters
  • Easy integration with existing projects
  • Minimal overhead and dependencies

Installation

You can install Simple Inject using pip:

pip install py-simple-inject

Quick Start

Basic Usage

Here is a simple example demonstrating basic dependency injection and scope management:

from simple_inject import provide, inject, create_scope

# Provide a dependency
provide('config', {'debug': True})

# Inject a dependency
config = inject('config')
print(config['debug'])  # Output: True

Using Namespaces

from simple_inject import provide, inject, create_scope

provide('key', 'value1', namespace='ns1')
provide('key', 'value2', namespace='ns2')

print(inject('key', namespace='ns1'))  # Output: value1
print(inject('key', namespace='ns2'))  # Output: value2

Using Scopes

provide('config', {'debug': True})

# Use scopes to manage dependencies
with create_scope():
    provide('config', {'debug': False})
    config = inject('config')
    print(config['debug'])  # Output: False

# Outside the scope, the original value is preserved
config = inject('config')
print(config['debug'])  # Output: True

Scopes can also be used with the scoped decorator:

@scoped()
def scoped_function():
    provide('key', 'scoped_value')
    return inject('key')

provide('key', 'outer_value')
print(inject('key'))  # Output: outer_value
print(scoped_function())  # Output: scoped_value
print(inject('key'))  # Output: outer_value

Nested Scopes

Scoped scopes can be nested, and dependencies in inner scopes will override those in outer scopes.

provide('key', 'outer')

with create_scope():
    provide('key', 'inner')
    print(inject('key'))  # Output: inner

    with create_scope():
        provide('key', 'innermost')
        print(inject('key'))  # Output: innermost

    print(inject('key'))  # Output: inner

print(inject('key'))  # Output: outer

Automatic Injection via Function Parameters

Simple Inject also supports automatic injection via function parameters. The following example demonstrates how to use this advanced feature:

from simple_inject import provide, inject, create_scope, auto_inject, Inject

class Engine:
    def start(self):
        print("Engine started")

# Provide a dependency
provide('engine', Engine())

# Manually inject a dependency
engine = inject('engine')
engine.start()  # Output: Engine started

# Use automatic injection
@auto_inject()
def drive(car: str, engine: Engine = Inject('engine')):
    print(f"Driving {car}")
    engine.start()

drive("Tesla")  # Output: Driving Tesla and Engine started

# Use scopes to manage dependencies
with create_scope():
    provide('engine', Engine())  # Provide a new Engine instance
    drive("BMW")  # Output: Driving BMW and Engine started

# Outside the scope, the original value is preserved
drive("Toyota")  # Output: Driving Toyota and Engine started

API Reference

provide(key: str, value: Any, namespace: str = 'default')

Provides a dependency in the current context.

inject(key: str, namespace: str = 'default') -> Any

Injects a dependency from the current context.

create_scope()

Creates a new dependency scope. Used with the with statement.

scoped()

Decorator to create a new dependency scope for a function.

auto_inject()

Decorator to automatically inject parameters marked with Inject.

Inject(key: str, namespace: str = 'default')

Class to mark a parameter for automatic injection.

purge(namespace: Optional[str] = None)

Clears dependencies, either for a specific namespace or for all namespaces.

Contributing

Contributions are welcome! Feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

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

py_simple_inject-0.7.0.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

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

py_simple_inject-0.7.0-py3-none-any.whl (6.7 kB view details)

Uploaded Python 3

File details

Details for the file py_simple_inject-0.7.0.tar.gz.

File metadata

  • Download URL: py_simple_inject-0.7.0.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.21.0 CPython/3.10.0 Windows/10

File hashes

Hashes for py_simple_inject-0.7.0.tar.gz
Algorithm Hash digest
SHA256 604f6d99bb2160552bd0b23a3ee2c1988fcb1ad634f2af97bf609bfee85e29d2
MD5 9bbd248f34eda1085039a8c66b9bfd93
BLAKE2b-256 df44d51a368b78948dcfb7b828089f2d5528ad00ef272bb67f85b574a0a1d60e

See more details on using hashes here.

File details

Details for the file py_simple_inject-0.7.0-py3-none-any.whl.

File metadata

  • Download URL: py_simple_inject-0.7.0-py3-none-any.whl
  • Upload date:
  • Size: 6.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.21.0 CPython/3.10.0 Windows/10

File hashes

Hashes for py_simple_inject-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 17448acf093bbe8867751141c27bb46ad9ce66da5da593fe8694dff43a9c620e
MD5 d579fc014474103071eaf708882fe8da
BLAKE2b-256 cbddebe81301efba57900ac138338f280b1c53a35604b9f1b77f548aece49dd5

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