Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any alternative way to check if there is any attribute in python?

a = SomeClass()
if hasattr(a, 'property'):
        a.property

Is this the only way to check if there is a property or not? Is there any other way to do the same thing?

like image 331
shibly Avatar asked Jan 29 '12 22:01

shibly


1 Answers

You could just use the property and catch the AttributeError exception if it doesn't exist. But using hasattr is also a reasonable approach.

A potential issue with catching the exception is that you can't easily distinguish between the attribute not existing, and it existing but when you call it some code is run and that code raises an AttributeError (perhaps due to a bug in the code).

You may also want to look at these related questions for more information on this topic:

  • How to know if an object has an attribute in Python
  • hasattr() vs try-except block to deal with non-existent attributes
like image 188
Mark Byers Avatar answered Nov 03 '22 01:11

Mark Byers