Course contentsShow
← Python
Lesson 1013 of 1,06016. Capstone and AutomationFree lesson

Creating Context Objects for Shared State Management

Use dependency injection patterns to pass shared state and configuration objects across various commands without relying on global variables.

In this lesson, you will learn how to replace fragile global variables with injectable context objects to maintain clean, thread-safe state across your CLI commands.

The Problem with Globals

As your data pipelines grow in complexity, you often need to share database connections, configuration settings, or logging instances across multiple commands. Relying on global variables makes your code difficult to test, prone to side effects, and hard to debug. Instead, we use the Dependency Injection pattern, where we instantiate a "Context Object" at the entry point of our application and pass it explicitly to the commands that require it.

Implementing a Context Object

Using a dataclass or a simple object, we can bundle our shared state. When building a CLI (such as with Typer, which we covered previously), you can define a state object that holds your environment-specific configuration and stateful resources.

from dataclasses import dataclass
from typing import Optional

@dataclass
class AppContext:
    config_path: str
    db_connection: Optional[object] = None
    verbose: bool = False

# Injecting the context into commands
def run_ingestion(ctx: AppContext):
    if ctx.verbose:
        print(f"Ingesting data from {ctx.config_path}...")
    # Use ctx.db_connection here...

Why This Matters for Pipelines

By creating a dedicated object, you enforce a clear interface contract. When a command needs access to a specific resource, it doesn't "reach out" to the global scope; instead, the application lifecycle orchestrator provides the context. This allows you to swap out configurations (for instance, pointing to a mock database during testing or a production instance during execution) without modifying the internal logic of your commands.

This approach also simplifies unit testing: you can easily instantiate a mock AppContext and pass it directly to your functions, ensuring your pipeline components are decoupled from the environment they reside in. It turns "hidden" dependencies into "explicit" requirements, which is the hallmark of a professional, scalable codebase.

Key Takeaway: Replace global variables with an explicit Context Object to decouple your application state from individual logic blocks, enabling cleaner dependency injection and more maintainable pipelines.