Metadata-Version: 2.4
Name: typed-registry
Version: 0.2.0
Summary: A tiny, fully typed service registry for Python application composition
Keywords: dependency-injection,service-locator,registry,typing,composition-root
Author: Denis Maciel
Author-email: Denis Maciel <denispmaciel@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.14
Project-URL: Homepage, https://github.com/denismaciel/typed-registry
Project-URL: Repository, https://github.com/denismaciel/typed-registry
Project-URL: Issues, https://github.com/denismaciel/typed-registry/issues
Description-Content-Type: text/markdown

# typed-registry

A tiny, zero-dependency, fully typed service registry for Python — ~90 lines of code, no casts.

```python
event_bus = registry.get(Services.event_bus)  # type checker knows: EventBus
mailer = registry.get(Services.mailer)        # type checker knows: Mailer | None
```

## Why

Most service locators key services by string or class and hand back `Any`, forcing `cast(...)` at every call site. `typed-registry` keys services by **typed tokens** instead. Each token carries the type and optionality of the service it names:

- `registry.get(token)` returns `T` for `ServiceToken[T]` and `T | None` for `OptionalToken[T]`, inferred by MyPy, ty, and Zuban.
- `token.register(registry, value)` rejects values of the wrong type at type-check time and raises `DuplicateServiceError` on accidental double-registration.
- Two tokens with the same name never collide, because tokens compare by identity.
- `registry.freeze()` locks the registry after composition so runtime code cannot mutate it.

## Install

Requires Python 3.14+.

```sh
uv add typed-registry
```

## Quick start

Declare a catalogue of tokens owned by your application. Token names are derived automatically from the class and attribute name via `__set_name__` (or pass an explicit string):

```python
from typing import Final

from typed_registry import OptionalToken, ServiceToken


class Services:
    event_bus: Final = ServiceToken[EventBus]()
    settings: Final = ServiceToken[Settings]()
    mailer: Final = OptionalToken[Mailer]()
```

Wire concrete services in your composition root and freeze the registry when wiring finishes:

```python
from typed_registry import ServiceRegistry

registry = ServiceRegistry()
Services.settings.register(registry, Settings.from_env())
Services.event_bus.register(registry, EventBus())
registry.freeze()
```

Resolve them where you assemble the rest of the application:

```python
event_bus = registry.get(Services.event_bus)  # EventBus
settings = registry.get(Services.settings)    # Settings
mailer = registry.get(Services.mailer)        # Mailer | None
```

Type mismatches fail before your code runs:

```python
Services.event_bus.register(registry, Settings())
# error: Argument 2 to "register" of "_Token" has incompatible type "Settings"; expected "EventBus"
```

Requesting an unregistered `ServiceToken` raises `MissingServiceError` (a `LookupError` subclass) exposing `service_name`. Registering the same token twice raises `DuplicateServiceError` (a `ValueError` subclass).

```python
from typed_registry import MissingServiceError

try:
    registry.get(Services.event_bus)
except MissingServiceError as error:
    print(error.service_name)  # "Services.event_bus"
```

## Testing

Use `copy()` to clone a frozen production-wired registry into a mutable copy, then `override()` or `unregister()` individual tokens — still type-checked against the token:

```python
registry = build_registry().copy()
Services.event_bus.override(registry, FakeEventBus())
```

## Design notes

`typed-registry` belongs in the **composition root** — the single place where an application builds its object graph. Keep the registry there and pass narrow dependencies into domain code as plain arguments.

Deliberate non-features:

- **No autowiring or reflection.** Construct services yourself, in order.
- **No scopes or lifecycles.** Create one registry per scope if needed.
- **No global registry.** Instantiate and pass `ServiceRegistry` explicitly.

## API

| Name | Description |
| --- | --- |
| `ServiceToken[T](name="")` | Required typed, identity-compared key (`name` defaults to `Owner.attr` via `__set_name__`). |
| `OptionalToken[T](name="")` | Optional typed, identity-compared key (`registry.get` returns `T \| None`). |
| `token.register(registry, service)` | Store `service: T`; raises `DuplicateServiceError` if already registered or `FrozenRegistryError` if frozen. |
| `token.override(registry, service)` | Insert or replace `service: T`; raises `FrozenRegistryError` if frozen. |
| `token.unregister(registry)` | Remove the token if present; raises `FrozenRegistryError` if frozen. |
| `ServiceRegistry.get(token)` | Return `T` for `ServiceToken[T]` (raising `MissingServiceError` if absent) or `T \| None` for `OptionalToken[T]`. |
| `ServiceRegistry.get_optional(token)` | Return `T \| None` for either token kind without raising. |
| `token in registry` | Check whether a token is registered. |
| `ServiceRegistry.freeze()` / `.frozen` | Lock the registry against further mutations. |
| `ServiceRegistry.copy()` | Return an unfrozen shallow copy of the registry. |
| `MissingServiceError` | `LookupError` subclass with `service_name`. |
| `DuplicateServiceError` | `ValueError` subclass with `service_name`. |
| `FrozenRegistryError` | `RuntimeError` raised when mutating a frozen registry. |

## Development

See [docs/development.md](docs/development.md) for local setup, checks, and release procedures.

## License

MIT. See [LICENSE](LICENSE).
