Registry / web-framework / inject

inject

JSON →
library5.5.0pypypi✓ verified 22d ago

Inject is a lightweight, fast, and thread-safe Python dependency injection framework. It facilitates the creation and management of object dependencies, promoting modular and testable code. The library supports features like automatic parameter injection using type annotations and context managers. It maintains an active development status, with the current version being 5.3.0, and new releases are made periodically.

pip install inject
INSTALL
IMPORT
SIG · INJECT
I
inject
web-frameworkpythonv5.5.0
Install
1.5s avg
Import
49ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v5.5.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.050s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.5s · import 0.048s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

inject
import inject
autoparams
from inject import autoparams
import inject.autoparams
While `import inject` and then `inject.autoparams` works, direct import is cleaner if only `autoparams` is needed.
params
from inject import params
from inject import param
`inject.param` is deprecated; use `inject.params` for multiple or single parameter injection.
instance
from inject import instance

This quickstart demonstrates how to set up and use `inject` for dependency injection. It covers configuring bindings, requesting instances directly with `inject.instance()`, and automatically injecting parameters into functions using `@inject.autoparams` (with type hints) or explicitly with `@inject.params`.

import inject # 1. Define services/dependencies class Cache: def save(self, key, value): print(f"Saving to cache: {key} = {value}") class DbInterface: def query(self, statement): print(f"Executing DB query: {statement}") return [f"result_for_{statement}"] # 2. Configure bindings (once at application start) def config(binder): binder.bind(Cache, Cache()) binder.bind(DbInterface, DbInterface()) inject.configure(config) # 3. Use dependency injection # Method 1: Using inject.instance() cache_instance = inject.instance(Cache) cache_instance.save('app_init', 'initial_value') # Method 2: Using @inject.autoparams (requires type hints) @inject.autoparams def process_data(data: str, cache: Cache, db: DbInterface): cache.save('processed', data) results = db.query(f"SELECT * FROM data WHERE value = '{data}'") print(f"Processed '{data}', results: {results}") process_data('example_data') # Method 3: Using @inject.params (explicitly name dependencies) @inject.params(cache=Cache, db=DbInterface) def report_status(message: str, cache=None, db=None): if cache: cache.save('status', message) if db: db.query(f"INSERT INTO logs VALUES ('{message}')") print(f"Status reported: {message}") report_status('Application running successfully')
Debug
Known issues
breaking`inject` v5.0 and later require Python 3.9+. If you are using an older Python version (e.g., 3.5-3.8), you must use `inject` v4.x. For Python 2.7-3.5, use `inject` v3.x.
fix
Upgrade your Python environment to 3.9+ or pin `inject` to an appropriate older major version (e.g., `pip install 'inject<5'` for Python 3.5-3.8).
affects: 5.0.0+
deprecatedThe `inject.param` decorator is deprecated. Use `inject.params` instead for injecting parameters into functions.
fix
Replace `@inject.param('dependency_name', DependencyType)` with `@inject.params(dependency_name=DependencyType)`.
affects: 4.1+
gotchaBy default, `inject` attempts to implicitly instantiate a class if a binding is missing (`bind_in_runtime=True`). This can mask missing bindings and lead to hard-to-debug issues if the default constructor is called unintentionally. For stricter control, disable runtime binding.
fix
Call `inject.configure(config, bind_in_runtime=False)` to disable implicit runtime binding. This will cause `inject.instance()` or injection to raise an `InjectorException` immediately if a binding is not explicitly provided.
affects: All versions
gotcha`inject` creates objects as singletons by default. For advanced scope management (e.g., thread-local, request-local instances), you need to implement custom providers rather than relying on built-in scope management features found in some other DI frameworks.
fix
Define and bind custom provider functions (e.g., `binder.bind_to_provider(MyScopedDep, my_custom_scope_provider_func)`) for dependencies that require non-singleton lifetimes.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'inject'
The 'inject' library is not installed in the Python environment being used, or the Python interpreter cannot find it due to incorrect environment configuration (e.g., virtual environment not activated, or package installed in a different Python version).
fix
Ensure the 'inject' library is installed for your active Python environment using pip: `pip install inject`.
AttributeError: 'NoneType' object has no attribute 'some_method'
This error often occurs when a dependency expected to be injected by `inject` is not properly bound or resolved, leading to `None` being injected instead of the intended object. When a method is called on this `None` object, an `AttributeError` is raised.
fix
Verify that all dependencies are correctly bound in the `inject.configure` function using `binder.bind(DependencyType, to=DependencyImplementation)` or `binder.bind_to_provider` or `binder.bind_to_constructor`. Ensure that the types in your annotations match the registered bindings.
InjectorException: No binding for <class 'your_module.YourDependency'>
This error occurs when `inject.configure(bind_in_runtime=False)` has been set, disabling automatic (runtime) binding, and `inject` attempts to provide an instance for a class or interface that has not been explicitly bound using a `binder`.
fix
Explicitly bind the missing dependency in your `inject.configure` function, for example: `binder.bind(YourDependency, to=YourDependencyImplementation)`. Alternatively, if runtime binding is desired, remove `bind_in_runtime=False` from `inject.configure` (though this is generally not recommended for robust applications).
TypeError: 'type' object is not callable (when using @inject.autoparams on a class method)
The `@inject.autoparams` decorator is typically used for functions or `__init__` methods of classes to automatically inject dependencies based on type hints. Applying it directly to a regular class method might lead to unexpected behavior or `TypeError` if not used as intended by the library to resolve its own parameters.
fix
Use `@inject.autoparams` on the `__init__` method of a class for constructor injection. For other methods, consider injecting dependencies into the constructor and then using `self.dependency` within the method, or explicitly define the dependencies as arguments to the method if they are context-specific and then call `inject.instance()` or `inject.params()` if method injection is truly needed and supported for that specific case. The `inject` library generally favors constructor injection for class dependencies.
Upgrade
Version history
5.5.0latest on PyPI · released Jul 13, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Resources
inject — pip install inject · libregistry