Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:173TECH Sayn PythonTask

From Leeroopedia
Knowledge Sources
Domains Python, Task_Interface
Last Updated 2026-10-17 00:00 GMT

Overview

Concrete tool for writing Python-based SAYN tasks using either a decorator interface with automatic dependency injection or a class-based interface with full lifecycle control.

Description

The PythonTask module provides two ways to write Python tasks:

1. Decorator-based (@task):

  • Decorate a function with @task(sources=..., outputs=..., parents=..., tags=..., on_fail=...)
  • SAYN inspects the function signature and injects:
    • context → task instance (for src(), out(), connections, logging)
    • Connection names → Database objects
    • Other names → task parameters from YAML

2. Class-based (PythonTask subclass):

  • Override config(), setup(), run(), compile(), test()
  • Access connections via self.connections[name]
  • Access parameters via self.parameters (merged project + task)
  • Use self.src()/self.out() for object resolution
  • Use self.set_run_steps()/self.step() for progress tracking

The DecoratorTaskWrapper collects metadata at decoration time and is discovered by PythonLoader.get_objects via module inspection. The DecoratorTask class handles the actual execution.

Usage

  • Decorator: For simple tasks that just need a run() method with injected dependencies
  • Class-based: For tasks needing config validation, setup logic, or compile/test behavior

Code Reference

Source Location

  • Repository: SAYN
  • File: sayn/tasks/python.py
  • Lines: L15-29 (PythonTask), L32-117 (DecoratorTask), L120-213 (DecoratorTaskWrapper), L215-228 (task_type), L231-246 (task)
  • File: sayn/__init__.py
  • Lines: L8-11 (re-exports PythonTask, task)

Signature

# Class-based interface
class PythonTask(Task):
    def config(self, **task_config) -> Result
    def setup(self) -> Result
    def run(self) -> Result
    def compile(self) -> Result
    def test(self) -> Result

# Decorator interface
def task(
    func=None,
    sources: Optional[Union[List[str], str]] = None,
    outputs: Optional[Union[List[str], str]] = None,
    parents: Optional[Union[List[str], str]] = None,
    tags: Optional[Union[List[str], str]] = None,
    on_fail: Optional[str] = None,
) -> DecoratorTaskWrapper

class DecoratorTaskWrapper(Task):
    def __init__(self, func, sources=None, outputs=None, parents=None, tags=None, on_fail=None)
    def __call__(self, name, group, tracker, ...) -> DecoratorTask

class DecoratorTask(PythonTask):
    def run(self) -> Result  # Inspects signature, injects args, calls func

Import

from sayn import task, PythonTask

I/O Contract

Inputs (Decorator)

Name Type Required Description
func callable Yes The decorated function
sources List[str] No Source table declarations
outputs List[str] No Output table declarations
parents List[str] No Explicit parent tasks
tags List[str] No Task tags
on_fail str No "skip" or "no_skip"

Inputs (Function Signature Injection)

Parameter Name Injected As Description
context DecoratorTask (self) Task instance with src(), out(), connections, logging
<connection_name> Database Database object matching a required credential name
<any_other> task parameter Value from task_parameters in YAML

Outputs

Name Type Description
result Result Ok/Err from the function's return value

Usage Examples

Decorator-Based Task (Simple)

# python/load_data.py
from sayn import task

@task(sources="raw.users", outputs="analytics.user_summary")
def summarize_users(context, warehouse):
    """warehouse is injected as the Database connection named 'warehouse'."""
    users = warehouse.read_data(
        f"SELECT * FROM {context.src('raw.users')}"
    )
    summary = [
        {"user_id": u["user_id"], "name": u["name"]}
        for u in users
    ]
    warehouse.load_data(
        context.out("analytics.user_summary"),
        summary,
        replace=True,
    )
    context.info(f"Loaded {len(summary)} records")

Class-Based Task (Full Lifecycle)

# python/custom_etl.py
from sayn import PythonTask

class CustomETL(PythonTask):
    def config(self, **task_config):
        self.threshold = task_config.get("threshold", 100)
        self.set_run_steps(["Extract", "Transform", "Load"])
        return self.success()

    def setup(self):
        # Validate that source table exists
        db = self.connections["warehouse"]
        if not db._table_exists("raw", "staging"):
            return self.fail("Source table raw.staging does not exist")
        return self.success()

    def run(self):
        db = self.connections["warehouse"]

        with self.step("Extract"):
            data = db.read_data("SELECT * FROM raw.staging")

        with self.step("Transform"):
            processed = [transform(r) for r in data]
            if len(processed) > self.threshold:
                self.warning(f"Data exceeds threshold: {len(processed)}")

        with self.step("Load"):
            db.load_data("analytics.output", processed, replace=True)

        return self.success()

Using Parameters

# Access project and task parameters
@task
def parametrized_task(context, warehouse):
    # Parameters merged from project.yaml and task config
    start = context.parameters.get("start_date")
    limit = context.parameters.get("max_records", 1000)

    data = warehouse.read_data(
        f"SELECT * FROM events WHERE date >= '{start}' LIMIT {limit}"
    )

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment