Airflow Custom Operators
A custom operator is a reusable task template that you write yourself. Built-in operators cover many jobs. A team often repeats the same pattern in many DAGs, such as "check a file and log its size". A custom operator turns that pattern into one clean block.
The Cookie Cutter Picture
A baker who makes star-shaped cookies every day builds a star cutter once. After that, each cookie takes one press. A custom operator is the cutter, and each task is one cookie made with it.
Copy-paste approach: same 20 lines in 15 DAGs → 15 places to fix Custom operator: one class, used 15 times → 1 place to fix
Anatomy of an Operator
Every operator extends BaseOperator. Two parts matter: the __init__ method, which stores settings, and the execute method, which does the work.
from airflow.models import BaseOperator
class GreetOperator(BaseOperator):
def __init__(self, name, **kwargs):
super().__init__(**kwargs)
self.name = name
def execute(self, context):
message = f"Hello, {self.name}!"
self.log.info(message)
return message
Use the Operator in a DAG
from datetime import datetime
from airflow import DAG
from my_operators import GreetOperator
with DAG("greet_demo", start_date=datetime(2024, 1, 1),
schedule="@daily", catchup=False) as dag:
greet = GreetOperator(task_id="greet_sam", name="Sam")
Save my_operators.py in the plugins folder or in a folder that Python can import from, such as the dags folder.
Key Parts Explained
| Part | Role |
|---|---|
__init__ | Receives settings and passes unknown arguments to the parent class |
super().__init__(**kwargs) | Keeps task_id, retries, and other standard options working |
execute(self, context) | Holds the work. Airflow calls it at run time |
| Return value | Saved automatically as an XCom |
self.log | Writes to the task log |
A Practical Example: File Size Check
import os
from airflow.models import BaseOperator
from airflow.exceptions import AirflowException
class FileSizeCheckOperator(BaseOperator):
template_fields = ("path",)
def __init__(self, path, min_bytes=1, **kwargs):
super().__init__(**kwargs)
self.path = path
self.min_bytes = min_bytes
def execute(self, context):
size = os.path.getsize(self.path)
self.log.info("File %s has %s bytes", self.path, size)
if size < self.min_bytes:
raise AirflowException(f"File {self.path} is too small")
return size
check = FileSizeCheckOperator(
task_id="check_sales_file",
path="/data/sales_{{ ds_nodash }}.csv",
min_bytes=1000,
)
Templated Fields
The line template_fields = ("path",) tells Airflow to render Jinja placeholders in that attribute. The path above becomes a real date-based file name at run time. Add only the fields that need templating.
Where Hooks Fit
Keep connection logic in a hook and keep the operator thin. The operator asks the hook to do the outside work. Another operator can reuse the same hook.
Operator ──► Hook ──► Outside system (what to do) (how to connect)
Useful Class Attributes
| Attribute | Effect |
|---|---|
ui_color | Background color of the task box in the Graph view |
ui_fgcolor | Text color of the task box |
template_ext | File endings, such as .sql, that Airflow loads and renders |
Custom Operator or Python Function?
- Use a plain PythonOperator for a one-time job in one DAG.
- Use a TaskFlow
@taskfunction for small, simple steps. - Use a custom operator for logic that many DAGs share and that has its own settings.
Good Habits
- Keep
__init__light. Airflow runs it every time it parses a DAG. - Do the real work inside
executeonly. - Raise
AirflowExceptionwith a clear message when something goes wrong. - Write a unit test that calls
executewith a fake context.
Key Takeaways
- A custom operator extends BaseOperator and implements execute.
- Template fields allow date placeholders in your settings.
- Shared logic in one operator reduces copy-paste and bugs.
