Skip to main content

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 add application features through PyBoot plugins.

Requirements and installation

  • Python 3.11 or newer
  • pyboot-framework 0.1.19
python -m pip install pyboot-framework

For a source checkout:

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:

from pyboot.core.builtins.component import Component


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

main.py:

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:

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:

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.

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:

@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

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:

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:

[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:

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:

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:

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

Test asynchronous IoC resolution separately:

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"

License

PyBoot is distributed under the MIT License. See LICENSE.

Metadata

Release files for pyboot-framework 0.1.22

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyboot-framework 0.1.22
File Size Uploaded Provenance Actions
pyboot_framework-0.1.22.tar.gz 15.3 kB Without provenance Details for pyboot_framework-0.1.22.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyboot-framework 0.1.22
File Interpreter ABI Platform Actions
pyboot_framework-0.1.22-py3-none-any.whl Python 3 none any Details for pyboot_framework-0.1.22-py3-none-any.whl

Total release size: 31.7 kB

Release files / pyboot_framework-0.1.22.tar.gz

Download URL pyboot_framework-0.1.22.tar.gz
Size 15.3 kB
Tags Source
SHA-256 checksum
How to use checksums
619d60597b09ec7acec37cfa39a3a346abb5b2bfc116880683bf677b1581c57f
BLAKE2b-256 checksum
How to use checksums
10a60103e21788262f98b8b8e36749e4653dfd339f42f8446d6335b757a63430
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / pyboot_framework-0.1.22-py3-none-any.whl

Download URL pyboot_framework-0.1.22-py3-none-any.whl
Size 16.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
213f759e818d4c686b9824a19eebe1eab88c4816d9a503c2194549e4421510ac
BLAKE2b-256 checksum
How to use checksums
8a0aa158bae8e131d9da1590cdd74dada8d564bfaa281e61b316f7bbc261d16e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for pyboot-framework 0.1.22

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page