airflow.providers.standard.operators.python

Module Contents

Classes

PythonOperator

Executes a Python callable.

BranchPythonOperator

A workflow can "branch" or follow a path after the execution of this task.

ShortCircuitOperator

Allows a pipeline to continue based on the result of a python_callable.

PythonVirtualenvOperator

Run a function in a virtualenv that is created and destroyed automatically.

BranchPythonVirtualenvOperator

A workflow can "branch" or follow a path after the execution of this task in a virtual environment.

ExternalPythonOperator

Run a function in a virtualenv that is not re-created.

BranchExternalPythonOperator

A workflow can "branch" or follow a path after the execution of this task.

Functions

get_current_context()

Retrieve the execution context dictionary without altering user method's signature.

Attributes

log

airflow.providers.standard.operators.python.log[source]
class airflow.providers.standard.operators.python.PythonOperator(*, python_callable, op_args=None, op_kwargs=None, templates_dict=None, templates_exts=None, show_return_value_in_logs=True, **kwargs)[source]

Bases: airflow.models.baseoperator.BaseOperator

Executes a Python callable.

See also

For more information on how to use this operator, take a look at the guide: PythonOperator

When running your callable, Airflow will pass a set of keyword arguments that can be used in your function. This set of kwargs correspond exactly to what you can use in your jinja templates. For this to work, you need to define **kwargs in your function header, or you can add directly the keyword arguments you would like to get - for example with the below code your callable will get the values of ti context variables.

With explicit arguments:

def my_python_callable(ti):
    pass

With kwargs:

def my_python_callable(**kwargs):
    ti = kwargs["ti"]
Parameters
  • python_callable (Callable) – A reference to an object that is callable

  • op_args (collections.abc.Collection[Any] | None) – a list of positional arguments that will get unpacked when calling your callable

  • op_kwargs (collections.abc.Mapping[str, Any] | None) – a dictionary of keyword arguments that will get unpacked in your function

  • templates_dict (dict[str, Any] | None) – a dictionary where the values are templates that will get templated by the Airflow engine sometime between __init__ and execute takes place and are made available in your callable’s context after the template has been applied. (templated)

  • templates_exts (collections.abc.Sequence[str] | None) – a list of file extensions to resolve while processing templated fields, for examples ['.sql', '.hql']

  • show_return_value_in_logs (bool) – a bool value whether to show return_value logs. Defaults to True, which allows return value log output. It can be set to False to prevent log output of return value when you return huge data such as transmission a large amount of XCom to TaskAPI.

template_fields: collections.abc.Sequence[str] = ('templates_dict', 'op_args', 'op_kwargs')[source]
template_fields_renderers[source]
BLUE = '#ffefeb'[source]
ui_color[source]
shallow_copy_attrs: collections.abc.Sequence[str] = ('python_callable', 'op_kwargs')[source]
execute(context)[source]

Derive when creating an operator.

Context is the same dictionary used as when rendering jinja templates.

Refer to get_template_context for more context.

determine_kwargs(context)[source]
execute_callable()[source]

Call the python callable with the given arguments.

Returns

the return value of the call.

Return type

Any

class airflow.providers.standard.operators.python.BranchPythonOperator(*, python_callable, op_args=None, op_kwargs=None, templates_dict=None, templates_exts=None, show_return_value_in_logs=True, **kwargs)[source]

Bases: PythonOperator, airflow.operators.branch.BranchMixIn

A workflow can “branch” or follow a path after the execution of this task.

It derives the PythonOperator and expects a Python function that returns a single task_id, a single task_group_id, or a list of task_ids and/or task_group_ids to follow. The task_id(s) and/or task_group_id(s) returned should point to a task or task group directly downstream from {self}. All other “branches” or directly downstream tasks are marked with a state of skipped so that these paths can’t move forward. The skipped states are propagated downstream to allow for the DAG state to fill up and the DAG run’s state to be inferred.

execute(context)[source]

Derive when creating an operator.

Context is the same dictionary used as when rendering jinja templates.

Refer to get_template_context for more context.

