Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: AttributeError: 'NoneType' object has no attribute

Something returned None where you expected a value. Find the call, decide what a missing value means, and make the return type say so.

~4 min readPython
#python#attributeerror#none#debugging
Bold white headline reading NONETYPE with a Python object crate holding an amber empty value plate and a cyan attribute label beside it.

Introduction & Quick Summary

The traceback ends with a message about a type, not about your code:

AttributeError: 'NoneType' object has no attribute 'strip'

Quick answer: some expression you expected to return text returned None instead.

python
name = config.get("name") if name is None: name = "anonymous" print(name.strip())

NoneType is the type of the single value None, and None has almost no attributes — no strip, no split, no group, no get. The error is never "None is broken"; it is "a function returned nothing where you expected a value". Python makes that easy to do by accident because every function without an explicit return returns None, and several built-in methods return None on purpose. Finding which call returned it is the whole job, and the traceback's last line already points at the attribute access.

Core Mechanics, Signatures & Reproducible Setup

Reproduce the shape that produces this error most often:

python
def load_settings(path): if os.path.exists(path): return json.load(open(path)) # no else: implicit None settings = load_settings("config.json") print(settings["name"].strip()) # AttributeError: 'NoneType' object has no attribute 'strip'

Three lines of evidence narrow it down. The traceback line number names the attribute access. The expression before the dot is the candidate. If that expression is a call chain such as user.get("name").strip(), each link can return None.

The built-in and library calls that return None on purpose are worth memorising, because they are the source of most reports:

CallReturnsCommon mistake
list.sort()Nonex = y.sort()
list.append(x)Nonex = y.append(1)
dict.get(k) without defaultNoneassuming the key exists
re.match(p, s) on no matchNonecalling .group() on it
re.search(p, s) on no matchNonesame
os.environ.get("X")Noneint(os.environ.get("PORT"))
cursor.fetchone()Noneunpacking it directly
input.strip() on empty stdin"", not Nonedifferent error, same family

Key Comparison Table

The sibling errors tell you which operation met None, which is often enough to identify the call:

MessageOperation attemptedTypical source
'NoneType' object has no attribute 'X'attribute accessany call returning None
'NoneType' object is not subscriptablex[key]API field, .get() result
'NoneType' object is not callablex()config value named like a function
'NoneType' object is not iterablefor or unpackingmissing list default
argument of type 'NoneType' is not iterablein checkif "a" in maybe_none
unsupported operand type(s) for +: 'NoneType' and 'int'arithmeticcounter never initialised

Four repairs, ranked by how much they protect the rest of the program:

RepairCodeBehaviour on missing valueBest for
Explicit defaultconfig.get("k", "")continues with a valueoptional settings
Guard and raiseif x is None: raise ValueError(...)fails loudly with contextrequired input
Type-annotated optionaldef f() -> Optional[str]mypy flags every uselarge codebases
Early returnif x is None: returnskips the workhandlers, loops

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Every code path must return

python
from pathlib import Path import json def load_settings(path: Path) -> dict: if not path.exists(): return {} with path.open(encoding="utf-8") as fh: return json.load(fh)

Returning {} instead of falling off the end removes the error class entirely for this function. The with block also fixes the leaked file handle that json.load(open(path)) leaves behind — a second bug in the same line that surfaces later as "too many open files".

The annotation is part of the fix, not decoration. Writing -> dict tells a type checker that the function always produces a dict, so a later refactor that adds a return None branch is flagged at the definition instead of at every caller:

python
def find_user(email: str) -> dict | None: row = cursor.execute("select id, email from users where email = ?", (email,)).fetchone() return {"id": row[0], "email": row[1]} if row else None

Callers then have to decide what None means. That decision is the actual bug fix; the attribute error was only the symptom of it being skipped.

2. or is not a safe default

python
port = os.environ.get("PORT") or 8000 # fine for strings, wrong for 0 timeout = config.get("timeout") or 30 # 0 becomes 30, silently

or treats 0, "", [] and False as missing. When zero is a legitimate value, use an explicit check:

python
timeout = config.get("timeout") if timeout is None: timeout = 30

Python 3.8+ has dict.get(key, default) for the simple case, and := for the read-once pattern: if (name := config.get("name")) is None: ....

3. re.match and re.search return None

python
import re m = re.search(r"(?P<id>\d+)", line) if m is None: raise ValueError(f"no id in line: {line!r}") item_id = int(m.group("id"))

The tempting one-liner int(re.search(r"\d+", line).group()) works for every line until the first malformed one. re.findall returns [] instead of None, which is why conversions between the two functions change behaviour. Exercising a pattern against real lines in the regex tester before shipping catches the empty-match case cheaply.

4. Objects whose attributes are conditionally set

python
class Job: def __init__(self, payload: dict): self.id = payload.get("id") self.owner = payload["owner"] if "owner" in payload else None job = Job({"id": 1}) print(job.owner.email) # AttributeError: 'NoneType' object has no attribute 'email'

Two habits fix this class of bug. Declare attributes with types and defaults in one place so a reader can see which are optional, and use dataclasses with explicit Optional fields:

python
from dataclasses import dataclass @dataclass class Job: id: int owner: "Owner | None" = None

Then job.owner.email is a type error that a checker reports before the program runs, rather than an AttributeError at 3 a.m.

5. Database and HTTP clients return None for "no row"

python
row = cursor.fetchone() if row is None: raise LookupError("user not found") user_id, email = row

fetchone() returns None when the result set is empty; requests.get(...).json()["items"] can be None if the API sends null; response.json() itself raises on invalid JSON, which is a different error with a similar shape. Logging the raw body once — through the JSON formatter — prevents a long hunt through application code for a bug that lives in the response.

6. Debugging when the traceback is not enough

bash
python -X dev script.py # enables development mode warnings python -m pdb script.py # break at the failing line

In pdb, p locals() before the failing line shows which name is None, and w prints the stack so the caller that passed None is visible. For library code you cannot edit, python -X dev plus a temporary assert x is not None, name above the failing line converts a mystery into a named failure. When the traceback crosses a framework boundary — a template engine, a task queue, a web view — the handler in the stack often shows only AttributeError with no application frame. Logging the value just before the access (logger.debug("name=%r", name)) costs one line and answers the question in the next occurrence.

Common Compilation/Runtime Mistakes & Version Gotchas

Catching AttributeError to keep going. It also hides typos in attribute names and real API changes. Catch the specific error you expect, or check for None first.

Using hasattr chains as null checks. if hasattr(obj, "x") and obj.x: fails when x exists and is None. Use getattr(obj, "x", None).

Assuming str(None) is "". It is "None", which then flows into databases and filenames. Guard before formatting.

Mutable default arguments. def f(items=[]) shares one list across calls and produces a different, nastier family of bugs that often begins with a .append on None somewhere else.

Version notes. Python 3.10 added X | None syntax, and from __future__ import annotations makes the same syntax work in 3.7+. Python 3.11 rewrote attribute error messages to include attribute suggestions, which is why a typo now reads "Did you mean: 'strip'?" — helpful, but it also means the message no longer implies the type is wrong. mypy --strict and pyright both flag every unguarded use of an Optional, and turning either on for one module is the cheapest permanent fix for this error class.

Reference material: Built-in exceptions and Constants, including None.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.