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.22
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


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

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


main()

bootstrap() is a synchronous convenience method that runs the asynchronous bootstrap lifecycle with asyncio.run(). Bean retrieval is asynchronous and must be awaited when requested directly. 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 WebPlugin.

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:

def test_user_service_is_wired() -> None:
    import asyncio

    boot = PyBoot()
    boot.bootstrap("app")
    service = asyncio.run(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.26

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.26
File Size Uploaded Provenance Actions
pyboot_framework-0.1.26.tar.gz 15.8 kB Without provenance Details for pyboot_framework-0.1.26.tar.gz

Built distribution (wheel)

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

Total release size: 32.8 kB

Release files / pyboot_framework-0.1.26.tar.gz

Download URL pyboot_framework-0.1.26.tar.gz
Size 15.8 kB
Tags Source
SHA-256 checksum
How to use checksums
35468007117bad26c89a20e2e5f4984e60f9405089e6a8231ebedf807f283eab
BLAKE2b-256 checksum
How to use checksums
7c1b8e21222a3d326c4754641171a4ac03e44d25a001f181f3d5fb3aaee91a35
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.26-py3-none-any.whl

Download URL pyboot_framework-0.1.26-py3-none-any.whl
Size 17.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
60f72535a3a062482568b2662d7c306c30bc833e95e074373997d27909a1b2f9
BLAKE2b-256 checksum
How to use checksums
146499aa1e55c5fba60f0396ea10fb7d7f19d0e8a030936d3a9636c9dfd79534
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.26

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