0

I apology ahead if this is a repost. I'm currently using a following "self-invented" verification method to check if a Class's attribute (or method) exists before trying to access it:

if 'methodName' in dir(myClassInstance): result=myClassInstance.methodName()

I wonder if there is a more common "standardized" way of doing the same.

Bach
  • 6,145
  • 7
  • 36
  • 61
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • possible duplicate of [How to know if an object has an attribute in Python](http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python) – DNA Mar 29 '14 at 20:18

2 Answers2

2

Use hasattr. It returns True if a given object has a given name as an attribute, else False:

if hasattr(myClassInstance, 'methodName'):
    ...  # Whatever you want to do as a result.
anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • Thanks guys! Do you think there are any side-effects if I would keep using if 'methodName' in dir(myClassInstance)? How much more "reliable" hasattr() is? – alphanumeric Mar 29 '14 at 20:18
  • @Sputnix Although, you will have to wait fifteen minutes before it allows you, unfortunately. :) – anon582847382 Mar 29 '14 at 20:24
1

Use hasattr(myClassInstance, 'methodName').

Another possibility is to just try accessing it and handle the exception if it's not there:

try:
   myClassInstance.methodName()
except AttributeError:
   # do what you need to do if the method isn't there

How you'll want to handle this depends on why you're doing the check, how common it is for the object to not have that attribute, and what you want to do if it's not there.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384