Top Related Projects
A pythonic dependency injection library.
Dependency injection framework for Python
Python dependency injection framework, inspired by Guice
Quick Overview
Injector is a dependency injection framework for Python, inspired by Google's Guice. It provides a simple and intuitive way to manage dependencies in your Python applications, promoting loose coupling and easier testing. Injector supports Python 3.7+ and is designed to be lightweight and easy to use.
Pros
- Simplifies dependency management and promotes modular code design
- Supports both constructor and method injection
- Integrates well with existing Python codebases
- Provides a clear and intuitive API
Cons
- May introduce a learning curve for developers new to dependency injection
- Can add some overhead to application startup time
- Might be overkill for small projects or scripts
- Limited community support compared to some other Python libraries
Code Examples
- Basic usage with constructor injection:
from injector import inject, Injector
class Database:
def __init__(self, url: str):
self.url = url
class UserRepository:
@inject
def __init__(self, database: Database):
self.database = database
class UserService:
@inject
def __init__(self, user_repository: UserRepository):
self.user_repository = user_repository
def configure(binder):
binder.bind(Database, to=Database('sqlite:///example.db'))
injector = Injector(configure)
user_service = injector.get(UserService)
- Using modules for configuration:
from injector import Module, provider, singleton
class AppModule(Module):
@singleton
@provider
def provide_database(self) -> Database:
return Database('sqlite:///example.db')
@provider
def provide_user_repository(self, database: Database) -> UserRepository:
return UserRepository(database)
injector = Injector([AppModule()])
user_service = injector.get(UserService)
- Method injection:
from injector import inject
class EmailSender:
def send_email(self, to: str, subject: str, body: str):
pass
class UserNotifier:
@inject
def notify_user(self, user_id: str, email_sender: EmailSender):
email_sender.send_email(user_id, "Notification", "Hello, user!")
injector = Injector()
notifier = injector.get(UserNotifier)
notifier.notify_user("user123")
Getting Started
To get started with Injector, first install it using pip:
pip install injector
Then, define your classes and their dependencies:
from injector import inject, Injector
class Engine:
def start(self):
return "Engine started"
class Car:
@inject
def __init__(self, engine: Engine):
self.engine = engine
def start(self):
return f"Car starting... {self.engine.start()}"
injector = Injector()
car = injector.get(Car)
print(car.start()) # Output: Car starting... Engine started
This example demonstrates basic usage of Injector with constructor injection.
Competitor Comparisons
A pythonic dependency injection library.
Pros of Pinject
- Simpler API with fewer concepts to learn
- Supports automatic dependency injection without explicit bindings
- Integrates well with Google's coding style and practices
Cons of Pinject
- Less actively maintained (last update in 2018)
- Limited documentation and community support
- Lacks some advanced features found in Injector
Code Comparison
Pinject:
import pinject
class SomeClass:
@pinject.inject()
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
obj_graph = pinject.new_object_graph()
some_instance = obj_graph.provide(SomeClass)
Injector:
from injector import inject, Injector
class SomeClass:
@inject
def __init__(self, foo: Foo, bar: Bar):
self.foo = foo
self.bar = bar
injector = Injector()
some_instance = injector.get(SomeClass)
Both libraries aim to provide dependency injection for Python, but Injector offers more features and active development. Pinject's simplicity may be appealing for smaller projects or those following Google's coding practices. However, Injector's broader feature set and ongoing maintenance make it a more robust choice for complex applications and long-term projects.
Dependency injection framework for Python
Pros of python-dependency-injector
- More comprehensive and feature-rich, offering a wider range of dependency injection patterns
- Better performance, especially for large-scale applications
- Extensive documentation and examples, making it easier for newcomers to adopt
Cons of python-dependency-injector
- Steeper learning curve due to its more complex API and additional features
- Slightly more verbose syntax for basic use cases
- Larger library size, which may be overkill for simple projects
Code Comparison
python-injector:
from injector import inject, Injector
class Database:
pass
class DataAccessObject:
@inject
def __init__(self, db: Database):
self.db = db
injector = Injector()
dao = injector.get(DataAccessObject)
python-dependency-injector:
from dependency_injector import containers, providers
class Container(containers.DeclarativeContainer):
database = providers.Singleton(Database)
dao = providers.Factory(DataAccessObject, db=database)
container = Container()
dao = container.dao()
Both libraries provide dependency injection functionality, but python-dependency-injector offers more flexibility and control over the injection process. The syntax differs slightly, with python-dependency-injector using a container-based approach, while python-injector relies more on decorators and type hints.
Python dependency injection framework, inspired by Guice
Pros of injector
- More actively maintained with regular updates
- Larger community and better documentation
- Supports Python 3.7+ and has type hinting
Cons of injector
- Slightly more complex API compared to the alternative
- May have a steeper learning curve for beginners
Code Comparison
injector:
from injector import inject, Injector
class Database:
def __init__(self, url: str):
self.url = url
class UserRepository:
@inject
def __init__(self, database: Database):
self.database = database
def configure(binder):
binder.bind(Database, to=Database('localhost:5432'))
injector = Injector(configure)
user_repository = injector.get(UserRepository)
Note
The comparison you requested is not possible as there is only one repository named python-injector/injector. The repository you mentioned twice is the same project. Therefore, this response focuses on the features, pros, and cons of the injector library itself, rather than comparing it to another repository.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Injector - Python dependency injection framework, inspired by Guice
Introduction
While dependency injection is easy to do in Python due to its support for keyword arguments, the ease with which objects can be mocked and its dynamic nature, a framework for assisting in this process can remove a lot of boiler-plate from larger applications. That's where Injector can help. It automatically and transitively provides dependencies for you. As an added benefit, Injector encourages nicely compartmentalised code through the use of modules.
If you're not sure what dependency injection is or you'd like to learn more about it see:
- The Clean Code Talks - Don't Look For Things! (a talk by Miško Hevery)
- Inversion of Control Containers and the Dependency Injection pattern (an article by Martin Fowler)
The core values of Injector are:
-
Simplicity - while being inspired by Guice, Injector does not slavishly replicate its API. Providing a Pythonic API trumps faithfulness. Additionally some features are omitted because supporting them would be cumbersome and introduce a little bit too much "magic" (member injection, method injection).
Connected to this, Injector tries to be as nonintrusive as possible. For example while you may declare a class' constructor to expect some injectable parameters, the class' constructor remains a standard constructor â you may instantiate the class just the same manually, if you want.
-
No global state â you can have as many Injector instances as you like, each with a different configuration and each with different objects in different scopes. Code like this won't work for this very reason:
class MyClass: @inject def __init__(t: SomeType): # ... MyClass()
This is simply because there's no global
Injector
to use. You need to be explicit and use Injector.get, Injector.create_object or injectMyClass
into the place that needs it. -
Cooperation with static type checking infrastructure â the API provides as much static type safety as possible and only breaks it where there's no other option. For example the Injector.get method is typed such that
injector.get(SomeType)
is statically declared to return an instance ofSomeType
, therefore making it possible for tools such as mypy to type-check correctly the code using it. -
The client code only knows about dependency injection to the extent it needs âÂ
inject
,Inject
andNoInject
are simple markers that don't really do anything on their own and your code can run just fine without Injector orchestrating things.
How to get Injector?
-
GitHub (code repository, issues): https://github.com/alecthomas/injector
-
PyPI (installable, stable distributions): https://pypi.org/project/injector/. You can install it using pip:
pip install injector
-
Documentation: https://injector.readthedocs.org
-
Change log: https://injector.readthedocs.io/en/latest/changelog.html
Injector works with CPython 3.8+ and PyPy 3 implementing Python 3.8+.
A Quick Example
>>> from injector import Injector, inject
>>> class Inner:
... def __init__(self):
... self.forty_two = 42
...
>>> class Outer:
... @inject
... def __init__(self, inner: Inner):
... self.inner = inner
...
>>> injector = Injector()
>>> outer = injector.get(Outer)
>>> outer.inner.forty_two
42
Or with dataclasses
if you like:
from dataclasses import dataclass
from injector import Injector, inject
class Inner:
def __init__(self):
self.forty_two = 42
@inject
@dataclass
class Outer:
inner: Inner
injector = Injector()
outer = injector.get(Outer)
print(outer.inner.forty_two) # Prints 42
A Full Example
Here's a full example to give you a taste of how Injector works:
>>> from injector import Module, provider, Injector, inject, singleton
We'll use an in-memory SQLite database for our example:
>>> import sqlite3
And make up an imaginary RequestHandler
class that uses the SQLite connection:
>>> class RequestHandler:
... @inject
... def __init__(self, db: sqlite3.Connection):
... self._db = db
...
... def get(self):
... cursor = self._db.cursor()
... cursor.execute('SELECT key, value FROM data ORDER by key')
... return cursor.fetchall()
Next, for the sake of the example, we'll create a configuration type:
>>> class Configuration:
... def __init__(self, connection_string):
... self.connection_string = connection_string
Next, we bind the configuration to the injector, using a module:
>>> def configure_for_testing(binder):
... configuration = Configuration(':memory:')
... binder.bind(Configuration, to=configuration, scope=singleton)
Next we create a module that initialises the DB. It depends on the configuration provided by the above module to create a new DB connection, then populates it with some dummy data, and provides a Connection
object:
>>> class DatabaseModule(Module):
... @singleton
... @provider
... def provide_sqlite_connection(self, configuration: Configuration) -> sqlite3.Connection:
... conn = sqlite3.connect(configuration.connection_string)
... cursor = conn.cursor()
... cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)')
... cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")')
... return conn
(Note how we have decoupled configuration from our database initialisation code.)
Finally, we initialise an Injector
and use it to instantiate a RequestHandler
instance. This first transitively constructs a sqlite3.Connection
object, and the Configuration dictionary that it in turn requires, then instantiates our RequestHandler
:
>>> injector = Injector([configure_for_testing, DatabaseModule()])
>>> handler = injector.get(RequestHandler)
>>> tuple(map(str, handler.get()[0])) # py3/py2 compatibility hack
('hello', 'world')
We can also verify that our Configuration
and SQLite
connections are indeed singletons within the Injector:
>>> injector.get(Configuration) is injector.get(Configuration)
True
>>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection)
True
You're probably thinking something like: "this is a large amount of work just to give me a database connection", and you are correct; dependency injection is typically not that useful for smaller projects. It comes into its own on large projects where the up-front effort pays for itself in two ways:
- Forces decoupling. In our example, this is illustrated by decoupling our configuration and database configuration.
- After a type is configured, it can be injected anywhere with no additional effort. Simply
@inject
and it appears. We don't really illustrate that here, but you can imagine adding an arbitrary number ofRequestHandler
subclasses, all of which will automatically have a DB connection provided.
Footnote
This framework is similar to snake-guice, but aims for simplification.
© Copyright 2010-2013 to Alec Thomas, under the BSD license
Top Related Projects
A pythonic dependency injection library.
Dependency injection framework for Python
Python dependency injection framework, inspired by Guice
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot