Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using hasattr and not hasattr in python

Tags:

python

I need to use python hasattr for my very specific purpose. I need to check that an object is having an attribute, and not having another attribute.

Consider the class object named model, I need to check that whether it is having an attribute called domain_id:

if hasattr(model, 'domain_id'):

I also need to check for one more condition that it shouldn't have attribute called type.

if not hasattr(model, 'type'):

How to combine the two checks here?

like image 738
iamnewuser Avatar asked Oct 14 '25 09:10

iamnewuser


1 Answers

Just combine the two conditions with and:

if hasattr(model, 'domain_id') and not hasattr(model, 'type'):

The if block will only execute if both conditions are true.

like image 200
Martijn Pieters Avatar answered Oct 17 '25 00:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!