Python Reference ยท Exceptions
Python AttributeError
Reference for Python AttributeError: why a missing attribute or method raises it, the name and obj fields, None pitfalls, getattr() and hasattr() fixes.
AttributeError is raised when you read, assign or delete an attribute that an object does not have, or when an assignment is not allowed. The message names the type and the attribute: 'str' object has no attribute 'push'.
It is a subclass of Exception. The most common real-world cause is a value that is None (or another unexpected type) where you expected an object, because a function returned nothing.
text = "hello" text.push("!") # AttributeError: 'str' object has no attribute 'push'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
try: value = obj.attribute except AttributeError as error: print(error.name, error.obj)
| Name | Description |
|---|---|
name |
The attribute name that was requested (added in Python 3.10). |
obj |
The object that was searched (added in Python 3.10). |
Raises when: attribute lookup finds nothing in the instance, its class or its bases, __getattr__ is not defined or raises it, or an assignment targets a read-only attribute or an object without a __dict__ and without the slot.
Usage notes
Noneis the usual culprit. Methods that change a list in place (sort(),append(),reverse()) returnNone, and so doesre.search()when nothing matches. Check the value orif match:before using it.- Typos and wrong case. Attribute names are case sensitive:
"abc".Upper()fails. Recent Python versions add a "Did you mean" hint to the traceback, but not tostr(error). - Wrong type. Calling a list method on a string or a string method on bytes gives this error. Print
type(value)to see what you really have. - Use
getattr(obj, name, default)to read an optional attribute andhasattr(obj, name)to test for one. Note thathasattr()catches onlyAttributeError, so other errors from properties still escape. - Modules count too. A local file named like a standard module (
random.py) shadows it, and thenrandom.randintraisesAttributeError: module 'random' has no attribute 'randint'. - Instance attributes must exist first. Reading
self.countin a method before__init__assigned it fails; initialize every attribute in__init__. __slots__and immutables. Classes with__slots__reject new attribute names; tuples, ints and strings do not allow attribute assignment at all.__getattr__is called only after normal lookup fails. RaiseAttributeErrorfrom it (notKeyError) sogetattr()defaults andhasattr()keep working.- A property that raises
AttributeErrorinternally can be confusing: Python may fall back to__getattr__and report a missing attribute that actually exists.
Related
NameError,TypeError, the exception hierarchygetattr(),hasattr()- Lessons: Exceptions, Classes