How to check existence of an attribute in an object in python?

+1 vote
asked Aug 1, 2017 by Hitesh Garg (251 points)  
edited Aug 11, 2017 by Hitesh Garg

I have to determine whether some object has an attribute or not. I am working on a jira application to perform some tasks and when I get the information of the worklog author name it gives below mentioned error in some cases.
type object 'PropertyHolder' has no attribute 'displayName'

How to check if the has displayName property or not?

1 Answer

+1 vote
answered Aug 11, 2017 by Rahul Singh (328 points)  
selected Aug 11, 2017 by Hitesh Garg
Best answer

hasattr is a method used for checking the existence of an attribute in an object.

Example -

if hasattr(objRef, 'propName'):

You can simply use the code below to check the existence of attribute 'displayname' and if it doesn't exists then use value of name as there is always a name attribute with this field you have mentioned in the question.

display_name = if hasattr(, "displayName") else
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.