# TypeError: 'NoneType' object is not subscriptable (Python)

Raised on a line that uses square brackets (x[0], x['key'], x[1:]) when x is None. Python 3.11 and later underline the failing sub-expression with carets, which tells you which value was None on a chained line.

```
Traceback (most recent call last):
  File "/srv/app/report.py", line 22, in <module>
    send_summary(load_user(42))
  File "/srv/app/report.py", line 15, in send_summary
    to = user["email"]
         ~~~~^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
```

## Quick fix

Find which value on the failing line is None (the carets point at it on Python 3.11+), then trace back to the call that produced it. Handle the empty case explicitly with if value is None, and fix functions that fall off the end without a return statement.

1. Use the caret markers, or split the line, to find which object is None.
2. Trace that variable back to the call that assigned it.
3. Make every branch of a value-returning function end in a return.
4. Handle not-found explicitly: if row is None, return early or raise a clear error.
5. Don't assign the result of list.sort(), list.reverse() or random.shuffle().

```python
# Wrong: sort() sorts in place and returns None
scores = scores.sort()
top = scores[0]  # TypeError

# Right
scores.sort()          # or: scores = sorted(scores)
top = scores[0]

row = cur.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone()
if row is None:
    raise LookupError(f"user {user_id} not found")
email = row[0]
```

## Why it happens

### Function returns None on some path

A function returns a dict in the happy path but simply ends (implicitly returning None) when a condition fails or an exception is caught and logged. The caller indexes the result without knowing a None can come back.

### Assigning the result of an in-place method

list.sort(), list.reverse(), list.append(), dict.update() and random.shuffle() modify the object and return None. items = items.sort() replaces your list with None, and the next items[0] fails.

### Lookup that found nothing

dict.get(), os.environ.get(), re.match() and re.search(), cursor.fetchone() and ORM .first() all return None for a miss. Code written against test data that always matched breaks on the first real miss.

### null in JSON data

json.loads turns null into None. data['user']['name'] fails when the API sends "user": null, even though the key exists, so a key check alone does not protect you.

### Decorator that drops the return value

A wrapper that calls func(*args, **kwargs) without returning its result makes every decorated function return None. Every caller that indexes the result fails at once, often right after someone adds logging or timing.

## Other fixes

- Annotate return types as Optional[...] and run mypy or pyright so unchecked None access is flagged before runtime.
- For optional nested JSON, read defensively: (data.get('user') or {}).get('name').
- Write regex code as m = re.search(...) then if m: value = m[1], never re.search(...)[1].

## Same error, other wording

- `TypeError: 'NoneType' object has no attribute '__getitem__'`
- `TypeError: 'NoneType' object does not support item assignment`

## Sources

- [Python: Built-in exceptions (TypeError)](https://docs.python.org/3/library/exceptions.html)
- [Python tutorial: More on lists (methods that return None)](https://docs.python.org/3/tutorial/datastructures.html)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/nonetype-not-subscriptable
