BugHunt

AttributeError: 'str' object has no attribute

You called a method or read an attribute that this kind of object does not have: a list method on a string, a typo, or an attribute your own class never stored.

PythonType errors

What it means

Each object has only the attributes of its type. 'str' object has no attribute 'reverse' means reverse exists (on lists), just not on strings. With your own class, 'Student' object has no attribute 'name' usually means __init__ never stored it on self. (When the type is 'NoneType', the value was None: that has its own guide.)

Common causes

1. A method that belongs to a different type

Strings, lists and dicts each have their own methods.

Breaks

word.reverse()   # lists have reverse(), strings do not

Works

word[::-1]

2. An attribute never stored in __init__

name = name only sets a local variable that disappears when __init__ returns.

Breaks

def __init__(self, name):
    name = name

Works

def __init__(self, name):
    self.name = name

3. A typo or the wrong name

Python does not guess; uppercase is not upper.

Breaks

text.uppercase()

Works

text.upper()

4. Text where you expected parsed data

A JSON response is a string until you parse it.

Breaks

data = response_text
data.get("id")

Works

data = json.loads(response_text)
data.get("id")

How to find it in your own code

Print type(obj) and dir(obj) just before the failing line: the first shows which object you really have, the second lists what it supports. For your own class, check that every attribute is assigned to self.<name> in __init__.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors