### Installing Injector with Pip (Shell) Source: https://github.com/python-injector/injector/blob/master/docs/index.rst This command shows how to install the Injector library using the pip package manager. It fetches the latest stable version from PyPI. ```Shell pip install injector ``` -------------------------------- ### Importing Injector Components for Full Example - Python Source: https://github.com/python-injector/injector/blob/master/README.md Imports core classes and decorators from the `injector` library required for demonstrating modules, providers, singletons, injection, and the main `Injector` class in a more complete scenario. ```Python >>> from injector import Module, provider, Injector, inject, singleton ``` -------------------------------- ### Installing Injector with pip - Bash Source: https://github.com/python-injector/injector/blob/master/README.md Provides the command-line instruction to install the `injector` library using the pip package installer for Python. ```Bash pip install injector ``` -------------------------------- ### Initializing Injector and Getting RequestHandler - Python Source: https://github.com/python-injector/injector/blob/master/README.md Initializes the `Injector` by providing a list of modules (`configure_for_testing` function and `DatabaseModule` instance). It then uses `injector.get(RequestHandler)` to obtain a `RequestHandler` instance, demonstrating how Injector resolves the entire dependency graph (RequestHandler -> sqlite3.Connection -> Configuration). ```Python >>> injector = Injector([configure_for_testing, DatabaseModule()]) >>> handler = injector.get(RequestHandler) >>> tuple(map(str, handler.get()[0])) # py3/py2 compatibility hack ('hello', 'world') ``` -------------------------------- ### Incorrect Injector Usage Example (Python) Source: https://github.com/python-injector/injector/blob/master/docs/index.rst This Python snippet demonstrates incorrect usage by attempting to instantiate a class with injected dependencies directly. Injector requires using methods like Injector.get or Injector.create_object to manage instantiation, as there is no global injector instance. ```Python # This will NOT work: class MyClass: @inject def __init__(self, t: SomeType): # ... MyClass() ``` -------------------------------- ### Importing SQLite Library - Python Source: https://github.com/python-injector/injector/blob/master/README.md Imports the standard Python `sqlite3` library, which is used in the full example to demonstrate injecting a database connection. ```Python >>> import sqlite3 ``` -------------------------------- ### Getting Instance Directly from Injector Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Demonstrates how to retrieve a bound instance of a specific type directly from the configured Injector using the get method. Injector resolves the type based on its bindings and provides the corresponding instance. ```python # Assuming injector, Name, and Description are defined and configured injector.get(Name) ``` ```python # Assuming injector, Name, and Description are defined and configured injector.get(Description) ``` -------------------------------- ### Assisted Injection Example Base Classes Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Defines simple classes (`Database`, `User`, `UserUpdater`) used to illustrate assisted injection. `UserUpdater` is designed with a mix of an injectable dependency (`db`) and a parameter (`user`) intended for manual provision at construction time. ```python class Database: pass class User: def __init__(self, name): self.name = name class UserUpdater: def __init__(self, db: Database, user): pass ``` -------------------------------- ### Preferring Direct Dependency Injection over Injector.get Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Shows the recommended practice of injecting dependencies directly into a class's constructor rather than injecting the Injector instance and calling `get()`. This pattern clearly expresses dependencies and facilitates unit testing. ```python class A: pass class B: pass class C: @inject def __init__(self, a: A, b: B): self.a = a self.b = b ``` -------------------------------- ### Getting Transitive Instance from Injector Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Shows how to get an instance of a class (`User`) that has dependencies defined in its constructor via @inject. The injector automatically resolves and injects these dependencies recursively before returning the requested instance. ```python # Assuming injector and User class are defined and configured user = injector.get(User) isinstance(user, User) user.name user.description ``` -------------------------------- ### Installing Custom Injector Scope in Module (Python) Source: https://github.com/python-injector/injector/blob/master/docs/scopes.rst Shows the necessary step to make a custom scope available within an injector. This is done by installing the custom scope class in a `Module`'s `configure` method using `binder.install(CustomScope)`. ```python class MyModule(Module): def configure(self, binder): binder.install(CustomScope) ``` -------------------------------- ### Testing value binding with Injector in Python unittest Source: https://github.com/python-injector/injector/blob/master/docs/testing.rst This snippet shows how to use `injector` within a `unittest.TestCase`. It defines a module to bind a string value, initializes the injector in the `setUp` method, and retrieves the bound value in a test method using `injector.get()` to assert its correctness. ```Python import unittest from injector import Injector, Module class UsernameModule(Module): def configure(self, binder): binder.bind(str, 'Maria') class TestSomethingClass(unittest.TestCase): def setUp(self): self.__injector = Injector(UsernameModule()) def test_username(self): username = self.__injector.get(str) self.assertEqual(username, 'Maria') ``` -------------------------------- ### Implementing Custom Injector Scope (Python) Source: https://github.com/python-injector/injector/blob/master/docs/scopes.rst Shows how to define a custom dependency injection scope by subclassing the `injector.Scope` abstract base class and implementing its required `get` method. This method is responsible for returning an instance for the given key and provider. ```python from injector import Scope class CustomScope(Scope): def get(self, key, provider): return provider ``` -------------------------------- ### Constructor Injection with Dataclasses and Injector - Python Source: https://github.com/python-injector/injector/blob/master/README.md Extends the basic example to show compatibility with Python `dataclasses`. The `@inject` decorator is applied to a `dataclass` whose fields represent dependencies, allowing the `Injector` to automatically inject them. ```Python 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 ``` -------------------------------- ### Defining RequestHandler with Injected DB Connection - Python Source: https://github.com/python-injector/injector/blob/master/README.md Defines a `RequestHandler` class that requires a `sqlite3.Connection` injected into its constructor using `@inject`. It includes a method `get` to query data using the injected connection. ```Python >>> 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() ``` -------------------------------- ### Using AssistedBuilder with Keys and Bindings Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Illustrates using `AssistedBuilder` (instead of `ClassAssistedBuilder`) with a binding Key. This demonstrates that the builder respects the configured binding (mapping DB Key to DBImplementation) when creating the instance, mixing injected dependencies with provided parameters like 'uri'. ```python from injector import Key, Injector, AssistedBuilder DB = Key('DB') class DBImplementation: def __init__(self, uri): pass def configure(binder): binder.bind(DB, to=DBImplementation) injector = Injector(configure) builder = injector.get(AssistedBuilder[DB]) instance = builder.build(uri='x') isinstance(instance, DBImplementation) ``` -------------------------------- ### Creating Injector with Module Instances Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Shows how to instantiate the Injector class by passing a list of module instances. This configures the injector's bindings based on the provided module configurations. ```python from injector import Injector, Module # Assuming UserModule and UserAttributeModule are defined elsewhere class UserModule(Module): pass # Placeholder for example context class UserAttributeModule(Module): pass # Placeholder for example context injector = Injector([UserModule(), UserAttributeModule()]) ``` -------------------------------- ### Creating Injector with Module Classes Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Shows how to instantiate the Injector class by passing a list of module classes. The injector automatically instantiates the modules and uses their configurations to set up bindings. ```python from injector import Injector, Module # Assuming UserModule and UserAttributeModule are defined elsewhere class UserModule(Module): pass # Placeholder for example context class UserAttributeModule(Module): pass # Placeholder for example context injector = Injector([UserModule, UserAttributeModule]) ``` -------------------------------- ### Creating Dictionary Bindings Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Demonstrates how bindings can be represented as a Python dictionary mapping keys (type/name tuples) to InstanceProvider instances, providing simple constant values. This illustrates the underlying binding structure Injector uses internally. ```python from injector import InstanceProvider bindings = { (Name, None): InstanceProvider('Sherlock'), (Description, None): InstanceProvider('A man of astounding insight'), } ``` -------------------------------- ### Using ClassAssistedBuilder for Instances Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Demonstrates using Injector.get with `ClassAssistedBuilder` to obtain a builder for a specific class (`UserUpdater`). The builder's `build` method is then used to create an instance by automatically resolving injectable dependencies and accepting manually provided parameters. ```python from injector import Injector, ClassAssistedBuilder, Module # Assuming Database, User, UserUpdater are defined # A minimal module is needed for Injector context class BasicModule(Module): def configure(self, binder): binder.bind(Database) injector = Injector([BasicModule]) builder = injector.get(ClassAssistedBuilder[UserUpdater]) user = User('John') user_updater = builder.build(user=user) ``` -------------------------------- ### Defining Configuration Class - Python Source: https://github.com/python-injector/injector/blob/master/README.md Defines a simple `Configuration` class to hold database connection string settings, demonstrating how application configuration can be represented and potentially injected. ```Python >>> class Configuration: ... def __init__(self, connection_string): ... self.connection_string = connection_string ``` -------------------------------- ### Verifying Singleton Scopes - Python Source: https://github.com/python-injector/injector/blob/master/README.md Demonstrates that types bound or provided with the `singleton` scope (as done for `Configuration` and `sqlite3.Connection` in the modules) result in the same instance being returned on subsequent `injector.get` calls. ```Python >>> injector.get(Configuration) is injector.get(Configuration) True >>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection) True ``` -------------------------------- ### Binding Configuration with Module - Python Source: https://github.com/python-injector/injector/blob/master/README.md Defines a function `configure_for_testing` which acts as an Injector module. It creates a `Configuration` instance for an in-memory database and binds it to the `Configuration` type with a `singleton` scope using the provided `binder`. ```Python >>> def configure_for_testing(binder): ... configuration = Configuration(':memory:') ... binder.bind(Configuration, to=configuration, scope=singleton) ``` -------------------------------- ### Configuring Module Bindings Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Shows how to define bindings within a Module subclass by implementing the configure method and using binder.bind. This is the standard declarative way to map types or keys to specific values, instances, or providers. ```python from injector import Module class MyModule(Module): def configure(self, binder): binder.bind(Name, to='Sherlock') binder.bind(Description, to='A man of astounding insight') ``` -------------------------------- ### Demonstrating TypeError with Manual Instantiation in Injector (Python) Source: https://github.com/python-injector/injector/blob/master/docs/faq.rst This Python code snippet demonstrates how manually creating an instance of a class (`X`) with an `@inject` decorated `__init__` method results in a `TypeError`. This occurs because `@inject` relies on the `Injector` instance to resolve dependencies, which is bypassed during manual instantiation. It requires the `injector` library. ```python class X: @inject def __init__(self, s: str): self.s = s def configure(binder): binder.bind(s, to='some string') injector = Injector(configure) x = X() ``` -------------------------------- ### Handling Module Dependency Order in Injector Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Shows how injecting dependencies into Injector modules' constructors or `configure` methods can make the injection process fragile and dependent on the order modules are passed to the Injector. It illustrates scenarios leading to errors when dependencies are not bound before a module that requires them is processed. ```python A = Key('A') B = Key('B') class ModuleA(Module): @inject(a=A) def configure(self, binder, a): pass class ModuleB(Module): @inject(b=B) def __init__(self, b): pass class ModuleC(Module): def configure(self, binder): binder.bind(A, to='a') binder.bind(B, to='b') ``` ```python # error, at the time of ModuleA processing A is unbound Injector([ModuleA, ModuleC]) ``` ```python # error, at the time of ModuleB processing B is unbound Injector([ModuleB, ModuleC]) ``` ```python # no error this time Injector([ModuleC, ModuleA, ModuleB]) ``` -------------------------------- ### Implementing Module Provider Method Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Illustrates using the @provider decorator within a Module to define a method that dynamically creates and provides an instance for a specific type. This allows for more complex or dynamic instance creation logic within the module configuration. ```python from injector import provider, Module import time class MyModule(Module): def configure(self, binder): binder.bind(Name, to='Sherlock') @provider def describe(self) -> Description: return 'A man of astounding insight (at %s)' % time.time() ``` -------------------------------- ### Avoiding Injecting Injector and Using Injector.get Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Illustrates the anti-pattern of injecting the Injector instance itself into a class and then using `injector.get()` within that class to resolve other dependencies. This obscures dependencies, makes testing harder, and defeats the purpose of explicit dependency injection. ```python class A: pass class B: pass class C: @inject def __init__(self, injector: Injector): self.a = injector.get(A) self.b = injector.get(B) ``` -------------------------------- ### Providing SQLite Connection with Module - Python Source: https://github.com/python-injector/injector/blob/master/README.md Defines a `DatabaseModule` class inheriting from `injector.Module`. It uses the `@provider` decorator on `provide_sqlite_connection` to indicate it provides a `sqlite3.Connection`. This provider method itself requires a `Configuration` instance (which will be injected) and is scoped as a `@singleton`. ```Python >>> 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 ``` -------------------------------- ### Using Injector for Managed Dependency Composition Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Presents the correct approach where a class's dependencies are injected into its constructor, and the Injector framework handles the composition of dependent objects. This keeps the consumer class focused on its logic rather than dependency assembly. ```python class A: pass class B: @inject def __init__(self, a: A): self.a = a class C: @inject def __init__(self, b: B): self.b = b ``` -------------------------------- ### Basic Constructor Injection with Injector - Python Source: https://github.com/python-injector/injector/blob/master/README.md Demonstrates fundamental dependency injection using `injector`. The `Outer` class depends on `Inner` and uses the `@inject` decorator. An `Injector` instance resolves and provides the `Inner` dependency when `Outer` is retrieved. ```Python >>> 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 ``` -------------------------------- ### Implementing Basic Injection Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Demonstrates dependency injection using the @inject decorator on a class constructor and within a module's @provider method. Injector automatically resolves dependencies specified in method signatures or inject arguments using the configured bindings. ```python from typing import NewType from injector import Binder, Module, inject, provider Name = NewType("Name", str) Description = NewType("Description", str) class User: @inject def __init__(self, name: Name, description: Description): self.name = name self.description = description class UserModule(Module): def configure(self, binder: Binder): binder.bind(User) class UserAttributeModule(Module): def configure(self, binder: Binder): binder.bind(Name, to='Sherlock') @provider def describe(self, name: Name) -> Description: return '%s is a man of astounding insight' % name ``` -------------------------------- ### Setting Injector Logger Level to DEBUG in Python Source: https://github.com/python-injector/injector/blob/master/docs/logging.rst This code snippet demonstrates how to configure the 'injector' logger using Python's standard 'logging' module. It sets the logger level to DEBUG, which enables tracing and other useful information within the injector library. ```python import logging logging.getLogger('injector').setLevel(logging.DEBUG) ``` -------------------------------- ### Implementing Method Injection (Deprecated in Injector) Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Illustrates injecting dependencies into a regular method rather than the constructor. This practice is generally discouraged as it hides dependencies and is no longer supported by default in Injector 0.11+. ```python class Service2(object): def __init__(self): # some other code # tens or hundreds lines of code @inject(http_client=HTTP) def method(self, http_client): # do something pass ``` -------------------------------- ### Creating Child Injector with Binding Override Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Demonstrates creating a child injector from a parent injector. The child inherits all parent bindings but can define its own bindings that override those in the parent, without affecting the parent injector's configuration. ```python from injector import Injector def configure_parent(binder): binder.bind(str, to='asd') binder.bind(int, to=42) def configure_child(binder): binder.bind(str, to='qwe') parent = Injector(configure_parent) child = parent.create_child_injector(configure_child) parent_str, parent_int = parent.get(str), parent.get(int) child_str, child_int = child.get(str), child.get(int) ``` -------------------------------- ### Declaring Singleton Scopes in Injector (Python) Source: https://github.com/python-injector/injector/blob/master/docs/scopes.rst Demonstrates three methods for declaring a class or provider to be in the Singleton scope within the injector library: using the `@singleton` class decorator, explicitly binding with `binder.bind(scope=singleton)`, and using the `@singleton` decorator on a `@provider` method. ```python @singleton class Thing: pass class ThingModule(Module): def configure(self, binder): binder.bind(Thing, scope=singleton) @singleton @provider def provide_thing(self) -> Thing: return Thing() ``` -------------------------------- ### Implementing Constructor Injection in Injector Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Demonstrates the preferred method of dependency injection in Injector (v0.11+): injecting dependencies directly into a class's constructor using the `@inject` decorator. This approach makes dependencies explicit and simplifies testing. ```python class Service1(object): @inject(http_client=HTTP) def __init__(self, http_client): self.http_client = http_client # some other code # tens or hundreds lines of code def method(self): # do something pass ``` -------------------------------- ### Retrieving Custom Injector Scope Instance (Python) Source: https://github.com/python-injector/injector/blob/master/docs/scopes.rst Demonstrates how to retrieve an instance of a custom scope from the injector. It also verifies that multiple calls to `injector.get(CustomScope)` within the same injector instance return the identical scope object, confirming that scope instances themselves are singletons. ```python >>> injector = Injector([MyModule()]) >>> injector.get(CustomScope) is injector.get(CustomScope) True ``` -------------------------------- ### Injecting ClassAssistedBuilder Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Shows how `ClassAssistedBuilder` itself can be injected into another class (`NeedsUserUpdater`) or provider method. This pattern allows the consuming class to delegate the responsibility of building instances of the target type (`UserUpdater`) to the injected builder. ```python from injector import inject, ClassAssistedBuilder # Assuming UserUpdater is defined class NeedsUserUpdater: @inject def __init__(self, builder: ClassAssistedBuilder[UserUpdater]): self.updater_builder = builder def method(self): updater = self.updater_builder.build(user=None) ``` -------------------------------- ### Creating Injector Scope Decorator (Python) Source: https://github.com/python-injector/injector/blob/master/docs/scopes.rst Illustrates how to create a `ScopeDecorator` instance linked to a custom scope class. This decorator instance can then be used to easily annotate classes, associating them with the custom scope. ```python from injector import ScopeDecorator customscope = ScopeDecorator(CustomScope) ``` -------------------------------- ### Avoiding Manual Dependency Composition in Injector Consumers Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Highlights the anti-pattern where a class receives a dependency via injection but then manually instantiates another class using the injected dependency. This shifts the composition responsibility back to the consumer, undermining the dependency injection container's role. ```python class A: pass class B: def __init__(self, a): self.a = a class C: @inject def __init__(self, a: A): self.b = B(a) ``` -------------------------------- ### Avoiding Blocking Operations in Injector Providers Python Source: https://github.com/python-injector/injector/blob/master/docs/practices.rst Demonstrates the danger of performing blocking operations (like infinite loops or IO without timeouts) inside module providers. Since Injector uses a lock for thread safety during injection, blocking code in a provider can halt dependency resolution for all threads, potentially causing deadlocks. ```python from threading import Thread from time import sleep from injector import inject, Injector, Module, provider class A: pass class SubA(A): pass class B: pass class BadModule(Module): @provider def provide_a(self, suba: SubA) -> A: return suba @provider def provide_suba(self) -> SubA: print('Providing SubA...') while True: print('Sleeping...') sleep(1) # This never executes return SubA() @provider def provide_b(self) -> B: return B() injector = Injector([BadModule]) thread = Thread(target=lambda: injector.get(A)) # to make sure the thread doesn't keep the application alive thread.daemon = True thread.start() # This will never finish injector.get(B) print('Got B') ``` -------------------------------- ### Applying Custom Injector Scope Decorator (Python) Source: https://github.com/python-injector/injector/blob/master/docs/scopes.rst Demonstrates how to use the `ScopeDecorator` instance created for a custom scope as a class decorator. Applying this decorator to a class marks that class as being bound to the specified custom scope when injected. ```python @customscope class MyClass: pass ``` -------------------------------- ### Child Injector Singleton Scope Override Behavior Python Source: https://github.com/python-injector/injector/blob/master/docs/terminology.rst Highlights a specific behavior observed when overriding a parent's singleton-scoped binding in a child injector. Retrieving the instance from the child works as expected, but retrieving from the parent might return the child's overridden singleton instance, a behavior noted as potentially unexpected. ```python from injector import Injector, singleton, Module def configure_parent(binder): binder.bind(str, to='asd', scope=singleton) def configure_child(binder): binder.bind(str, to='qwe', scope=singleton) parent = Injector(configure_parent) child = parent.create_child_injector(configure_child) child_str = child.get(str) # this behaves as expected parent_str = parent.get(str) # wat ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.