skip to content

Why does a KFP v2 lightweight @dsl.component that relies on a module-level import and a same-file helper fail on the cluster with NameError?

level: middleimportance: should knowfreq 10%

answer

  1. only the function's source travels
  2. hermetic: imports inside the body
  3. packages_to_install runs every execution
  4. additional_funcs or target_image
  5. base_image defaults to python:3.11

basics

~20 s

A lightweight component ships only its own function source, run in base_image after KFP's own imports, so module-level imports and helpers never arrive. Import inside the body, list packages in packages_to_install, pass helpers through additional_funcs, or build a containerized component.

solid answer

~40 s

`@dsl.component` without `target_image` builds a **lightweight** component. The SDK copies the decorated function's source into the compiled spec, and at run time the step writes it to an ephemeral module inside `base_image` (`python:3.11` by default in SDK 2.17). That module's only preamble is `import kfp`, `from kfp import dsl`, `from kfp.dsl import *` and `from typing import *`. A module-level `import pandas as pd`, a `clean_text()` helper or a constant never makes the trip, hence the `NameError`. The fixes are to import inside the body and add the package to `packages_to_install` (installed at every execution), to pass shared helpers with `additional_funcs` (SDK 2.15+), or to set `target_image` and build a **containerized** Python component with `kfp component build`. The last option bakes code and dependencies into an image and lifts the self-contained rule.

code

python · 16 lines
python
from kfp import dsl
from kfp.dsl import Dataset, Input, Output

def clean_text(text: str) -> str:
    return ' '.join(text.lower().split())

@dsl.component(
    base_image='python:3.11',
    packages_to_install=['pandas', 'pyarrow'],
    additional_funcs=[clean_text],
)
def prepare_articles(articles: Input[Dataset], prepared: Output[Dataset]):
    import pandas as pd  # imports live inside the body
    df = pd.read_parquet(articles.path)
    df['body'] = df['body'].map(clean_text)
    df.to_parquet(prepared.path)

go deeper

for a junior

Recall that a lightweight component must be self-contained: imports and helpers go inside the function, and dependencies go in packages_to_install.

for a middle

Explain what actually ships: the function source in an ephemeral module with only KFP's imports, run on base_image, and how additional_funcs and target_image change that.

for a senior

Choose per component: lightweight for quick steps, containerized images with pinned tags for production code with real dependencies, container components for non-Python tools, and pin base_image ahead of the 3.12 switch.

for a principal

Set the team's component standard: who owns base images and the registry, whether runtime pip installs are allowed at all, and how image tags tie a run to reviewed code.

