요약

  • Python 데코레이터의 기능을 airflow task로 활용
  • airflow 공식 문서에서도 PythonOperator보다 task decorator 활용을 권장
  • from airflow.decorators import task를 통해 사용

1. Python 데코레이터

Python decorator 개념

  1. 원래의 함수를 감싸(wrapping) 바깥에 추가 기능을 덧붙임
  2. 함수를 직접 수정하지 않고 wrapping 함수로 변경 최소화
def outer_func(target_func):
    def inner_func():
        print('target 함수 실행 전')
        target_func()
        print('target 함수 실행 후')
    return inner_func()
 
# Decorator 활용
@outer_func
def get_data():
    print('함수 실행')
 
get_data()

2. Task 데코레이터

PythonOperator vs Task Decorator 비교

PythonOperator 활용:

from airflow.operators.python import PythonOperator
 
def python_func():
    ...
 
py_task_1 = PythonOperator(
    task_id='py_task_1',
    python_callable=python_func
)

Task decorator 활용 (코드 단축):

from airflow.decorators import task
 
@task(task_id='py_task_1')
def python_func():
    ...
 
py_task_1 = python_func()

참고사이트