Python Dependency Injection Library
Project description
Wireup
Modern Dependency Injection for Python.
Wireup is a performant, concise, and easy-to-use dependency injection container for Python 3.8+.
⚡ Key Features
- Inject services and configuration.
- Interfaces and abstract classes.
- Factory pattern.
- Singleton and transient dependencies.
- Framework-agnostic.
- Apply the container anywhere as a decorator
- Service Locator
- Simplified use with Django, Flask, and FastAPI.
📋 Quickstart
Example showcasing a Redis wrapper and a weather service that calls an external API and caches results as needed.
1. Set up
from wireup import container, initialize_container
def create_app():
app = ...
# ⬇️ Start the container: Register and initialize services.
initialize_container(
container,
# Parameters serve as application/service configuration.
parameters={
"redis_url": os.environ["APP_REDIS_URL"],
"weather_api_key": os.environ["APP_WEATHER_API_KEY"]
},
# Top-level modules containing service registrations.
service_modules=[services]
)
return app
2. Register services
Use a declarative syntax to describe services, and let the container handle the rest.
from wireup import service, Inject
@service # ⬅️ Decorator tells the container this is a service.
class KeyValueStore:
# Inject the value of the parameter during creation. ⬇️
def __init__(self, dsn: Annotated[str, Inject(param="redis_url")]):
self.client = redis.from_url(dsn)
def get(self, key: str) -> Any: ...
def set(self, key: str, value: Any): ...
@service
@dataclass # Can be used alongside dataclasses to simplify init boilerplate.
class WeatherService:
# Inject the value of the parameter to this field. ⬇️
api_key: Annotated[str, Inject(param="weather_api_key")]
kv_store: KeyValueStore # ⬅️ This will be injected automatically.
def get_forecast(self, lat: float, lon: float) -> WeatherForecast:
...
3. Inject
Decorate targets where the library should perform injection.
from wireup import container
@app.get("/weather/forecast")
# ⬇️ Decorate functions to perform Dependency Injection.
@container.autowire
def get_weather_forecast_view(weather_service: WeatherService, request):
return weather_service.get_forecast(request.lat, request.lon)
Installation
# Install using poetry:
poetry add wireup
# Install using pip:
pip install wireup
📑 Documentation
For more information check out the documentation
🎮 Demo application
A demo flask application is available at maldoinc/wireup-demo
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
wireup-0.9.0.tar.gz
(20.2 kB
view hashes)
Built Distribution
wireup-0.9.0-py3-none-any.whl
(25.0 kB
view hashes)