---
title: Python Code
description: Run your own Python code on the incoming items, in a sandbox in the browser
---

*Formerly **Code**. The step was renamed in AWFlow 0.9; searching for the old name still finds it.*

Run your own Python code on the incoming items when no other step does what you need. For JavaScript, use [JavaScript Code](/nodes/builtin/core/javascript-code/), which starts faster.

## What it does

Python Code runs your Python (Python 3 with its standard library, in the browser) and passes on the value of its **last line**. Anything you `print()` appears in the run's activity log. The code runs in an isolated sandbox: no network, no access to the page or your stored data, and a 30-second time limit. The first run after a pause takes a few seconds while Python starts.

At the top of **Setup**, a green card says what the step can reach: **What it touches: nothing outside this step**. No internet (use [HTTP Request](/nodes/builtin/core/http-request/) for calls), no web pages, tabs or your files, no connections or stored data, and how long it may run (*Stops after …*), with **Change limits** (the step's **Time limit**). In **Ready to run** and on a Marketplace listing, the step shows as a calm grey *Runs code in a sandbox* row, not a warning.

Code is never searched for `{{ }}`: `f"{{name}}"` and `{{ $input.x }}` reach Python exactly as written (the editor warns *Looks like an expression: use items instead*).

### Python Code version 2 (new steps in AWFlow 0.9)

Pick how it runs with **Run**:

* **Once for all items** (default): one interpreter for the whole list, so 50 items take seconds, not minutes. `items` is the list of items (dicts), `input` the first item. The last line must be a **list**: each element becomes one item.
* **Once for each item**: `input` is the current item and `item_index` its position. A dict result **is** the new item; any other value becomes `{ "result": value }`.

Both modes also get `workflow` and `execution` dicts (ids, name, run mode).

```python title="Once for all items"
# items is a list of dicts; the last line is the output
[{**i, "total": i["qty"] * i["price"]} for i in items]
```

```python title="Once for each item"
# input is the current item; the last line is the new item
{**input, "total": input["qty"] * input["price"]}
```

Errors name the line and the item: `Line 4, item 3: KeyError: 'email'`. The full traceback stays in the activity log. A run that's too long stops with `Stopped after 30 s (time limit)`.

### Steps saved before AWFlow 0.9

They run once per item, `{{ }}` in the code is replaced before it runs, and the value comes out under `result`. The sections below describe them. **Update** in the step's header moves to version 2 and sets **Once for each item**, so the same code gives the same items.

## When to use it

* A calculation or text transformation that would take many nodes otherwise.
* Reshape a complex structure: regroup a list, merge fields, count values.
* Parse an unusual format with Python's standard library (`re`, `json`, `csv`, `datetime`, `statistics`).

For simple field changes, [Edit Fields](/nodes/builtin/datatransformation/editfields/) or [Math](/nodes/builtin/datatransformation/math/) need no code. To call an API, use [HTTP Request](/nodes/builtin/core/http-request/). For counts and sums per group, [Summarize items](/nodes/builtin/datatransformation/summarize/) needs no code.

## Inputs and settings

### Reading `input` (steps saved before 0.9)

`input` is a normal Python value (a dict, a list or a single value), the same data that `{{ $input }}` holds in other nodes. Its shape depends on how many nodes are connected:

* **One node connected.** `input` is that node's output as it produced it:

  ```python
  # input == {"selectionText": "Hello", "triggerType": "contextmenu"}
  input["selectionText"]  # -> "Hello"
  ```

* **Several nodes connected.** `input` is a dict keyed by each source node's label, so you can tell them apart:

  ```python
  # input == {
  #   "Get Selected Text": {"selection": "Hello"},
  #   "Http Request": {"data": {...}},
  # }
  input["Get Selected Text"]["selection"]  # -> "Hello"
  ```

  A node with a blank label is keyed by its id. If two nodes share a label, both keys get a short suffix, such as `"Http Request [a1b2]"`.

* **Nothing connected.** `input` is an empty dict, `{}`, so `input.get("selectionText", "")` is always safe.

### Returning a value

Put the value you want to pass on as the last line, on its own. An assignment on the last line returns nothing.

```python
words = input.get("selectionText", "").split()
{
    "words": len(words),
    "longest": max(words, key=len) if words else "",
}
```

## Outputs

Version 2 returns your items as they are. In steps saved before 0.9, read the returned value downstream with `{{ $input.result }}`, or a field of it with `{{ $input.result.words }}`. The value travels as JSON: dicts become objects, sets become lists, integers too large for JSON become text, and values with no JSON form (such as class instances) are returned as their text form.

## Dependencies and credentials

None. This node needs no connection and has no slots for other nodes.

## Example workflow

Count the words in text you select on a page:

1. [Context Menu](/nodes/builtin/trigger/contextmenu/) trigger, **Menu Contexts** `Selection`.
2. Python Code, **Once for each item**, ending with `{**input, "words": len(input.get("selectionText", "").split())}`.
3. [Browser Notification](/nodes/extension/browsernotification/), **Title** `Word count`, **Message** `{{ $input.words }} words`.

## Common issues

* **"Network access is disabled in the Code node sandbox. Use an HTTP Request node to call APIs."** The code tried to fetch something. Fetch it with [HTTP Request](/nodes/builtin/core/http-request/) before this step and read the response from `input`.
* **"Stopped after 30 s (time limit)"**. The code ran longer than 30 seconds (start-up included), often an endless loop. Simplify it or split the work across items.
* **"Once for all items" code must end with a list.** End with a list, for example `items` or a list comprehension.
* **`result` is `null`.** The last line is an assignment, a `print()` or `None`. End with the value itself, for example `out` on its own line.
* **`ModuleNotFoundError`.** Only the Python standard library is available; packages such as `numpy` or `requests` cannot be installed.
* **`KeyError` on `input[...]`.** The field is not there, or several nodes are connected and `input` is keyed by node label. Use `print(input)` to see its shape in the activity log.

## Related nodes

* [Edit Fields](/nodes/builtin/datatransformation/editfields/): set or rename fields without code.
* [JavaScript Code](/nodes/builtin/core/javascript-code/): the same in JavaScript.
* [HTTP Request](/nodes/builtin/core/http-request/): call APIs, which code steps cannot do.
* [JSON](/nodes/builtin/datatransformation/json/): reshape JSON without code.
* [Test helper](/nodes/builtin/core/debug/): make sample data while you build.