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.

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.
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:
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:
| Call | Returns | Common mistake |
|---|---|---|
list.sort() | None | x = y.sort() |
list.append(x) | None | x = y.append(1) |
dict.get(k) without default | None | assuming the key exists |
re.match(p, s) on no match | None | calling .group() on it |
re.search(p, s) on no match | None | same |
os.environ.get("X") | None | int(os.environ.get("PORT")) |
cursor.fetchone() | None | unpacking it directly |
input.strip() on empty stdin | "", not None | different error, same family |
Key Comparison Table
The sibling errors tell you which operation met None, which is often enough to identify the call:
| Message | Operation attempted | Typical source |
|---|---|---|
'NoneType' object has no attribute 'X' | attribute access | any call returning None |
'NoneType' object is not subscriptable | x[key] | API field, .get() result |
'NoneType' object is not callable | x() | config value named like a function |
'NoneType' object is not iterable | for or unpacking | missing list default |
argument of type 'NoneType' is not iterable | in check | if "a" in maybe_none |
unsupported operand type(s) for +: 'NoneType' and 'int' | arithmetic | counter never initialised |
Four repairs, ranked by how much they protect the rest of the program:
| Repair | Code | Behaviour on missing value | Best for |
|---|---|---|---|
| Explicit default | config.get("k", "") | continues with a value | optional settings |
| Guard and raise | if x is None: raise ValueError(...) | fails loudly with context | required input |
| Type-annotated optional | def f() -> Optional[str] | mypy flags every use | large codebases |
| Early return | if x is None: return | skips the work | handlers, loops |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Every code path must return
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:
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 NoneCallers 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
port = os.environ.get("PORT") or 8000 # fine for strings, wrong for 0
timeout = config.get("timeout") or 30 # 0 becomes 30, silentlyor treats 0, "", [] and False as missing. When zero is a legitimate value, use an explicit check:
timeout = config.get("timeout")
if timeout is None:
timeout = 30Python 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
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
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:
from dataclasses import dataclass
@dataclass
class Job:
id: int
owner: "Owner | None" = NoneThen 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"
row = cursor.fetchone()
if row is None:
raise LookupError("user not found")
user_id, email = rowfetchone() 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
python -X dev script.py # enables development mode warnings
python -m pdb script.py # break at the failing lineIn 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 documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
Python 3.14 PEP 649: NameError from lazy annotations
Annotations are no longer strings. A NAME only imported under TYPE_CHECKING now raises when FastAPI or Pydantic reads the signature.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.