Accessing Step Context
Use theget_step_context() function to access context within a step:
What’s Available in Step Context
from zenml import step, get_step_context
@step
def info_step() -> dict:
"""Display step execution information."""
context = get_step_context()
info = {
"step_name": context.step_name,
"step_run_id": str(context.step_run.id),
"pipeline_name": context.pipeline.name,
"pipeline_run_id": str(context.pipeline_run.id),
"run_name": context.pipeline_run.name,
}
print(f"Step: {info['step_name']}")
print(f"Pipeline: {info['pipeline_name']}")
print(f"Run: {info['run_name']}")
return info
from zenml import step, get_step_context
@step
def stack_aware_step() -> dict:
"""Access active stack components."""
context = get_step_context()
# Get artifact store
artifact_store = context.stack.artifact_store
print(f"Artifact store: {artifact_store.name}")
print(f"Artifact store path: {artifact_store.path}")
# Get orchestrator
orchestrator = context.stack.orchestrator
print(f"Orchestrator: {orchestrator.name}")
# Check for optional components
if context.stack.experiment_tracker:
print(f"Experiment tracker: {context.stack.experiment_tracker.name}")
return {
"artifact_store": artifact_store.name,
"orchestrator": orchestrator.name,
}
from zenml import step, get_step_context
from zenml.client import Client
@step
def compare_with_baseline(current_metrics: dict) -> dict:
"""Compare current metrics with baseline from previous run."""
context = get_step_context()
client = Client()
# Get the current pipeline
pipeline_name = context.pipeline.name
# Find previous successful runs
previous_runs = client.list_pipeline_runs(
pipeline_name=pipeline_name,
status="completed",
size=2 # Get last 2 runs (current + previous)
)
if len(previous_runs.items) > 1:
# Get the previous run (index 1, since 0 is current)
previous_run = previous_runs.items[1]
# Load artifact from previous run
baseline_metrics = previous_run.steps["evaluate_model"].output.load()
comparison = {
"current_accuracy": current_metrics["accuracy"],
"baseline_accuracy": baseline_metrics["accuracy"],
"improvement": current_metrics["accuracy"] - baseline_metrics["accuracy"]
}
print(f"Improvement: {comparison['improvement']:.3f}")
return comparison
else:
print("No baseline available, this is the first run")
return {"current_accuracy": current_metrics["accuracy"]}
from zenml import step, get_step_context, Model
@step(model=Model(name="my_model"))
def save_to_model_registry(model: object, metrics: dict) -> None:
"""Save model and associate with model registry."""
context = get_step_context()
# Access the model context
model_context = context.model
print(f"Model name: {model_context.name}")
print(f"Model version: {model_context.version}")
# The model and metrics are automatically tracked
# in the model registry through the context
Common Use Cases
Conditional Logic Based on Environment
Make decisions based on the active stack:Dynamic Artifact Naming
Create artifact names based on runtime information:Accessing Input Artifacts
Get information about input artifacts:Logging Custom Metadata
Add custom metadata to step runs:Working with Experiment Trackers
Integrate with experiment tracking systems:Accessing Configuration
Retrieve step and pipeline configuration:Pipeline State Management
Share state between steps using the run context:Error Handling with Context
Use context for better error messages:Best Practices
Use Context Judiciously
Only access context when needed. Don’t make every step context-dependent.
Cache Context Reference
Call
get_step_context() once and reuse the reference within the step.Handle Missing Components
Always check if optional stack components exist before using them.
Document Context Usage
Clearly document when steps depend on specific stack components.
Context Properties Reference
Available Properties
Limitations
Next Steps
Writing Steps
Learn the fundamentals of creating pipeline steps
Artifact Management
Understand how artifacts are tracked and accessed
Stack Configuration
Learn about configuring stack components
