AttributeError Examples
Short, runnable programs that show python attributeerror in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python AttributeError lesson.
1Calling a list method on a string
Splitting text gives you a list, but forgetting split() leaves a string. The error names the real type, so you can tell what happened.
line = "pen,book,lamp"
try:
line.append("bag")
except AttributeError as err:
print("AttributeError:", err)
items = line.split(",")
items.append("bag")
print(items)Expected outputAttributeError: 'str' object has no attribute 'append'
['pen', 'book', 'lamp', 'bag']
2Using the result of an in-place method
append(), sort(), reverse() and update() change the object and return None. Chaining another method after them fails.
cart = ["pen"]
try:
cart.append("book").append("lamp")
except AttributeError as err:
print("AttributeError:", err)
cart.append("lamp")
print(cart)
prices = [30, 10, 20]
cheapest = sorted(prices)[0]
print(cheapest, prices)Expected outputAttributeError: 'NoneType' object has no attribute 'append'
['pen', 'book', 'lamp']
10 [30, 10, 20]
3re.match returns None when nothing matches
A pattern search that finds nothing gives None, so calling .group() on it raises AttributeError. Test the match first.
import re
def order_number(text):
match = re.search(r"#(\d+)", text)
if match is None:
return None
return int(match.group(1))
print(order_number("Order #482 shipped"))
print(order_number("No number here"))
try:
re.search(r"#(\d+)", "missing").group(1)
except AttributeError as err:
print("AttributeError:", err)Expected output482
None
AttributeError: 'NoneType' object has no attribute 'group'
4A class that forgot to save an attribute
Two constructors for the same data. The broken one never stores balance on self, so reading it fails later, far from the cause.
class BrokenAccount:
def __init__(self, owner, balance):
self.owner = owner
balance = balance
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
for cls in (BrokenAccount, Account):
account = cls("Asha", 120)
try:
print(cls.__name__, account.owner, account.balance)
except AttributeError as err:
print(cls.__name__, "->", err)Expected outputBrokenAccount -> 'BrokenAccount' object has no attribute 'balance'
Account Asha 120
5getattr() with a default for optional fields
When objects may or may not have an attribute, getattr(obj, name, default) reads it safely. Use it for genuinely optional data.
class Product:
def __init__(self, name, discount=None):
self.name = name
if discount is not None:
self.discount = discount
catalog = [Product("pen"), Product("book", discount=15), Product("lamp")]
for product in catalog:
discount = getattr(product, "discount", 0)
print(f"{product.name}: {discount}% off")Expected outputpen: 0% off
book: 15% off
lamp: 0% off
6Listing what an object can do
dir() shows every attribute. Filtering out the names that start with an underscore leaves the methods you would normally call.
text = "python"
numbers = [3, 1, 2]
str_methods = [n for n in dir(text) if n.startswith("s") and not n.startswith("_")]
list_methods = [n for n in dir(numbers) if not n.startswith("_")]
print(str_methods)
print(list_methods)
print("append" in dir(text), "append" in dir(numbers))Expected output['split', 'splitlines', 'startswith', 'strip', 'swapcase']
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
False True
Practise next
Python AttributeError exercises → Back to the lesson
Python Exceptions: try, except, else and finally examplesPython TypeError: What It Means and How to Fix It examplesPython NameError examplesPython Classes and Objects examples