class airflow.providers.standard.operators.python.ShortCircuitOperator(*, ignore_downstream_trigger_rules=True, **kwargs)[source]

Bases: PythonOperator, airflow.models.skipmixin.SkipMixin

Allows a pipeline to continue based on the result of a python_callable.

The ShortCircuitOperator is derived from the PythonOperator and evaluates the result of a python_callable. If the returned result is False or a falsy value, the pipeline will be short-circuited. Downstream tasks will be marked with a state of “skipped” based on the short-circuiting mode configured. If the returned result is True or a truthy value, downstream tasks proceed as normal and an XCom of the returned result is pushed.

The short-circuiting can be configured to either respect or ignore the trigger_rule set for downstream tasks. If ignore_downstream_trigger_rules is set to True, the default setting, all downstream tasks are skipped without considering the trigger_rule defined for tasks. However, if this parameter is set to False, the direct downstream tasks are skipped but the specified trigger_rule for other subsequent downstream tasks are respected. In this mode, the operator assumes the direct downstream tasks were purposely meant to be skipped but perhaps not other subsequent tasks.

See also

For more information on how to use this operator, take a look at the guide: ShortCircuitOperator

Parameters

ignore_downstream_trigger_rules (bool) – If set to True, all downstream tasks from this operator task will be skipped. This is the default behavior. If set to False, the direct, downstream task(s) will be skipped but the trigger_rule defined for all other downstream tasks will be respected.

execute(context)[source]

Derive when creating an operator.

Context is the same dictionary used as when rendering jinja templates.

Refer to get_template_context for more context.

class airflow.providers.standard.operators.python.PythonVirtualenvOperator(*, python_callable, requirements=None, python_version=None, serializer=None, system_site_packages=True, pip_install_options=None, op_args=None, op_kwargs=None, string_args=None, templates_dict=None, templates_exts=None, expect_airflow=True, skip_on_exit_code=None, index_urls=None, venv_cache_path=None, env_vars=None, inherit_env=True, use_airflow_context=False, **kwargs)[source]

Bases: _BasePythonVirtualenvOperator

Run a function in a virtualenv that is created and destroyed automatically.

The function (has certain caveats) must be defined using def, and not be part of a class. All imports must happen inside the function and no variables outside the scope may be referenced. A global scope variable named virtualenv_string_args will be available (populated by string_args). In addition, one can pass stuff through op_args and op_kwargs, and one can use a return value. Note that if your virtualenv runs in a different Python major version than Airflow, you cannot use return values, op_args, op_kwargs, or use any macros that are being provided to Airflow through plugins. You can use string_args though.

See also

For more information on how to use this operator, take a look at the guide: PythonVirtualenvOperator

