Implementation of dependency injection for Python 3
Overall
score
92%
Scoped service management through ActivationScope context managers. Enables per-request or per-operation service scoping with automatic cleanup and support for nested scopes.
Creates a new activation scope for managing scoped service lifetimes within a specific context.
def __init__(self, provider: Optional[Services] = None, scoped_services: Optional[Dict[Union[Type[T], str], T]] = None):
"""
Initialize an ActivationScope.
Args:
provider: Services provider for service resolution
scoped_services: Optional dictionary of pre-scoped service instances
"""Resolves services within the current scope, creating scoped instances as needed and reusing them within the scope lifetime.
def get(self, desired_type: Union[Type[T], str], scope: Optional[ActivationScope] = None, *, default: Optional[Any] = ...) -> T:
"""
Get a service instance within this scope.
Args:
desired_type: Type or name of service to resolve
scope: Optional nested scope (defaults to current scope)
default: Default value if service cannot be resolved
Returns:
Service instance (scoped or singleton as appropriate)
Raises:
CannotResolveTypeException: If service cannot be resolved and no default provided
"""Manually dispose of the scope and clean up scoped service instances.
def dispose(self):
"""
Dispose of the scope and clean up scoped services.
Calls dispose() on any scoped services that implement it.
"""ActivationScope implements context manager protocol for automatic resource cleanup.
def __enter__(self):
"""
Enter the scope context.
Returns:
The ActivationScope instance
"""
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Exit the scope context and automatically dispose resources.
Args:
exc_type: Exception type (if any)
exc_val: Exception value (if any)
exc_tb: Exception traceback (if any)
"""Usage examples:
# Manual scope management
scope = services.create_scope()
try:
scoped_service = scope.get(ScopedService)
# Use scoped service
finally:
scope.dispose()
# Automatic scope management with context manager
with services.create_scope() as scope:
scoped_service = scope.get(ScopedService)
database_service = scope.get(DatabaseService)
# Services automatically disposed when exiting contextExperimental class for advanced nested scope scenarios with tracking capabilities.
class TrackingActivationScope(ActivationScope):
def __init__(self, provider=None, scoped_services=None):
"""
Initialize a TrackingActivationScope for nested scope support.
Args:
provider: Services provider for service resolution
scoped_services: Optional dictionary of pre-scoped services
"""Common pattern for web applications where services are scoped per HTTP request:
# In web framework integration
def handle_request(request):
with services.create_scope() as scope:
# Register request-specific services
request_context = RequestContext(request)
scope.set(RequestContext, request_context)
# Resolve and execute handler
handler = scope.get(RequestHandler)
return handler.process(request)Pattern for database transactions where services are scoped per transaction:
def process_business_operation():
with services.create_scope() as scope:
# Scoped database connection
db_service = scope.get(DatabaseService)
try:
# Business logic using scoped services
user_service = scope.get(UserService)
result = user_service.create_user(user_data)
db_service.commit()
return result
except Exception:
db_service.rollback()
raiseAdvanced pattern using nested scopes for complex service hierarchies:
# Parent scope
with services.create_scope() as parent_scope:
parent_service = parent_scope.get(ParentService)
# Child scope inheriting from parent
with parent_scope.create_scope() as child_scope:
child_service = child_scope.get(ChildService)
# Child scope can access parent scoped services
same_parent = child_scope.get(ParentService) # Same instance as parent_serviceInstall 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