Skip to main content

How to Run a Python Function in Apache Airflow® with PythonOperator

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

When a pipeline step is a Python function you already have, Apache Airflow® can run it as a task with PythonOperator. You hand it the function and the arguments to call it with, and Airflow logs what it prints and the value it returns. This guide runs a small function that adds two numbers on Airflow 3.4.0.

Syntax​

Syntax
from airflow.providers.standard.operators.python import PythonOperator

PythonOperator(
task_id="<task id>",
python_callable=<function>,
op_kwargs={"<parameter>": <value>},
)
PartWhat it means
from airflow.providers.standard.operators.python import PythonOperatorThe operator, from the standard provider that's installed with Airflow
task_id="<task id>"The task's name in the Dag
python_callable=<function>The function to run: its name, without parentheses
op_kwargs={"<parameter>": <value>}The arguments to call it with. Each key is the name of one of the function's parameters

The PythonOperator guide says: "Use the PythonOperator to execute Python callables." The operator's own documentation describes op_kwargs as "a dictionary of keyword arguments that will get unpacked in your function".

The Example​

add(a, b) adds two numbers, logs the sum and returns it. A Dag called add_numbers runs it once as the task add, with a=2 and b=3.

Prerequisites​

  • Apache Airflow® running, for example with airflow standalone, and its dags folder in your AIRFLOW_HOME.

Step 1: Write the Function​

Create dags/add_numbers.py and start it with the function:

dags/add_numbers.py
import logging

from airflow.providers.standard.operators.python import PythonOperator
from airflow.sdk import dag

log = logging.getLogger(__name__)


def add(a: int, b: int) -> int:
total = a + b
log.info("%d + %d = %d", a, b, total)
return total

It's an ordinary Python function: nothing in it depends on Airflow. log.info writes the sum to the task log.

Step 2: Run It with PythonOperator​

Below the function, add the Dag:

dags/add_numbers.py
@dag(schedule=None, tags=["demo"])
def add_numbers():
PythonOperator(
task_id="add",
python_callable=add,
op_kwargs={"a": 2, "b": 3},
)


add_numbers()

python_callable=add passes the function itself; Airflow calls it when the task runs, as add(a=2, b=3). The complete file:

dags/add_numbers.py
import logging

from airflow.providers.standard.operators.python import PythonOperator
from airflow.sdk import dag

log = logging.getLogger(__name__)


def add(a: int, b: int) -> int:
total = a + b
log.info("%d + %d = %d", a, b, total)
return total


@dag(schedule=None, tags=["demo"])
def add_numbers():
PythonOperator(
task_id="add",
python_callable=add,
op_kwargs={"a": 2, "b": 3},
)


add_numbers()

The add_numbers.py Dag file in an editor window: the add function that logs and returns a + b, and a PythonOperator with task_id add, python_callable=add and op_kwargs a 2 and b 3.

Step 3: Run It and Read the Log​

Trigger the Dag and open the add task's log (How to Read a Task Log in the Apache Airflow® UI shows where to click):

The log of the add task, a PythonOperator: Success, then the lines INFO - 2 + 3 = 5 and INFO - Done. Returned value was: 5.

  • 2 + 3 = 5 is the function's own log.info line.
  • Done. Returned value was: 5 is Airflow logging what the function returned. The operator's show_return_value_in_logs parameter controls this line, and it "Defaults to True".

The return value is also kept for other tasks: Airflow's XCom documentation says that "Many operators will auto-push their results into an XCom key called return_value".

Common Mistakes​

MistakeWhat happensDo this instead
Calling the function: python_callable=add(2, 3)Creating the operator fails with AirflowException: `python_callable` param must be callablePass the function, add, and its arguments in op_kwargs
A key in op_kwargs that isn't a parameter: {"a": 2, "c": 3}c is dropped without a warning, and the task fails with TypeError: add() missing 1 required positional argument: 'b'Use the function's exact parameter names as keys
Importing it from Airflow 2's path, airflow.operators.pythonIt still works in 3.4.0, with a warning: The `airflow.operators.python.PythonOperator` attribute is deprecated.Import it from airflow.providers.standard.operators.python

Troubleshooting​

SymptomLikely causeFix
AirflowException: `python_callable` param must be callablepython_callable got the function's result, not the functionRemove the parentheses and the arguments
TypeError: ... missing 1 required positional argumentA parameter has no value in op_kwargs, or its key is misspelledCompare the keys with the function's parameters
The function's log line isn't in the logYou opened another task's logOpen the add task's log

FAQ​

PythonOperator or @task?​

Both run a Python function. The guide calls the @task decorator "the Taskflow equivalent of PythonOperator": with @task you write the function inside the Dag, as in How to Write a Dag with the TaskFlow API in Apache Airflow®. PythonOperator takes any function by name, including one you import from your own module.

How do I pass arguments by position instead?​

Use op_args with a list: op_args=[2, 3]. The operator's documentation describes it as "a list of positional arguments that will get unpacked when calling your callable".

Conclusion​

PythonOperator(task_id="add", python_callable=add, op_kwargs={"a": 2, "b": 3}) ran add(a=2, b=3) as a task. Its log showed the function's own line, 2 + 3 = 5, and Airflow's Done. Returned value was: 5. Pass the function without parentheses, and name every argument exactly as the function does.

Additional Resources​

Apache®, Apache Airflow and Airflow® are either registered trademarks or trademarks of The Apache Software Foundation in the United States and/or other countries. No endorsement by The Apache Software Foundation is implied by the use of these marks.