svcs: A Flexible Service Locator

25.1.0 · active · verified Thu Apr 09

svcs is a flexible service locator for Python applications, simplifying dependency management and resource cleanup. It currently stands at version 25.1.0 and typically releases new versions every 1-2 months, incorporating bug fixes, minor features, and framework integrations.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a service, register it with `svcs.Registry` using a factory function, and then acquire and use it via `svcs.Container`. It also shows the recommended practice of using a `with` statement for automatic container cleanup.

import svcs

class MyService:
    def __init__(self, name: str):
        self.name = name

    def hello(self) -> str:
        return f"Hello from {self.name}!"

def create_my_service() -> MyService:
    return MyService(name="quickstart_service")

# 1. Create a registry and register your service factory
reg = svcs.Registry()
reg.register_factory(MyService, create_my_service)

# 2. Get a container, ensuring it's closed properly
with svcs.Container(reg) as container:
    # 3. Acquire the service
    service = container.get(MyService)
    print(service.hello())

view raw JSON →