## What a lightweight component ships In KFP v2 a function decorated with `@dsl.component`, and given no `target_image`, becomes a **lightweight Python component**. At compile time the SDK takes the source text of the decorated function, and only that function, and embeds it in the component's container command. At run time the step's container works through four steps: 1. It starts from `base_image`, which defaults to `python:3.11` in KFP SDK 2.17. 2. It pip-installs `kfp` and anything listed in `packages_to_install`. 3. It writes the embedded source to a temporary `ephemeral_component.py`. That module's preamble is `import kfp`, `from kfp import dsl`, `from kfp.dsl import *` and `from typing import *`, followed by any `additional_funcs` and then your function. 4. It calls the function with the task's resolved inputs. Nothing else from your Python file exists in that module. The KFP docs call this requirement **hermetic**: the function may not reference any symbol defined outside its body. Testing the plain, undecorated function in a notebook hides the problem, because there the file's imports and helpers are all in scope. ## Why the NameError happens Take a `prepare_articles` component written in a notebook: - `import pandas as pd` at the top of the file: `pd` is undefined in the ephemeral module, so the first `pd.read_parquet(...)` raises `NameError`. - a `clean_text()` helper defined beside it: also undefined, with the same error. - a module-level constant such as `MAX_TOKENS = 512`: undefined as well. The failure is not about missing packages. A package that is absent from the image surfaces as `ModuleNotFoundError` on the import line, and only once that import line actually sits inside the function. ## Three ways to fix it | Fix | How | What it costs | |---|---|---| | Make it hermetic | move `import pandas as pd` into the body; add `'pandas'` to `packages_to_install` | pip install on every execution; the package index must be reachable | | `additional_funcs` (SDK 2.15+) | `@dsl.component(additional_funcs=[clean_text])` embeds the helper's source before your function | helpers only; packages still need installing | | Containerized Python component | set `target_image`, build with `kfp component build` | an image build and a registry, in exchange for importing adjacent modules freely | The KFP docs recommend the containerized form as production practice whenever a component needs `packages_to_install`. Dependencies are then installed once, when the image is built, rather than at the start of every task. ## Containerized Python components Put the component and its helper modules in a directory such as `src/`, and decorate the function with both `base_image` and `target_image`: ```python @dsl.component(base_image='python:3.11', target_image='registry.internal.example/article-topics/prepare:v3') def prepare_articles(articles: Input[Dataset], prepared: Output[Dataset]): from text_utils import clean_text # an adjacent module baked into the image ... ``` Then run `kfp component build src/ --component-filepattern prepare.py --push-image`. Here `base_image` becomes the `FROM` line of the generated Dockerfile. The build copies your code in and installs dependencies and KFP, and the compiled component simply runs `target_image`. Use `--no-push-image` to keep the image local. Pin `target_image` to a tag you change on every build, so that a run never quietly picks up different code under the same name. ## Where @dsl.container_component fits `@dsl.container_component` is for steps that are not Python functions at all: a shell script, a compiled binary, another language. The function returns `dsl.ContainerSpec(image=..., command=..., args=...)`. Inputs become placeholders in `command` and `args`, and outputs must be written by your own code to paths declared with `dsl.OutputPath(...)` or to output-artifact paths, because a container has no return value. ## A checklist when a lightweight component fails remotely - **`NameError`**: a name used in the body was defined at file level. Move it inside, or pass it through `additional_funcs` if it is a function. - **`ModuleNotFoundError`**: the import is inside the body, but the package is neither in `base_image` nor in `packages_to_install`. - **Different behaviour from your laptop**: the container runs `base_image`'s Python and whatever versions pip resolved that day. Pin both. - **Slow start on every run**: `packages_to_install` is reinstalling at each execution. That is the signal to move to a containerized component. ## Pin the base image When `base_image` is omitted, SDK 2.17 emits a `FutureWarning`: the default will switch from `python:3.11` to `python:3.12` on Oct 1, 2027. A pipeline that relies on the default can change interpreter just by being recompiled with a later SDK. Set `base_image` explicitly and pin the versions in `packages_to_install`. Trust the SDK over prose here, since one older lightweight-components docs page still quotes `python:3.7` as the default.

  • What does packages_to_install cost you in production?
    The listed packages are pip-installed at the start of every execution of the step. Each run pays the install time and depends on the package index being reachable, and an unpinned name can resolve to a different release next week. The KFP docs recommend a containerized Python component whenever `packages_to_install` is needed, because `kfp component build` installs dependencies into the image once.
  • When is @dsl.container_component the right choice instead?
    When the step is not a Python function: a shell script, a binary, another language. The function returns `dsl.ContainerSpec(image=..., command=..., args=...)`, inputs become placeholders in `command` and `args`, and outputs must be written by your code to paths declared with `dsl.OutputPath(...)`, because a container has no return value.

  • Module-level imports are bundled with a lightweight component automatically
  • A NameError on pd means pandas is missing from packages_to_install
  • packages_to_install bakes dependencies into the image once at compile time
  • The default base image for @dsl.component is python:3.7
  • A containerized Python component needs @dsl.container_component, not @dsl.component

Assumes KFP SDK 2.17.0: default base_image python:3.11 with a FutureWarning about python:3.12 from Oct 1, 2027; additional_funcs arrived in SDK 2.15.