Parameters
  • python_callable (Callable) – A python function with no references to outside variables, defined with def, which will be run in a virtual environment.

  • requirements (None | collections.abc.Iterable[str] | str) – Either a list of requirement strings, or a (templated) “requirements file” as specified by pip.

  • python_version (str | None) – The Python version to run the virtual environment with. Note that both 2 and 2.7 are acceptable forms.

  • serializer (_SerializerTypeDef | None) –

    Which serializer use to serialize the args and result. It can be one of the following:

    • "pickle": (default) Use pickle for serialization. Included in the Python Standard Library.

    • "cloudpickle": Use cloudpickle for serialize more complex types, this requires to include cloudpickle in your requirements.

    • "dill": Use dill for serialize more complex types, this requires to include dill in your requirements.

  • system_site_packages (bool) – Whether to include system_site_packages in your virtual environment. See virtualenv documentation for more information.

  • pip_install_options (list[str] | None) – a list of pip install options when installing requirements See ‘pip install -h’ for available options

  • op_args (collections.abc.Collection[Any] | None) – A list of positional arguments to pass to python_callable.

  • op_kwargs (collections.abc.Mapping[str, Any] | None) – A dict of keyword arguments to pass to python_callable.

  • string_args (collections.abc.Iterable[str] | None) – Strings that are present in the global var virtualenv_string_args, available to python_callable at runtime as a list[str]. Note that args are split by newline.

  • templates_dict (dict | None) – a dictionary where the values are templates that will get templated by the Airflow engine sometime between __init__ and execute takes place and are made available in your callable’s context after the template has been applied

  • templates_exts (list[str] | None) – a list of file extensions to resolve while processing templated fields, for examples ['.sql', '.hql']

  • expect_airflow (bool) – expect Airflow to be installed in the target environment. If true, the operator will raise warning if Airflow is not installed, and it will attempt to load Airflow macros when starting.

  • skip_on_exit_code (int | collections.abc.Container[int] | None) – If python_callable exits with this exit code, leave the task in skipped state (default: None). If set to None, any non-zero exit code will be treated as a failure.

  • index_urls (None | collections.abc.Collection[str] | str) – an optional list of index urls to load Python packages from. If not provided the system pip conf will be used to source packages from.

  • venv_cache_path (None | os.PathLike[str]) – Optional path to the virtual environment parent folder in which the virtual environment will be cached, creates a sub-folder venv-{hash} whereas hash will be replaced with a checksum of requirements. If not provided the virtual environment will be created and deleted in a temp folder for every execution.

  • env_vars (dict[str, str] | None) – A dictionary containing additional environment variables to set for the virtual environment when it is executed.

  • inherit_env (bool) – Whether to inherit the current environment variables when executing the virtual environment. If set to True, the virtual environment will inherit the environment variables of the parent process (os.environ). If set to False, the virtual environment will be executed with a clean environment.

  • use_airflow_context (bool) – Whether to provide get_current_context() to the python_callable. NOT YET IMPLEMENTED - waits for AIP-72 context serialization.

template_fields: collections.abc.Sequence[str][source]
template_ext: collections.abc.Sequence[str] = ('.txt',)[source]
execute_callable()[source]

Call the python callable with the given arguments.

Returns

the return value of the call.

class airflow.providers.standard.operators.python.BranchPythonVirtualenvOperator(*, python_callable, requirements=None, python_version=None, serializer=None, system_site_packages=True, pip_install_options=None, op_args=None, op_kwargs=None, string_args=None, templates_dict=None, templates_exts=None, expect_airflow=True, skip_on_exit_code=None, index_urls=None, venv_cache_path=None, env_vars=None, inherit_env=True, use_airflow_context=False, **kwargs)[source]

Bases: PythonVirtualenvOperator, airflow.operators.branch.BranchMixIn

A workflow can “branch” or follow a path after the execution of this task in a virtual environment.

It derives the PythonVirtualenvOperator and expects a Python function that returns a single task_id, a single task_group_id, or a list of task_ids and/or task_group_ids to follow. The task_id(s) and/or task_group_id(s) returned should point to a task or task group directly downstream from {self}. All other “branches” or directly downstream tasks are marked with a state of skipped so that these paths can’t move forward. The skipped states are propagated downstream to allow for the DAG state to fill up and the DAG run’s state to be inferred.

See also

For more information on how to use this operator, take a look at the guide: BranchPythonVirtualenvOperator

execute(context)[source]

Derive when creating an operator.

Context is the same dictionary used as when rendering jinja templates.

Refer to get_template_context for more context.

class airflow.providers.standard.operators.python.ExternalPythonOperator(*, python, python_callable, serializer=None, op_args=None, op_kwargs=None, string_args=None, templates_dict=None, templates_exts=None, expect_airflow=True, expect_pendulum=False, skip_on_exit_code=None, env_vars=None, inherit_env=True, use_airflow_context=False, **kwargs)[source]

Bases: _BasePythonVirtualenvOperator

Run a function in a virtualenv that is not re-created.

Reused as is without the overhead of creating the virtual environment (with certain caveats).

The function must be defined using def, and not be part of a class. All imports must happen inside the function and no variables outside the scope may be referenced. A global scope variable named virtualenv_string_args will be available (populated by string_args). In addition, one can pass stuff through op_args and op_kwargs, and one can use a return value. Note that if your virtual environment runs in a different Python major version than Airflow, you cannot use return values, op_args, op_kwargs, or use any macros that are being provided to Airflow through plugins. You can use string_args though.

