3

I create my Airflow DAGs as follows:

dag = DAG(...)

But in multiple tutorials and course I see that they use the with ... as clause like this:

with DAG(...) as dag:
    # Code that will use the dag variable.

I guess this way, the DAG instances will be destroyed after the scheduler executes the code block, but is there a real benefit in doing so? I can't find any documentation talking about this.

Stephen
  • 7,475
  • 12
  • 47
  • 89
Robert Reynolds
  • 1,696
  • 1
  • 17
  • 47

1 Answers1

6

Yes.

If you understand what with...as does, then you should understand that its impact on the airflow ecosystem is really no different.

Specifically, it ensures that unmanaged resources -in this case implementations of the DAG class- are properly cleaned up, even if there are exceptions thrown (without needing to use a try/except block every time.)

Additionally it's nice to not have to add dag=dag to every single one.

Forest
  • 808
  • 6
  • 9
  • What actually needs to be cleaned up, though? `with` is used a lot to make sure that open file handles are automatically closed, for example. What would an Airflow DAG need to make sure was cleaned up? – Stephen Oct 13 '21 at 13:48