Skip to main content

A Lightweight Service Locator

Project description

svcs logo showing a radar

A Lightweight Service Locator for Python.

WARNING ☠️ Not ready yet! ☠️

This project is only public to gather feedback, and everything can and will change until the project is proclaimed stable.

Currently only Flask support is production-ready, but API details can still change.

At this point, it's unclear whether this project will become a "proper Hynek project". I will keep using it for my work projects, but whether this will grow beyond my personal needs depends on community interest.

svcs (pronounced services) is a service locator for Python. It provides you with a central place to register factories for types/interfaces and then imperatively request instances of those types with automatic cleanup and health checks.


This allows you to configure and manage all your resources in one central place and access them in a consistent way without worrying about cleaning them up.


In practice that means that at runtime, you say "Give me a database connection!", and svcs will give you whatever you've configured it to return when asked for a database connection. This can be an actual database connection or it can be a mock object for testing. All of this happens within your application – service locators are not related to service discovery.

If you follow the Dependency Inversion Principle (aka "program against interfaces, not implementations"), you would register concrete factories for abstract interfaces; in Python usually a Protocol or an abstract base class.

Benefits:

  • Eliminates tons of repetitive boilerplate code,
  • unifies acquisition and cleanups of resources,
  • simplifies testing,
  • and allows for easy health checks across all resources.

The goal is to minimize your business code to:

def view(request):
    db = request.services.get(Database)
    api = request.services.get(WebAPIClient)

or, if you don't shy away from some global state, even:

def view():
    db = services.get(Database)
    api = services.get(WebAPIClient)

The latter already works with Flask by utilizing the g object.

You set it up like this:

import atexit

from sqlalchemy import Connection, create_engine

...

engine = create_engine("postgresql://localhost")

def connection_factory():
    with engine.connect() as conn:
        yield conn

registry = svcs.Registry()
registry.register_factory(
    Connection,
    connection_factory,
    on_registry_close=engine.dispose
)

@atexit.register
def cleanup():
    registry.close()  # calls engine.dispose()

The generator-based setup and cleanup may remind you of pytest fixtures. The hooks that are defined as on_registry_close are called when you call Registry.close() – e.g. when your application is shutting down.

svcs comes with full async support via a-prefixed methods (i.e. aget() instead of get(), et cetera).

IMPORTANT All of this may look over-engineered if you have only one or two resources. However, it starts paying dividends very fast once you go past that.

Is this Dependency Injection!?

No.

Although the concepts are related and share the idea of having a central registry of services, the ways they provide those services are fundamentally different: Dependency injection always passes your dependencies as arguments while you actively ask a service locator for them when you need them. That usually requires less opaque magic since nothing meddles with your function/method definitions. But you can use, e.g., your web framework's injection capabilities to inject the locator object into your views and benefit from svcs's upsides without giving up some of DI's ones.

The active acquisition of resources by calling get() when you know for sure you're going to need it avoids the conundrum of either having to pass a factory (e.g., a connection pool – which also puts the onus of cleanup on you) or eagerly creating resources that you never use:

def view(request):
    if request.form.valid():
        # Form is valid; only NOW get a DB connection
        # and pass it into your business logic.
        return handle_form_data(
            request.services.get(Database),
            form.data,
        )

    raise InvalidFormError()

The main downside is that it's impossible to verify whether all required dependencies have been configured without running the code.

If you still prefer dependency injection, check out incant.


For now, please refer to the GitHub README for latest documentation.

Release Information

Added

  • Factories now may take a parameter called svcs_container or that is annotated to be svcs.Container. In this case the factory will receive the current container as a first positional argument. This allows for recursive factories without global state. #10

→ Full Changelog

Credits

svcs is written by Hynek Schlawack and distributed under the terms of the MIT license.

The development is kindly supported by my employer Variomedia AG and all my amazing GitHub Sponsors.

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

svcs-23.7.0.tar.gz (30.3 kB view hashes)

Uploaded Source

Built Distribution

svcs-23.7.0-py3-none-any.whl (9.8 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page