Skip to content

Commit ca755fb

Browse files
authored
Explain f-string conflicts with Jinja templating (#48712)
* Explain f-string conflicts with Jinja templating * Fixed spaces * Update operators.rst. - removed traling spaces * Update operators.rst Doubled back ticks --------- Co-authored-by: Kacper <>
1 parent c68f31d commit ca755fb

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

airflow-core/docs/core-concepts/operators.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,3 +304,30 @@ If you upgrade your environment and get the following error:
304304
AttributeError: 'str' object has no attribute '__module__'
305305
306306
change name from ``params`` in your operators.
307+
308+
Templating Conflicts with f-strings
309+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
310+
311+
When constructing strings for templated fields (like ``bash_command`` in ``BashOperator``) using Python f-strings, be mindful of the interaction between f-string interpolation and Jinja templating syntax. Both use curly braces (``{}``).
312+
313+
Python f-strings interpret double curly braces (``{{`` and ``}}``) as escape sequences for literal single braces (``{`` and ``}``). However, Jinja uses double curly braces (``{{ variable }}``) to denote variables for templating.
314+
315+
If you need to include a Jinja template expression (e.g., ``{{ ds }}``) literally within a string defined using an f-string, so that Airflow's Jinja engine can process it later, you must escape the braces for the f-string by doubling them *again*. This means using **four** curly braces:
316+
317+
.. code-block:: python
318+
319+
t1 = BashOperator(
320+
task_id="fstring_templating_correct",
321+
bash_command=f"echo Data interval start: {{{{ ds }}}}",
322+
dag=dag,
323+
)
324+
325+
python_var = "echo Data interval start:"
326+
327+
t2 = BashOperator(
328+
task_id="fstring_templating_simple",
329+
bash_command=f"{python_var} {{{{ ds }}}}",
330+
dag=dag,
331+
)
332+
333+
This ensures the f-string processing results in a string containing the literal double braces required by Jinja, which Airflow can then template correctly before execution. Failure to do this is a common issue for beginners and can lead to errors during DAG parsing or unexpected behavior at runtime when the templating does not occur as expected.

0 commit comments

Comments
 (0)