Lingua-e
← Errors
Python

AttributeError: What It Means and How to Fix It

Error reference

AttributeError

Language

Python

Severity

Medium

When it happens

An AttributeError is raised in Python when you try to access or call an attribute (a property or method) that does not exist on an object.

Potential fixes

Use hasattr(obj, 'attr') or getattr(obj, 'attr', default) to check safely. Make sure all attributes are initialized in __init__. If the variable might be None, add a None check before accessing any attributes.

Deep dive

An AttributeError is raised in Python when you try to access or call an attribute (a property or method) that does not exist on an object. This typically means the object is not the type you expected, or the attribute was never defined.

Why it happens

  • Accessing an attribute that was never defined in __init__ or the class body.
  • Calling a method that does not exist on that particular type (e.g. .sort() on a tuple).
  • A variable holds None instead of the expected object.
  • Typo in the attribute name.

Potential fixes

Use hasattr(obj, 'attr') or getattr(obj, 'attr', default) to check safely. Make sure all attributes are initialized in __init__. If the variable might be None, add a None check before accessing any attributes.

Examples

Python

Code that triggers the error

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

user = User("Alice")
print(user.email)

Error output

Traceback (most recent call last):
  File "app.py", line 6, in <module>
    print(user.email)
AttributeError: 'User' object has no attribute 'email'

Fixed code

class User:
    def __init__(self, name, email=None):
        self.name = name
        self.email = email

user = User("Alice", email="alice@example.com")
print(user.email)  # alice@example.com

# Or check first:
print(getattr(user, "email", "not set"))

Practice in English

How would you explain an AttributeError to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free