AttributeError
is a built-in exception that occurs when you attempt to access a method or attribute that isn’t defined for the object in question.
You should handle this exception to ensure your code doesn’t crash. Catching an AttributeError
allows you to provide a graceful degradation or alternative solution when users try to access an attribute that’s missing.
AttributeError
Occurs When
NoneType
object due to uninitialized or improperly assigned variablesAttributeError
Can Be Used When
You should handle this exception to ensure your code doesn’t crash. Catching an AttributeError
allows you to provide a graceful degradation or alternative solution when users try to access a missing attribute.
AttributeError
Examples
An example of when the exception appears:
An example of how to handle the exception:
Every Python object will raise an AttributeError
when you attempt to access a non-existent attribute on it. When you need to implement custom logic, then you can edit .__getattr__()
accordingly before raising the error manually:
You could also provide fallback mechanisms for the lookup before raising the AttributeError
. Raising it manually also allows you to customize the error message.
AttributeError
How to Fix It
For example, say that you have a Pen
class with a .color
attribute:
The class works correctly with .color
but fails with .colour
. To fix the above code, you could customize the attribute lookup in .__getattr__()
before raising AttributeError
manually:
With these edits to Pen
, you users can now access the ._color
attribute with both .color
and .colour
:
At the same time, the class still raises an AttributeError
when you try to access a non-existent attribute.
Note that you need to manually raise AttributeError
in .__getattr__()
if you overwrite the default implementation with your custom logic. Otherwise, you break the default behavior of raising an AttributeError
when looking up a non-existent attribute.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4