alphanumeric
alphanumeric

Reputation: 19329

How to verify Class attribute or method exists

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.

Upvotes: 0

Views: 1182

Answers (2)

anon582847382
anon582847382

Reputation: 20361

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.

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251368

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.

Upvotes: 1

Related Questions