n8n Native Python Code Node (n8n 2.x)
Write reliable, performant data transformations in n8n 2.x native Python Code nodes across n8n Cloud and self-hosted environments.
When to Use
Use this skill when:
- Writing custom Python transformation logic inside n8n Code nodes (Language: Python).
- Processing workflow items using n8n 2.x native Python data structures (
_items and _item).
- Navigating runtime constraints between n8n Cloud (pure built-in execution) and self-hosted n8n (task runner images with custom packages).
- Debugging Python syntax errors, item key access, or return format rejections in n8n.
Do not use this skill for:
- Writing schema-constrained AI Custom Code Tools for LangChain/AI Agent nodes (use
n8n-code-tool).
- Writing JavaScript Code nodes or utilizing n8n JS-specific helpers (
$helpers, Luxon, $jmespath).
Prerequisites
- n8n version 2.0+ with Native Python execution mode active.
- Defined input dataset from upstream trigger or action node.
Execution Model & Data Structures
In n8n 2.x native Python, data is exposed via two built-in variables depending on the selected execution mode:
| Mode |
Variable |
Description |
| Run Once for All Items |
_items |
List of item dictionaries: [{"json": {...}}, ...] |
| Run Once for Each Item |
_item |
Current item dictionary: {"json": {...}} |
[!NOTE]
Native Python in n8n 2.x does not support legacy Pyodide objects (_input.all(), _input.first(), _input.item) or global $node helpers. For legacy Pyodide instances (n8n 1.x), see the Legacy Pyodide Compatibility Guide.
Return Format Contract
- Run Once for All Items Mode: Must return a list of dictionaries with
"json" keys (e.g. [{"json": {...}}]) or a list of flat dictionaries (n8n will wrap them into {"json": ...}).
- Run Once for Each Item Mode: Must return a single dictionary with a
"json" key (e.g. {"json": {...}}) or a single flat dictionary.
Code Examples
Example 1: Batch Processing & Normalization (All Items Mode)
# Mode: Run Once for All Items
results = []
for item in _items:
data = item.get("json", {})
cleaned_record = {
"user_id": str(data.get("id", "")).strip().upper(),
"email": str(data.get("email", "")).strip().lower(),
"gross_amount": round(float(data.get("amount", 0.0)), 2),
"is_active": bool(data.get("status") == "active"),
}
results.append({"json": cleaned_record})
return results
Example 2: Per-Item Transformation (Each Item Mode)
# Mode: Run Once for Each Item
data = _item.get("json", {})
raw_tags = data.get("tags", "")
# Transform comma-separated string to deduplicated sorted list
tag_list = sorted(list(set(t.strip().lower() for t in raw_tags.split(",") if t.strip())))
return {
"json": {
"product_id": data.get("product_id"),
"normalized_tags": tag_list,
"tag_count": len(tag_list)
}
}
Cloud vs Self-Hosted Environment Constraints
n8n Cloud
- Runs in a strict sandbox where
import statements are disabled (even standard library modules like re, math, json, datetime cannot be imported).
- All transformations must use pure built-in Python syntax, string manipulation, dictionary/list methods, and mathematical operators.
Self-Hosted n8n
- Runs Python via dedicated task runner sidecar containers (
n8n-task-runners).
- Importing standard library or external packages (e.g.
pandas, requests, numpy) requires:
- Installing packages into the runner container image.
- Setting Python runner allowlist environment variables on the task runner:
N8N_RUNNERS_STDLIB_ALLOW=* (or specific standard-library modules like re,math,json,datetime)
N8N_RUNNERS_EXTERNAL_ALLOW=pandas,numpy,requests (for third-party installed packages)
Progressive Disclosure & Reference
Safety & Governance
- Always use
.get() with safe defaults when accessing dictionary keys to prevent unhandled KeyError crashes.
- Never execute dynamic untrusted string code using
eval() or exec().
Completion Evidence
- Code node executes cleanly in n8n 2.x without runtime syntax errors.
- Output matches the required
[{"json": {...}}] or {"json": {...}} contract.
1---2name: "n8n-code-python"3description: "Write, debug, and optimize Python transformations in n8n 2.x native Python Code nodes using _items and _item data structures, handling Cloud sandbox constraints and self-hosted runner environments. Use when writing Python transformations or debugging n8n 2.x Python Code nodes."4source: "community_canonical"5risk: "unknown"6license: "not_declared_upstream"7metadata:8 source: https://skillmd.com/skills/revrebel/n8n-code-python9---1011# n8n Native Python Code Node (n8n 2.x)1213Write reliable, performant data transformations in n8n 2.x native Python Code nodes across n8n Cloud and self-hosted environments.1415## When to Use1617Use this skill when:18- Writing custom Python transformation logic inside n8n Code nodes (Language: Python).19- Processing workflow items using n8n 2.x native Python data structures (`_items` and `_item`).20- Navigating runtime constraints between n8n Cloud (pure built-in execution) and self-hosted n8n (task runner images with custom packages).21- Debugging Python syntax errors, item key access, or return format rejections in n8n.2223Do not use this skill for:24- Writing schema-constrained AI Custom Code Tools for LangChain/AI Agent nodes (use `n8n-code-tool`).25- Writing JavaScript Code nodes or utilizing n8n JS-specific helpers (`$helpers`, Luxon, `$jmespath`).2627## Prerequisites2829- n8n version 2.0+ with Native Python execution mode active.30- Defined input dataset from upstream trigger or action node.3132## Execution Model & Data Structures3334In n8n 2.x native Python, data is exposed via two built-in variables depending on the selected execution mode:3536| Mode | Variable | Description |37|---|---|---|38| **Run Once for All Items** | `_items` | List of item dictionaries: `[{"json": {...}}, ...]` |39| **Run Once for Each Item** | `_item` | Current item dictionary: `{"json": {...}}` |4041> [!NOTE]42> Native Python in n8n 2.x does **not** support legacy Pyodide objects (`_input.all()`, `_input.first()`, `_input.item`) or global `$node` helpers. For legacy Pyodide instances (n8n 1.x), see the [Legacy Pyodide Compatibility Guide](./references/LEGACY_PYODIDE_COMPATIBILITY.md).4344### Return Format Contract4546- **Run Once for All Items Mode**: Must return a list of dictionaries with `"json"` keys (e.g. `[{"json": {...}}]`) or a list of flat dictionaries (n8n will wrap them into `{"json": ...}`).47- **Run Once for Each Item Mode**: Must return a single dictionary with a `"json"` key (e.g. `{"json": {...}}`) or a single flat dictionary.4849---5051## Code Examples5253### Example 1: Batch Processing & Normalization (All Items Mode)5455```python56# Mode: Run Once for All Items57results = []5859for item in _items:60 data = item.get("json", {})61 cleaned_record = {62 "user_id": str(data.get("id", "")).strip().upper(),63 "email": str(data.get("email", "")).strip().lower(),64 "gross_amount": round(float(data.get("amount", 0.0)), 2),65 "is_active": bool(data.get("status") == "active"),66 }67 results.append({"json": cleaned_record})6869return results70```7172### Example 2: Per-Item Transformation (Each Item Mode)7374```python75# Mode: Run Once for Each Item76data = _item.get("json", {})77raw_tags = data.get("tags", "")7879# Transform comma-separated string to deduplicated sorted list80tag_list = sorted(list(set(t.strip().lower() for t in raw_tags.split(",") if t.strip())))8182return {83 "json": {84 "product_id": data.get("product_id"),85 "normalized_tags": tag_list,86 "tag_count": len(tag_list)87 }88}89```9091---9293## Cloud vs Self-Hosted Environment Constraints9495### n8n Cloud96- Runs in a strict sandbox where `import` statements are disabled (even standard library modules like `re`, `math`, `json`, `datetime` cannot be imported).97- All transformations must use pure built-in Python syntax, string manipulation, dictionary/list methods, and mathematical operators.9899### Self-Hosted n8n100- Runs Python via dedicated task runner sidecar containers (`n8n-task-runners`).101- Importing standard library or external packages (e.g. `pandas`, `requests`, `numpy`) requires:102 1. Installing packages into the runner container image.103 2. Setting Python runner allowlist environment variables on the task runner:104 - `N8N_RUNNERS_STDLIB_ALLOW=*` (or specific standard-library modules like `re,math,json,datetime`)105 - `N8N_RUNNERS_EXTERNAL_ALLOW=pandas,numpy,requests` (for third-party installed packages)106107---108109## Progressive Disclosure & Reference110111- [Legacy Pyodide Compatibility Guide](./references/LEGACY_PYODIDE_COMPATIBILITY.md): Reference for legacy n8n 1.x / Pyodide syntax migration (`_input.all()`).112113---114115## Safety & Governance116117- Always use `.get()` with safe defaults when accessing dictionary keys to prevent unhandled `KeyError` crashes.118- Never execute dynamic untrusted string code using `eval()` or `exec()`.119120## Completion Evidence121122- Code node executes cleanly in n8n 2.x without runtime syntax errors.123- Output matches the required `[{"json": {...}}]` or `{"json": {...}}` contract.