Principle:173TECH Sayn Python Task Interface
| Knowledge Sources | |
|---|---|
| Domains | Software_Engineering, Python |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
Pattern for defining Python tasks through a decorator or class interface with automatic dependency injection of database connections, parameters, and context via function signature inspection.
Description
Python task interface allows users to write ETL logic in Python using two approaches:
- Decorator-based: Use
@taskon a function. SAYN inspects the function signature and injects arguments by name:context→ the task instance (self), providingsrc(),out(),connections,parameters, logging methods- Connection names (matching
required_credentials) →Databaseobjects - Other parameter names → task parameters from YAML
- Class-based: Subclass
PythonTaskand overrideconfig(),setup(),run(),compile(),test(). Access connections viaself.connections, parameters viaself.parameters.
The decorator approach is simpler for straightforward tasks; the class approach provides full lifecycle control.
Usage
Use this principle when Python logic is needed for tasks that cannot be expressed as SQL — e.g., API calls, complex transformations, data generation. Use the decorator for simple tasks and the class for tasks needing setup or compile logic.
Theoretical Basis
The decorator-based injection uses inspect.signature to read parameter names:
# Abstract algorithm (NOT real implementation)
def run(self):
sig = inspect.signature(self._func)
args = []
for param_name in sig.parameters:
if param_name == "context":
args.append(self) # Inject task instance
elif param_name in self.connections:
args.append(self.connections[param_name]) # Inject Database
else:
args.append(self.task_parameters.get(param_name)) # Inject parameter
return self._func(*args)
The DecoratorTaskWrapper collects metadata at decoration time (sources, outputs, parents, tags) and is discovered by PythonLoader.get_objects via module inspection.
Practical Guide
Decorator-based task:
# python/load_data.py
from sayn import task
@task(sources="raw.users", outputs="analytics.user_summary")
def summarize_users(context, warehouse):
"""Function params are injected by name."""
users = warehouse.read_data(
f"SELECT * FROM {context.src('raw.users')}"
)
summary = process_users(users)
warehouse.load_data(
context.out("analytics.user_summary"),
summary,
replace=True,
)
context.info(f"Loaded {len(summary)} records")
Class-based task:
# python/custom_task.py
from sayn import PythonTask
class CustomTask(PythonTask):
def config(self, **task_config):
self.threshold = task_config.get("threshold", 100)
return self.success()
def run(self):
db = self.connections["warehouse"]
data = db.read_data("SELECT * FROM staging")
if len(data) > self.threshold:
self.warning(f"Data exceeds threshold: {len(data)}")
return self.success()