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?
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?
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:
Well, you can just try to access it and catch AttributeError
in case it doesn't exist.
try:
a.foo
except AttributeError:
...
Not elegant either but for the sake of completeness using dir()
also works even when __dict__
is not defined for the object:
if 'property' in dir(a):
a.property
See also What's the biggest difference between dir()
and __dict__
in Python