svcs: A Flexible Service Locator
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
- breaking The handling of context managers passed to `register_value()` changed in version 23.21.0. Previously, `svcs` would NOT enter/exit context managers registered this way. Post 23.21.0, `svcs` WILL automatically enter and exit them by default.
- gotcha Failing to close `svcs.Container` or `svcs.Registry` instances with pending cleanups will raise a `ResourceWarning`.
Install
-
pip install svcs
Imports
- Registry
from svcs import Registry
- Container
from svcs import Container
- svcs_from_factory
from svcs import svcs_from_factory
Quickstart
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())