snippetpythonCritical
How can I check if an object has an attribute?
Viewed 0 times
howobjecthasattributecancheck
Problem
How do I check if an object has some attribute? For example:
How do I tell if
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "", line 1, in
AttributeError: SomeClass instance has no attribute 'property'
How do I tell if
a has the attribute property before using it?Solution
Try
See zweiterlinde's answer, which offers good advice about asking forgiveness! It is a very Pythonic approach!
The general practice in Python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than
hasattr():if hasattr(a, 'property'):
a.propertySee zweiterlinde's answer, which offers good advice about asking forgiveness! It is a very Pythonic approach!
The general practice in Python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than
hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.Code Snippets
if hasattr(a, 'property'):
a.propertyContext
Stack Overflow Q#610883, score: 3521
Revisions (0)
No revisions yet.