https://github.com/maldoinc/wireup
Concise, Powerful, and Type-Safe Python Dependency Injection Library
https://github.com/maldoinc/wireup
dependency-injection dependency-injection-container dependency-injector django flask injector python
Last synced: 1 day ago
JSON representation
Concise, Powerful, and Type-Safe Python Dependency Injection Library
- Host: GitHub
- URL: https://github.com/maldoinc/wireup
- Owner: maldoinc
- License: mit
- Created: 2023-08-19T22:09:32.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-04-10T22:02:51.000Z (about 1 year ago)
- Last Synced: 2024-04-11T01:48:30.487Z (about 1 year ago)
- Topics: dependency-injection, dependency-injection-container, dependency-injector, django, flask, injector, python
- Language: Python
- Homepage: https://maldoinc.github.io/wireup/
- Size: 4.43 MB
- Stars: 55
- Watchers: 3
- Forks: 0
- Open Issues: 6
-
Metadata Files:
- Readme: readme.md
- License: license.md
Awesome Lists containing this project
- awesome-dependency-injection-in-python - Wireup - Concise, Powerful, and Type-Safe Python Dependency Injection Library. [๐, MIT License]. (Software / DI Frameworks / Containers)
README
Wireup
Performant, concise and type-safe Dependency Injection for Python 3.8+
[](https://github.com/maldoinc/wireup)
[](https://github.com/maldoinc/wireup)
[](https://codeclimate.com/github/maldoinc/wireup)
[](https://pypi.org/project/wireup/)
[](https://pypi.org/project/wireup/)๐ Documentation | ๐ฎ Demo Application
> [!NOTE]
> Wireup 1.0 has been released, featuring support for scoped lifetimes, a simplified API, enhanced type safety, and improved documentation.
> Refer to the [Upgrading Guide](https://maldoinc.github.io/wireup/latest/upgrading/) for instructions on upgrading from version 0.x to 1.0.
---Dependency Injection (DI) is a design pattern where dependencies are provided externally rather than created within objects. Wireup automates dependency management using Python's type system, with support for async, generators and modern Python features.
## Features
### โจ Simple & Type-Safe DI
Inject services and configuration using a clean and intuitive syntax.
```python
@service
class Database:
pass@service
class UserService:
def __init__(self, db: Database) -> None:
self.db = dbcontainer = wireup.create_sync_container(services=[Database, UserService])
user_service = container.get(UserService) # โ Dependencies resolved.
```Example With Configuration
```python
@service
class Database:
def __init__(self, db_url: Annotated[str, Inject(param="db_url")]) -> None:
self.db_url = db_urlcontainer = wireup.create_sync_container(
services=[Database],
parameters={"db_url": os.environ["APP_DB_URL"]}
)
database = container.get(Database) # โ Dependencies resolved.
```### ๐ฏ Function Injection
Inject dependencies directly into functions with a simple decorator.
```python
@inject_from_container(container)
def process_users(service: Injected[UserService]):
# โ UserService injected.
pass
```### ๐ Interfaces & Abstract Classes
Define abstract types and have the container automatically inject the implementation.
```python
@abstract
class Notifier(abc.ABC):
pass@service
class SlackNotifier(Notifier):
passnotifier = container.get(Notifier)
# โ SlackNotifier instance.
```### ๐ Managed Service Lifetimes
Declare dependencies as singletons, scoped, or transient to control whether to inject a fresh copy or reuse existing instances.
```python
# Singleton: One instance per application. `@service(lifetime="singleton")` is the default.
@service
class Database:
pass# Scoped: One instance per scope/request, shared within that scope/request.
@service(lifetime="scoped")
class RequestContext:
def __init__(self) -> None:
self.request_id = uuid4()# Transient: When full isolation and clean state is required.
# Every request to create transient services results in a new instance.
@service(lifetime="transient")
class OrderProcessor:
pass
```### ๐ญ Flexible Creation Patterns
Defer instantiation to specialized factories when complex initialization or cleanup is required.
Full support for async and generators. Wireup handles cleanup at the correct time depending on the service lifetime.**Synchronous**
```python
class WeatherClient:
def __init__(self, client: requests.Session) -> None:
self.client = client@service
def weather_client_factory() -> Iterator[WeatherClient]:
with requests.Session() as session:
yield WeatherClient(client=session)
```**Async**
```python
class WeatherClient:
def __init__(self, client: aiohttp.ClientSession) -> None:
self.client = client@service
async def weather_client_factory() -> AsyncIterator[WeatherClient]:
async with aiohttp.ClientSession() as session:
yield WeatherClient(client=session)
```### ๐ก๏ธ Improved Safety
Wireup is mypy strict compliant and will not introduce type errors in your code. It will also warn you at the earliest possible stage about configuration errors to avoid surprises.
**Container Creation**
The container will raise errors at creation time about missing dependencies or other issues.
```python
@service
class Foo:
def __init__(self, unknown: NotManagedByWireup) -> None:
passcontainer = wireup.create_sync_container(services=[Foo])
# โ Parameter 'unknown' of 'Foo' depends on an unknown service 'NotManagedByWireup'.
```**Function Injection**
Injected functions will raise errors at module import time rather than when called.
```python
@inject_from_container(container)
def my_function(oops: Injected[NotManagedByWireup]):
pass# โ Parameter 'oops' of 'my_function' depends on an unknown service 'NotManagedByWireup'.
```**Integrations**
Wireup integrations assert that requested injections in the framework are valid.
```python
@app.get("/")
def home(foo: Injected[NotManagedByWireup]):
passwireup.integration.flask.setup(container, app)
# โ Parameter 'foo' of 'home' depends on an unknown service 'NotManagedByWireup'.
```### ๐ Framework-Agnostic
Wireup provides its own Dependency Injection mechanism and is not tied to specific frameworks. Use it anywhere you like.
### ๐ Share Services Between Application and CLI
Share the service layer between your web application and its accompanying CLI using Wireup.
### ๐ Native Integration with Django, FastAPI, or Flask
Integrate with popular frameworks for a smoother developer experience.
Integrations manage request scopes, injection in endpoints, and lifecycle of services.```python
app = FastAPI()
container = wireup.create_async_container(services=[UserService, Database])@app.get("/")
def users_list(user_service: Injected[UserService]):
passwireup.integration.fastapi.setup(container, app)
```### ๐งช Simplified Testing
Wireup does not patch your services and lets you test them in isolation.
If you need to use the container in your tests, you can have it create parts of your services
or perform dependency substitution.```python
with container.override.service(target=Database, new=in_memory_database):
# The /users endpoint depends on Database.
# During the lifetime of this context manager, requests to inject `Database`
# will result in `in_memory_database` being injected instead.
response = client.get("/users")
```## ๐ Documentation
For more information [check out the documentation](https://maldoinc.github.io/wireup)
## ๐ฎ Demo application
A demo flask application is available at [maldoinc/wireup-demo](https://github.com/maldoinc/wireup-demo)