### Quick start: dependency injection with @singleton, @injectable, and @inject Source: https://github.com/100nm/python-injection/blob/prod/docs/index.md Demonstrates the core usage of python-injection. The @singleton decorator registers the Printer class as a singleton, @injectable registers Service with its dependencies resolved via type hints, and @inject resolves the Service parameter in the main function. The example prints 'Hello world!' when run. ```python from injection import injectable, inject, singleton @singleton class Printer: def __init__(self): self.history = [] def print(self, message: str): self.history.append(message) print(message) @injectable class Service: def __init__(self, printer: Printer): self.printer = printer def hello(self): self.printer.print("Hello world!") @inject def main(service: Service): service.hello() if __name__ == "__main__": main() ``` -------------------------------- ### Resolve dependencies in entrypoint setup Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/main-functions.md Resolves a Config dependency from the setup function parameters to determine which profile to load. The config is registered as a constant in the default module. Dependencies resolved in the entrypoint setup must be registered in the default module (not profile-specific) and should be transient or constant to avoid state issues. ```python from dataclasses import dataclass from injection import constant from injection.entrypoint import Entrypoint, entrypointmaker from injection.loaders import PythonModuleLoader from os import getenv @dataclass class Config: profile: Profile @constant def _config_factory() -> Config: profile = Profile(getenv("PROFILE", "development")) return Config(profile) @entrypointmaker(profile_loader=profile_loader) def entrypoint[**P, T](self: Entrypoint[P, T], config: Config) -> Entrypoint[P, T]: import src profile = config.profile # Use config to determine profile suffixes = self.profile_loader.required_module_names(profile) module_loader = PythonModuleLoader.endswith(*suffixes) return self.inject().load_profile(profile).load_modules(module_loader, src) ``` -------------------------------- ### Install python-injection with pip Source: https://github.com/100nm/python-injection/blob/prod/docs/index.md Install the package using pip. Requires Python 3.12 or higher. ```bash pip install python-injection ``` -------------------------------- ### PythonModuleLoader.startswith: Filter by prefix Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/imports.md Imports only modules whose names start with the given prefix. Uses the startswith factory method. ```python # Import only modules starting with "impl_" PythonModuleLoader.startswith("impl_").load(adapters, services) ``` -------------------------------- ### Integrate ProfileLoader with entrypointmaker Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/main-functions.md Passes a ProfileLoader to @entrypointmaker via the profile_loader parameter. The setup loads a specific profile (Profile.DEV) with load_profile before loading modules. The load_profile method accepts a profile name and loads it before the main function executes. ```python from injection.entrypoint import Entrypoint, entrypointmaker from injection.loaders import ProfileLoader, PythonModuleLoader profile_loader = ProfileLoader(...) @entrypointmaker(profile_loader=profile_loader) def entrypoint[**P, T](self: Entrypoint[P, T]) -> Entrypoint[P, T]: import src module_loader = PythonModuleLoader.endswith("_impl") return ( self.inject() .load_profile(Profile.DEV) # Load a specific profile .load_modules(module_loader, src) ) ``` -------------------------------- ### Get instance with get_instance Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use get_instance to retrieve the instance of the specified type. Returns NotImplemented if not found. ```python from injection import get_instance dependency = get_instance(Dependency) ``` -------------------------------- ### Define Profile StrEnum and get module with mod Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/profiles.md Defines a Profile StrEnum with development, production, and staging values, then retrieves a module for the development profile using the mod function. ```python from enum import StrEnum from injection import mod class Profile(StrEnum): DEV = "development" PROD = "production" STAGING = "staging" # Get a module for a specific profile dev_module = mod(Profile.DEV) ``` -------------------------------- ### Marking a module with # auto-import comment Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/imports.md Example of a module that contains the '# auto-import' comment, which is used by from_keywords to include it in auto-importing. ```python # auto-import @injectable(on=AbstractDependency) class Dependency(AbstractDependency): ... ``` -------------------------------- ### Get instance with find_instance Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use find_instance to retrieve the instance of the specified type. Raises NoInjectable if not found. Useful when you expect the dependency to always be available and want to fail fast if it's not registered. ```python from injection import find_instance dependency = find_instance(Dependency) ``` -------------------------------- ### Scoped dependency with context manager Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a scoped dependency using a generator function to handle setup and teardown logic. Supports sync and async generators. ```python from collections.abc import Iterator from injection import scoped class Dependency: def open(self): ... def close(self): ... @scoped("") def dependency_factory() -> Iterator[Dependency]: dependency = Dependency() dependency.open() try: yield dependency finally: dependency.close() ``` -------------------------------- ### Use test_constant decorator Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Define a test constant factory that overrides a production constant for testing. The example shows a frozen dataclass Settings and test factory returning test values. ```python from dataclasses import dataclass from injection import constant from injection.testing import test_constant from os import environ @dataclass(frozen=True) class Settings: api_key: str debug: bool @constant def _settings_factory() -> Settings: return Settings(environ["API_KEY"], debug=False) @test_constant def _settings_test_factory() -> Settings: return Settings("test_key_123", debug=True) ``` -------------------------------- ### Inject sync dependency with LazyInstance in a test class Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/classes.md Use LazyInstance as a class attribute in a test class to inject a sync dependency. The dependency is resolved on every access, so with transient dependencies you get a new instance each time, while singletons return the same instance. ```python from injection import LazyInstance class TestFeature: dependency = LazyInstance(Dependency) def test_something(self): result = self.dependency.some_method() assert result == expected_value ``` -------------------------------- ### Inspect required modules with required_module_names Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/profiles.md Calls required_module_names on a ProfileLoader to get the set of module names required by the development profile. The output is a frozenset containing the profile, the stub subprofile, and the default module. ```python dev_modules = profile_loader.required_module_names(Profile.DEV) # Returns: frozenset({, , '__default__'}) ``` -------------------------------- ### Mypy error with @inject without default Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Static type checkers like mypy will report a missing argument error when calling an injected function without providing the dependency. This example shows the mypy error that occurs when no default value is provided. ```python @inject def function(dependency: Dependency): ... function() # ❌ mypy error: Missing positional argument "dependency" in call to "function" [call-arg] ``` -------------------------------- ### Create custom entrypoint with @entrypointmaker Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/main-functions.md Defines a custom entrypoint decorator with @entrypointmaker that injects dependencies, defines a shared lifespan scope, converts async to sync, and loads modules. The second block shows using the custom @entrypoint on a main function. Builder instructions execute in reverse order: modules load first, then async-to-sync conversion, then scope definition, then injection. ```python from injection import adefine_scope from injection.entrypoint import AsyncEntrypoint, Entrypoint, entrypointmaker from injection.loaders import PythonModuleLoader @entrypointmaker def entrypoint[**P, T](self: AsyncEntrypoint[P, T]) -> Entrypoint[P, T]: import src module_loader = PythonModuleLoader.endswith("_impl") return ( self.inject() .decorate(adefine_scope("lifespan", kind="shared")) .async_to_sync() .load_modules(module_loader, src) ) ``` ```python @entrypoint async def main(dependency: Dependency): # All setup is automatically applied ... if __name__ == "__main__": main() ``` -------------------------------- ### load_packages: Import all modules from packages Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/imports.md Imports all modules from the given packages. Accepts module objects or strings. Call early in startup before loading profile and dependency resolution. ```python from injection.loaders import load_packages from src import adapters, services # Import all modules in adapters and services packages load_packages(adapters, services) # Or using string notation load_packages("src.adapters", "src.services") ``` -------------------------------- ### Correct timing for setting PYTHON_INJECTION_THREADSAFE Source: https://github.com/100nm/python-injection/blob/prod/docs/threadsafety.md Demonstrates the correct and incorrect timing for setting the `PYTHON_INJECTION_THREADSAFE` environment variable. The variable must be set before importing `injection`; setting it after import has no effect. ```python # ❌ Too late - injection already imported import injection os.environ["PYTHON_INJECTION_THREADSAFE"] = "1" # ✅ Correct - set before import os.environ["PYTHON_INJECTION_THREADSAFE"] = "1" import injection ``` -------------------------------- ### Load profile with load_profile Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/profiles.md Loads the development profile using the load_profile function. This is the simplest approach when profiles are independent and don't share dependencies. ```python from injection.loaders import load_profile load_profile(Profile.DEV) ``` -------------------------------- ### Use ProfileLoader to load shared modules Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/profiles.md Creates a ProfileLoader that maps development and test profiles to a shared stub module, then loads the development profile. Only a single ProfileLoader instance should be created for the entire application. ```python from injection.loaders import ProfileLoader profile_loader = ProfileLoader( { Profile.DEV: [SubProfile.STUB], Profile.TEST: [SubProfile.STUB], } ) profile_loader.load(Profile.DEV) ``` -------------------------------- ### Activate test profile with load_test_profile Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Call load_test_profile to activate the test profile. This is required before using test dependencies. ```python from injection.testing import load_test_profile load_test_profile() ``` -------------------------------- ### Import test-specific decorators from injection.testing Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Import all available test decorators: set_test_constant, test_constant, test_injectable, test_scoped, and test_singleton. ```python from injection.testing import ( set_test_constant, test_constant, test_injectable, test_scoped, test_singleton, ) ``` -------------------------------- ### Async getters: afind_instance, aget_instance, aget_lazy_instance Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use the async variants of the getters: afind_instance, aget_instance, and aget_lazy_instance. The async version of get_lazy_instance returns an awaitable instead of an invertible object. ```python from injection import afind_instance, aget_instance, aget_lazy_instance # Async variants dependency = await afind_instance(Dependency) dependency = await aget_instance(Dependency) lazy_dependency = aget_lazy_instance(Dependency) dependency = await lazy_dependency # Note: awaitable instead of invertible ``` -------------------------------- ### Use ProfileLoader.load as context manager Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/profiles.md Uses ProfileLoader.load as a context manager. While inside the with block the development profile is active; on exit the profile is unloaded and all cached instances are cleared. ```python with profile_loader.load(Profile.DEV): # Dev profile is active run_app() # Profile is unloaded, cache is cleared ``` -------------------------------- ### Autocall entrypoint with autocall=True Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/main-functions.md Uses the entrypoint decorator with autocall=True so the decorated function runs automatically when the module is executed. Convenient for scripts and CLI commands that should execute immediately. ```python @entrypoint(autocall=True) async def main(dependency: Dependency): # This function runs automatically when the module is executed ... ``` -------------------------------- ### Define an async scope with bindings using adefine Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/scopes.md Async version of `define` for scopes with bindings. Use with `async with` for async scoped dependencies. ```python async with Bindings("fr_FR").scope.adefine(): ... ``` -------------------------------- ### Register implementation for abstract class Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a class as the implementation for an abstract class using the 'on' parameter. Ensure the implementation is imported. ```python from injection import injectable from abc import ABC class AbstractDependency(ABC): ... @injectable(on=AbstractDependency) class Dependency(AbstractDependency): ... ``` -------------------------------- ### Define a scope with define_scope Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/scopes.md Creates a contextual scope (default) for the duration of the context. Dependencies registered with this scope are available only within the `with` block. The `scope_name` parameter is required; using a `StrEnum` to store scope names is recommended. ```python from injection import define_scope with define_scope(""): # Dependencies registered with this scope are available here ... ``` -------------------------------- ### Use load_profile as context manager Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/profiles.md Uses load_profile as a context manager. While inside the with block the development profile is active; on exit the profile is unloaded and all cached instances are cleared. ```python with load_profile(Profile.DEV): # Dev profile is active run_app() # Profile is unloaded, cache is cleared ``` -------------------------------- ### Pass ProfileLoader to load_test_profile Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md If using a ProfileLoader, pass it to load_test_profile to use that loader for the test profile. ```python from injection.loaders import ProfileLoader from injection.testing import load_test_profile profile_loader = ProfileLoader(...) load_test_profile(profile_loader) ``` -------------------------------- ### Use test_singleton decorator Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Register a mock class as a test singleton for an abstract dependency. ```python from injection.testing import test_singleton @test_singleton(on=AbstractDependency) class MockDependency(AbstractDependency): ... ``` -------------------------------- ### Defer resolution with get_lazy_instance Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use get_lazy_instance to defer dependency resolution until needed. The returned object implements the __invert__ operator; calling ~ on it resolves and returns the instance, or NotImplemented if not found. ```python from injection import get_lazy_instance lazy_dependency = get_lazy_instance(Dependency) # ... later in your code dependency = ~lazy_dependency ``` -------------------------------- ### Configure FastAPI with lifespan and request scopes Source: https://github.com/100nm/python-injection/blob/prod/docs/integrations/fastapi.md Configures FastAPI with application lifespan and request scopes. Defines an InjectionScope enum with LIFESPAN and REQUEST values, uses adefine_scope for the lifespan scope, and a request-scoped binding via FastAPIRequestBindings. The FastAPI app is created with the request_scope dependency and the lifespan context manager. ```python from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import dataclass from enum import StrEnum, auto from fastapi import Depends, FastAPI, Request from injection import MappedScope, adefine_scope class InjectionScope(StrEnum): LIFESPAN = auto() REQUEST = auto() @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: async with adefine_scope(InjectionScope.LIFESPAN, kind="shared"): yield @dataclass class FastAPIRequestBindings: # You can use any bindings; Request is just an example. request: Request scope = MappedScope(InjectionScope.REQUEST) async def request_scope(request: Request) -> AsyncIterator[None]: async with FastAPIRequestBindings(request).scope.adefine(): yield app = FastAPI( dependencies=[Depends(request_scope)], lifespan=lifespan, ) ``` -------------------------------- ### Define an async scope with adefine_scope Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/scopes.md Async version of `define_scope` for dependencies instantiated with async context managers. Must be used with `async with`. ```python from injection import adefine_scope async with adefine_scope(""): # Async scoped dependencies are available here ... ``` -------------------------------- ### Define a scope with bindings using MappedScope Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/scopes.md Defines a scope with associated data bindings using `MappedScope`. Bindings are injectable in all dependencies, making them accessible throughout the dependency graph. The `define` method accepts the `kind` parameter with the same `"contextual"` and `"shared"` options. ```python from injection import MappedScope type Locale = str @dataclass class Bindings: locale: Locale scope = MappedScope("") with Bindings("fr_FR").scope.define(): # Dependencies can now access the locale binding ... ``` -------------------------------- ### Singleton dependency with @singleton Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a class as a singleton, sharing a single instance across the entire application. ```python from injection import singleton @singleton class Dependency: ... ``` -------------------------------- ### Resolve on access with LazyInstance descriptor Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use LazyInstance as a descriptor to resolve the dependency each time it's accessed via self. Dependencies requiring an async context are not compatible with LazyInstance since descriptors cannot be awaited. ```python from injection import LazyInstance class Class: dependency = LazyInstance(Dependency) def do_something(self): self.dependency.some_method() # Resolved on every access ``` -------------------------------- ### PythonModuleLoader.from_keywords: Filter by comment marker Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/imports.md Imports only modules containing a specific comment. Useful for explicitly marking modules for auto-import. ```python # Import only modules containing a specific comment PythonModuleLoader.from_keywords("# auto-import").load(adapters, services) ``` -------------------------------- ### Profile-specific dependency with @mod Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a dependency for a specific profile using the @mod decorator. Using a StrEnum for profile names is recommended. ```python from injection import mod @mod("").injectable class Dependency: ... ``` -------------------------------- ### Pytest fixture to load test dependencies Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/pytest.md Add this fixture to your conftest.py to automatically load test dependencies for every test. The autouse=True parameter ensures the fixture runs without explicit reference. If using a ProfileLoader, pass it to load_test_profile. ```python # conftest.py import pytest from injection.testing import load_test_profile @pytest.fixture(scope="function", autouse=True) def setup_test_dependencies(): with load_test_profile(): yield ``` -------------------------------- ### PythonModuleLoader.endswith: Filter by suffix Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/imports.md Imports only modules whose names end with the given suffix. Uses the endswith factory method. ```python # Import only modules ending with "_impl" PythonModuleLoader.endswith("_impl").load(adapters, services) ``` -------------------------------- ### Enable thread safety with threadsafe parameter Source: https://github.com/100nm/python-injection/blob/prod/docs/threadsafety.md Use the `threadsafe=True` parameter on `@inject`, `get_instance`, and `define_scope` to enable thread safety for individual dependency resolution and scope definition operations. This is necessary when resolving dependencies or defining scopes in a multi-threaded environment. ```python from injection import define_scope, get_instance, inject # Thread-safe dependency injection @inject(threadsafe=True) def function(dependency: Dependency): ... # Thread-safe manual resolution dependency = get_instance(Dependency, threadsafe=True) # Thread-safe scope definition with define_scope("", threadsafe=True): ... ``` -------------------------------- ### Inject async dependency with aget_lazy_instance in a test class Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/classes.md Use aget_lazy_instance for async dependencies in test classes. It returns an awaitable that must be awaited to obtain the dependency before calling its async methods. ```python from injection import aget_lazy_instance class TestAsyncFeature: lazy_dependency = aget_lazy_instance(AsyncDependency) async def test_something(self): dependency = await self.lazy_dependency result = await dependency.some_method() assert result == expected_value ``` -------------------------------- ### Register pre-existing value with set_constant Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a pre-existing value (e.g., a dataclass instance) as a dependency using set_constant. ```python from dataclasses import dataclass from injection import set_constant @dataclass(frozen=True) class Settings: api_key: str settings = set_constant(Settings("")) ``` -------------------------------- ### Define a shared scope with kind="shared" Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/scopes.md Creates a shared scope based on global state. All code within the scope shares the same dependency instances. ```python with define_scope("", kind="shared"): # All code shares the same scope instances ... ``` -------------------------------- ### Use set_test_constant Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Set a constant value with an alias. The code creates a test API key constant. ```python from injection.testing import set_test_constant type APIKey = str test_api_key = set_test_constant("test_key_123", APIKey, alias=True) ``` -------------------------------- ### Scoped dependency with @scoped Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a class as a scoped dependency, creating a single instance per scope. Using a StrEnum for scope names is recommended. ```python from injection import scoped @scoped("") class Dependency: ... ``` -------------------------------- ### Transient dependency with @injectable Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a class as a transient dependency, creating a new instance each time it is resolved. ```python from injection import injectable @injectable class Dependency: ... ``` -------------------------------- ### Use load_test_profile as context manager Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md When used as a context manager, load_test_profile automatically unloads the test profile after the block exits, and caches are cleared. ```python from injection.testing import load_test_profile with load_test_profile(): # Test dependencies are active here run_test() # Test profile is unloaded, cache is cleared ``` -------------------------------- ### PythonModuleLoader with custom predicate Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/imports.md Imports only modules that match a custom predicate function. The predicate receives the full module name and returns True to import. Accepts module objects or strings. ```python from injection.loaders import PythonModuleLoader from src import adapters, services def predicate(module_name: str) -> bool: # Only import modules containing "impl" in their name return "impl" in module_name PythonModuleLoader(predicate).load(adapters, services) ``` -------------------------------- ### Factory function with @injectable Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a factory function as a dependency. Requires a return type annotation. ```python from injection import injectable class Dependency: ... @injectable def _dependency_factory() -> Dependency: # ... return Dependency() ``` -------------------------------- ### Define a contextual scope with kind="contextual" Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/scopes.md Explicitly creates a contextual scope, which is the default kind. Contextual scopes are based on `ContextVar`, so each concurrent context (like async tasks) maintains its own isolated scope. ```python with define_scope("", kind="contextual"): # Each async task will have its own isolated scope ... ``` -------------------------------- ### Use test_injectable decorator Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Register a mock class as the test injectable for an abstract dependency. ```python from injection.testing import test_injectable @test_injectable(on=AbstractDependency) class MockDependency(AbstractDependency): ... ``` -------------------------------- ### Inject dependencies with @inject Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use the @inject decorator to automatically resolve function parameters based on type annotations. The first call is slower due to dependency resolution, but subsequent calls are cached. Applying @inject to an async function allows resolving dependencies that require an async context; if an async dependency is required by a sync function, a RuntimeError is raised. ```python from injection import inject @inject def function(dependency: Dependency): ... function() # You can now call `function` without arguments ``` -------------------------------- ### Fix mypy error with NotImplemented default Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Provide a default value of NotImplemented for injected parameters to satisfy static type checkers. Using NotImplemented is recommended because it acts as a sentinel: if the function is called without injection, any attempt to use the dependency will produce a clear error. ```python @inject def function(dependency: Dependency = NotImplemented): ... function() # ✅ OK ``` -------------------------------- ### Set PYTHON_INJECTION_THREADSAFE environment variable in Python Source: https://github.com/100nm/python-injection/blob/prod/docs/threadsafety.md Set the `PYTHON_INJECTION_THREADSAFE` environment variable in Python to enable global thread safety. Ensure this is done before importing `injection`, as the variable is resolved at module import time. ```python import os os.environ["PYTHON_INJECTION_THREADSAFE"] = "1" ``` -------------------------------- ### Use test_scoped decorator Source: https://github.com/100nm/python-injection/blob/prod/docs/testing/test-dependencies.md Register a mock class as a test scoped dependency for an abstract dependency in a given scope. ```python from injection.testing import test_scoped @test_scoped("", on=AbstractDependency) class MockDependency(AbstractDependency): ... ``` -------------------------------- ### Register constant for primitive type with type alias Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a constant for a primitive type using a type alias and the alias=True parameter in set_constant. ```python from injection import set_constant type APIKey = str api_key = set_constant("", APIKey, alias=True) ``` -------------------------------- ### Inject a dependency into a FastAPI endpoint Source: https://github.com/100nm/python-injection/blob/prod/docs/integrations/fastapi.md Injects a dependency instance into a FastAPI endpoint using the Inject type from injection.ext.fastapi. The endpoint parameter is annotated with Inject[Dependency] to receive the dependency. ```python from injection.ext.fastapi import Inject @app.get("/") async def endpoint(dependency: Inject[Dependency]): ... ``` -------------------------------- ### Use @asfunction with NamedTuple Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/resolve-dependencies.md Use @asfunction to separate injected dependencies (class attributes) from runtime parameters (defined in __call__). This is useful when frameworks strictly validate function signatures and reject unknown parameters. Using NamedTuple is recommended for concise syntax and built-in immutability. ```python from injection import asfunction from typing import NamedTuple @asfunction class Function(NamedTuple): dependency: Dependency def __call__(self, foo: str, bar: str, baz: str): # Use self.dependency here ... # Call with only the runtime parameters Function("foo", "bar", "baz") ``` -------------------------------- ### Set PYTHON_INJECTION_THREADSAFE environment variable in shell Source: https://github.com/100nm/python-injection/blob/prod/docs/threadsafety.md Set the `PYTHON_INJECTION_THREADSAFE` environment variable in a shell to make all dependency resolution and scope operations thread-safe by default. This is useful for applications that require global thread safety. ```bash export PYTHON_INJECTION_THREADSAFE=1 ``` -------------------------------- ### Lazy constant with @constant Source: https://github.com/100nm/python-injection/blob/prod/docs/guides/register-dependencies.md Registers a lazy constant using the @constant decorator. ```python from injection import constant @constant class LazySettings: ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.