I frequently need to check if an instance of a class has a property and if that property exists, make a comparison with its value. Is there no way to do it besides the following?
if house.garage:
if house.garage == '3 car':
# do something with house.garage
Instead of using the dot notation, you can make a call to getattr
, which can return a default value if the named attribute does not exist:
if getattr(house, 'garage', "") == '3 car':
# proceed
If house
does not have an attribute named 'garage', getattr
just needs to evaluate to something that does not equal '3 car'.
You can "consolidate conditional expression" as outlined by Martin Fowler here: http://sourcemaking.com/refactoring/consolidate-conditional-expression#permalink-15
Essentially, any if statement that contains another if statement inside it is really just 1 if statement with an and in between!
if house.garage:
if house.garage == '3 car':
# do something with house.garage
becomes
if house.garage and house.garage == '3 car':
# do something with house.garage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With