How to know if an object has an attribute in Python

0 votes

Is there a way in Python to determine if an object has some attribute? For example:

>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'

How can you tell if a has the attribute property before using it?

Dec 2, 2020 in Python by Roshni
• 10,520 points
422 views

1 answer to this question.

0 votes

Try hasattr():

if hasattr(a, 'property'):
    a.property

The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block

answered Dec 2, 2020 by Gitika
• 65,910 points

Related Questions In Python

0 votes
1 answer

Getting AttributeError: 'module' object (scipy) has no attribute 'misc' in Python. How to solve this?

>>> import scipy >>> scipy.misc Traceback (most recent call ...READ MORE

answered Dec 24, 2018 in Python by Nymeria
• 3,560 points
8,945 views
0 votes
5 answers

how to exit a python script in an if statement

Instead of using the normal UTF-8 encoding, ...READ MORE

answered Jul 4, 2023 in Python by bodymist
• 140 points
349,544 views
0 votes
1 answer

How to check the memory usage of an object in python

Hi, @Roshni, You can use this code below: import ...READ MORE

answered Jun 26, 2020 in Python by Gitika
• 65,910 points
3,193 views
+4 votes
7 answers
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,072 views
0 votes
1 answer
0 votes
1 answer

How to insert an object at a given index in Python?

Hi, @Roshni, I will explain to you with ...READ MORE

answered Jun 24, 2020 in Python by Gitika
• 65,910 points
1,033 views
0 votes
1 answer

How to save an image locally using Python in which we already know the URL address?

Hi, @Roshni, The following code is used to ...READ MORE

answered Jun 26, 2020 in Python by Gitika
• 65,910 points
1,565 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP