Skip to content

17 contracts

Zuko edited this page Jan 21, 2026 · 1 revision

Contracts - Interfaces

Interface definitions cho core components

DisposableInterface

Interface cho resources cần cleanup:

from core.contracts import DisposableInterface

class MyResource(DisposableInterface):
    def cleanup(self):
        """Called by ServiceLocator.releaseScope()"""
        # Cleanup logic
        self._releaseResources()
        self._closeConnections()

Usage

With ServiceLocator

from core import QtAppContext
from core.contracts import DisposableInterface

class DatabaseConnection(DisposableInterface):
    def __init__(self):
        self.connection = self._connect()
    
    def cleanup(self):
        if self.connection:
            self.connection.close()
            self.connection = None

# Register as scoped service
ctx = QtAppContext.globalInstance()
taskId = self.uuid

db = DatabaseConnection()
ctx.registerScopedService(taskId, db)

try:
    # Use database...
    pass
finally:
    ctx.releaseScope(taskId)  # Calls db.cleanup()

Cleanup Priority

ServiceLocator checks methods in order:

  1. cleanup() (highest priority - DisposableInterface)
  2. close()
  3. dispose()
class MyResource(DisposableInterface):
    def cleanup(self):  # ✅ Preferred
        # Cleanup logic
        pass
    
    def close(self):  # Alternative if cleanup() not found
        pass
    
    def dispose(self):  # Fallback
        pass

Best Practices

✅ DO

# Implement DisposableInterface for scoped resources
class BrowserService(DisposableInterface):
    def cleanup(self):
        self.driver.quit()

# Use with scoped services
ctx.registerScopedService(taskId, resource)

❌ DON'T

# Don't forget to implement cleanup
class MyResource(DisposableInterface):
    pass  # Missing cleanup()!

# Don't raise exceptions in cleanup
def cleanup(self):
    raise Exception('Error')  # Will be logged but won't stop other cleanups

Related Documentation

Clone this wiki locally