---
title: "Use a custom function in Airflow templates"
description: "How to add a custom function to Airflow and use it in a template"
author: "Bartosz Mikulski"
author_bio: "Principal AI Engineer & MLOps Architect. I bridge the gap between \"it works in a notebook\" and \"it works for 200 million users.\""
author_url: https://mikulskibartosz.name
author_linkedin: https://www.linkedin.com/in/mikulskibartosz/
author_github: https://github.com/mikulskibartosz
canonical_url: https://mikulskibartosz.name/use-custom-function-in-airflow-templates
---

Adding a custom function to Airflow is quite simple. First, we have do define a function in Python, for example, this one:

```python
def do_something_with_execution_date(execution_date):
    # Imagine that there is some useful code ;)
    ...
```

When the function is ready, we use the `user_defined_macros` parameter of the DAG object to pass a dictionary of custom functions:

```python
dag = DAG(
    ...,
    user_defined_macros={
        'custom_function': do_something_with_execution_date,
    }
)
```

Now, we can use the custom function in any place that supports Airflow templates. Of course, only in the DAGs that have access to the functions.

```
{%raw %}{{ custom_function(execution_date) }};{% endraw %}
```

Note that, I can pass parameters to the function and rename it by using a different name as the dictionary key.