If Airflow is installed in the external environment in different version that the version used by the operator, the operator will fail.,

See also

For more information on how to use this operator, take a look at the guide: ExternalPythonOperator

Parameters
  • python (str) – Full path string (file-system specific) that points to a Python binary inside a virtual environment that should be used (in VENV/bin folder). Should be absolute path (so usually start with “/” or “X:/” depending on the filesystem/os used).

  • python_callable (Callable) – A python function with no references to outside variables, defined with def, which will be run in a virtual environment.

  • serializer (_SerializerTypeDef | None) –

    Which serializer use to serialize the args and result. It can be one of the following:

    • "pickle": (default) Use pickle for serialization. Included in the Python Standard Library.

    • "cloudpickle": Use cloudpickle for serialize more complex types, this requires to include cloudpickle in your requirements.

    • "dill": Use dill for serialize more complex types, this requires to include dill in your requirements.

  • op_args (collections.abc.Collection[Any] | None) – A list of positional arguments to pass to python_callable.

  • op_kwargs (collections.abc.Mapping[str, Any] | None) – A dict of keyword arguments to pass to python_callable.

  • string_args (collections.abc.Iterable[str] | None) – Strings that are present in the global var virtualenv_string_args, available to python_callable at runtime as a list[str]. Note that args are split by newline.

  • templates_dict (dict | None) – a dictionary where the values are templates that will get templated by the Airflow engine sometime between __init__ and execute takes place and are made available in your callable’s context after the template has been applied

  • templates_exts (list[str] | None) – a list of file extensions to resolve while processing templated fields, for examples ['.sql', '.hql']

  • expect_airflow (bool) – expect Airflow to be installed in the target environment. If true, the operator will raise warning if Airflow is not installed, and it will attempt to load Airflow macros when starting.

  • skip_on_exit_code (int | collections.abc.Container[int] | None) – If python_callable exits with this exit code, leave the task in skipped state (default: None). If set to None, any non-zero exit code will be treated as a failure.

  • env_vars (dict[str, str] | None) – A dictionary containing additional environment variables to set for the virtual environment when it is executed.

  • inherit_env (bool) – Whether to inherit the current environment variables when executing the virtual environment. If set to True, the virtual environment will inherit the environment variables of the parent process (os.environ). If set to False, the virtual environment will be executed with a clean environment.

  • use_airflow_context (bool) – Whether to provide get_current_context() to the python_callable. NOT YET IMPLEMENTED - waits for AIP-72 context serialization.

template_fields: collections.abc.Sequence[str][source]
execute_callable()[source]

Call the python callable with the given arguments.

Returns

the return value of the call.

class airflow.providers.standard.operators.python.BranchExternalPythonOperator(*, python, python_callable, serializer=None, op_args=None, op_kwargs=None, string_args=None, templates_dict=None, templates_exts=None, expect_airflow=True, expect_pendulum=False, skip_on_exit_code=None, env_vars=None, inherit_env=True, use_airflow_context=False, **kwargs)[source]

Bases: ExternalPythonOperator, airflow.operators.branch.BranchMixIn

A workflow can “branch” or follow a path after the execution of this task.

Extends ExternalPythonOperator, so expects to get Python: virtual environment that should be used (in VENV/bin folder). Should be absolute path, so it can run on separate virtual environment similarly to ExternalPythonOperator.

See also

For more information on how to use this operator, take a look at the guide: BranchExternalPythonOperator

execute(context)[source]

Derive when creating an operator.

Context is the same dictionary used as when rendering jinja templates.

Refer to get_template_context for more context.

airflow.providers.standard.operators.python.get_current_context()[source]

Retrieve the execution context dictionary without altering user method’s signature.

This is the simplest method of retrieving the execution context dictionary.

Old style:

def my_task(**context):
    ti = context["ti"]

New style:

from airflow.providers.standard.operators.python import get_current_context


def my_task():
    context = get_current_context()
    ti = context["ti"]

Current context will only have value if this method was called after an operator was starting to execute.

Was this entry helpful?