6
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?

cola
  • 12,198
  • 36
  • 105
  • 165

4 Answers4

8

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:

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

Well, you can just try to access it and catch AttributeError in case it doesn't exist.

try:
    a.foo
except AttributeError:
    ...
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 1
    I haven't worked with much multithreading code, but it seems like this would also be the only threadsafe way to handle this. Is that correct? I mean, it seems like another thread could delete `a.foo` some time between `hasattr(a, 'foo')` and `a.foo` calls whereas this would be atomic. – Kirk Strauser Jan 29 '12 at 22:27
1

You could also use:

if 'property' in a.__dict__:
    a.property
Andrew Halloran
  • 1,518
  • 1
  • 14
  • 16
0

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

Febulix
  • 1
  • 2