Metadata-Version: 2.4
Name: pyboot-framework
Version: 0.1.20
Summary: A lightweight, extensible Python framework for building applications with dependency injection and a modular plugin architecture.
Author: Siddharth Karn
License-Expression: MIT
Keywords: pyboot,python-framework,dependency-injection,inversion-of-control,ioc,plugin-architecture,starlette
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: loguru>=0.7.3
Dynamic: license-file

# PyBoot

PyBoot is a lightweight Python framework for inversion of control (IoC),
constructor dependency injection, class discovery, and asynchronous plugin
lifecycle management.

The core package provides the container and lifecycle. Optional packages such
as [`pyboot-web`](../plugins/pyboot_web/README.md) add application features
through PyBoot plugins.

## Requirements and installation

- Python 3.11 or newer
- `pyboot-framework` 0.1.19

```bash
python -m pip install pyboot-framework
```

For a source checkout:

```bash
python -m pip install -e .
```

## Quick start

PyBoot scans the package passed to `bootstrap()` and its submodules. Put
managed classes below that package.

`app/services.py`:

```python
from pyboot.core.builtins.component import Component


@Component()
class GreetingService:
    def greet(self, name: str) -> str:
        return f"Hello, {name}!"
```

`main.py`:

```python
import asyncio

from pyboot import PyBoot
from app.services import GreetingService


async def main() -> None:
    boot = PyBoot(debug=False)
    boot.bootstrap(package="app")

    service = await boot.get_context().ioc.get_bean(GreetingService)
    print(service.greet("PyBoot"))


asyncio.run(main())
```

`bootstrap()` is a synchronous convenience method that runs the asynchronous
bootstrap lifecycle with `asyncio.run()`. Bean retrieval is asynchronous and
must be awaited. Do not call `bootstrap()` from a coroutine that already owns
an event loop; use the application boundary to invoke it outside that loop.

Enable PyBoot logging with `PyBoot(debug=True)`.

## Components and dependency injection

`@Component()` marks a class for the built-in component plugin. Required
constructor parameters must have type annotations:

```python
from pyboot.core.builtins.component import Component


@Component()
class UserRepository:
    def find_name(self, user_id: int) -> str:
        return {1: "Ada", 2: "Grace"}.get(user_id, "Unknown")


@Component()
class UserService:
    def __init__(self, repository: UserRepository) -> None:
        self.repository = repository

    def name_for(self, user_id: int) -> str:
        return self.repository.find_name(user_id)
```

The container resolves dependencies recursively and stores resolved objects as
singletons. Retrieve beans asynchronously:

```python
async def check_singleton(boot: PyBoot) -> None:
    service = await boot.get_context().ioc.get_bean(UserService)
    same_service = await boot.get_context().ioc.get_bean(UserService)
    assert service is same_service
```

Optional constructor parameters with defaults are skipped. A required
parameter without a type annotation raises `DependencyResolutionException`.
Circular dependency graphs raise `CircularDependencyException`.

## Configuration and bean factories

Use `@Configuration()` for a class containing factory methods. Every
`@Bean()` method must declare a return type; that return type becomes the IoC
key.

```python
from pyboot.core.builtins.configuration import Bean, Configuration


class Settings:
    def __init__(self, service_name: str) -> None:
        self.service_name = service_name


@Configuration()
class ApplicationConfiguration:
    @Bean()
    def settings(self) -> Settings:
        return Settings("example-service")
```

Factory methods can receive other annotated beans and can be asynchronous:

```python
@Configuration()
class ClientConfiguration:
    @Bean()
    async def client(self, settings: Settings) -> dict[str, str]:
        return {"service": settings.service_name}
```

The configuration plugin registers factories during `after_register`, before
the framework creates the remaining registered beans.

## Application context and resources

```python
async def inspect_context(boot: PyBoot) -> None:
    context = boot.get_context()
    service = await context.ioc.get_bean(UserService)

    context.put_resource("service_name", "example-service")
    assert context.exist_resource("service_name")
    assert context.get_resource("service_name") == "example-service"

    context.update_resource("service_name", "updated-service")
```

`put_resource()` rejects duplicate keys. `update_resource()` requires an
existing key. Resources provide a small shared storage area for plugins.

## Plugin development

Plugins extend `PyBootPlugin` and are discovered from the
`pyboot.plugins` entry-point group:

```python
from pyboot import PyBootPlugin
from pyboot.core.pyboot_context import PyBootContext


class MetricsPlugin(PyBootPlugin):
    async def after_plugins_discovery(self, context: PyBootContext) -> None:
        context.put_resource("metrics", {"started": True})

    async def on_ready(self, context: PyBootContext) -> None:
        print("PyBoot is ready")
```

Register it in the plugin distribution:

```toml
[project.entry-points."pyboot.plugins"]
metrics = "my_metrics.plugin:MetricsPlugin"
```

Lifecycle methods are asynchronous. PyBoot awaits both async and synchronous
results returned by lifecycle methods:

```text
after_plugins_discovery
before_classes_discovery
after_classes_discovery
before_register
on_register
after_register
before_load
on_load
after_load
on_ready
```

Use `on_register()` to register classes or bean factories. Use `after_load()` or
`on_ready()` when registered beans are available. Plugin ordering is not
guaranteed.

Loaded plugins are keyed by class:

```python
from my_metrics.plugin import MetricsPlugin


metrics = boot.get_plugin(MetricsPlugin)
```

`get_plugin()` raises `LookupError` when the class was not loaded.

## Built-in plugins

The core package registers:

| Entry point | Implementation | Responsibility |
| --- | --- | --- |
| `configuration` | `ConfigurationPlugin` | Registers `@Configuration()` and `@Bean()` |
| `component` | `ComponentPlugin` | Registers `@Component()` classes |

Other distributions can add entry points. `pyboot-web` adds its own
`RestPlugin`.

## Discovery rules

For `bootstrap("app")`, PyBoot:

1. Loads installed `pyboot.plugins` entry points.
2. Imports `app`.
3. Walks its submodules with `pkgutil`.
4. Records classes defined in those modules.
5. Lets plugins register supported classes.
6. Creates registered beans asynchronously.
7. Runs the loading and ready lifecycle hooks.

Use importable packages with `__init__.py` files. Imported classes are ignored
when their `__module__` does not match the module being scanned.

## Common exceptions

- `ClassNotRegisteredForBean`: the requested type is not registered.
- `DependencyResolutionException`: a dependency cannot be resolved.
- `CircularDependencyException`: the dependency graph contains a cycle.
- `MultipleBeanException`: two registrations use one bean type.
- `KeyAlreadyInResourceBucketException`: a resource key already exists.

Import these from `pyboot.core.exceptions` when they need explicit handling.

## Testing

Test business logic without the framework:

```python
def test_user_service() -> None:
    service = UserService(UserRepository())
    assert service.name_for(1) == "Ada"
```

Test asynchronous IoC resolution separately:

```python
import pytest


@pytest.mark.asyncio
async def test_user_service_is_wired() -> None:
    boot = PyBoot()
    boot.bootstrap("app")
    service = await boot.get_context().ioc.get_bean(UserService)
    assert service.name_for(1) == "Ada"
```

## Related documentation

- [Core examples](./examples.md)
- [pyboot-web README](../plugins/pyboot_web/README.md)
- [pyboot-web examples](../plugins/pyboot_web/EXAMPLES.md)

## License

PyBoot is distributed under the MIT License. See [LICENSE](./LICENSE).
