Implementation of dependency injection for Python 3
Overall
score
92%
Service activation and dependency resolution through the Services provider. The Services class provides efficient service lookup and instantiation with support for scoped resolution and method execution with dependency injection.
Creates a new Services provider instance for service resolution.
def __init__(self, services_map=None, scope_cls: Optional[Type[ActivationScope]] = None):
"""
Initialize a Services provider.
Args:
services_map: Internal service mapping (typically built by Container)
scope_cls: Custom ActivationScope class for scoped services
"""Primary method for resolving services from the provider with optional scoping and default values.
def get(self, desired_type: Union[Type[T], str], scope: Optional[ActivationScope] = None, *, default: Optional[Any] = ...) -> T:
"""
Get an instance of the specified service type.
Args:
desired_type: Type or name of service to resolve
scope: Optional activation scope for scoped services
default: Default value if service cannot be resolved (raises exception if not provided)
Returns:
Instance of the requested service type
Raises:
CannotResolveTypeException: If service cannot be resolved and no default provided
"""Usage examples:
# Build services from container
services = container.build_provider()
# Resolve a service
user_service = services.get(UserService)
# Resolve with scope
with services.create_scope() as scope:
scoped_service = services.get(ScopedService, scope)
# Resolve with default value
optional_service = services.get(OptionalService, default=None)Manually set a service instance in the provider.
def set(self, new_type: Union[Type, str], value: Any):
"""
Manually set a service instance in the provider.
Args:
new_type: Type or name to associate with the value
value: Service instance to set
"""Creates a new activation scope for managing scoped service lifetimes.
def create_scope(self, scoped: Optional[Dict[Union[Type, str], Any]] = None) -> ActivationScope:
"""
Create a new activation scope for scoped services.
Args:
scoped: Optional dictionary of pre-scoped services
Returns:
New ActivationScope instance
"""Creates an optimized executor function for methods with dependency injection.
def get_executor(self, method: Callable) -> Callable:
"""
Create an optimized executor for a method with dependency injection.
Args:
method: Method to create executor for
Returns:
Optimized callable that automatically injects dependencies
"""Usage example:
def business_method(user_service: UserService, logger: Logger):
# Method implementation
pass
# Create executor
executor = services.get_executor(business_method)
# Execute with automatic dependency injection
result = executor()Execute a method with automatic dependency injection, optionally within a specific scope.
def exec(self, method: Callable, scoped: Optional[Dict[Type, Any]] = None) -> Any:
"""
Execute a method with automatic dependency injection.
Args:
method: Method to execute
scoped: Optional dictionary of scoped services for this execution
Returns:
Return value of the executed method
"""Usage examples:
def handle_request(user_service: UserService, request_id: str):
return user_service.process_request(request_id)
# Execute with dependency injection
result = services.exec(handle_request, {"request_id": "12345"})
# Execute with scoped services
scoped_services = {RequestContext: RequestContext("current_request")}
result = services.exec(handle_request, scoped=scoped_services)Services class provides dictionary-like access methods for interoperability.
def __contains__(self, item):
"""Check if a service type is registered."""
def __getitem__(self, item):
"""Get a service instance using bracket notation."""
def __setitem__(self, key, value):
"""Set a service instance using bracket notation."""Usage examples:
# Check if service is registered
if UserService in services:
user_service = services[UserService]
# Set service using bracket notation
services[Logger] = ConsoleLogger()
# Get service using bracket notation
logger = services[Logger]Install with Tessl CLI
npx tessl i tessl/pypi-rodidocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10