Verification of existence and, if exists, is a specific value

I often need to check if an instance of a class has a property, and if this property exists, compare its value. Is there no way to do this other than the following?

if house.garage:
    if house.garage == '3 car':
        # do something with house.garage
+5
source share
2 answers

You can "consolidate the conditional expression" as described by Martin Fowler here: http://sourcemaking.com/refactoring/consolidate-conditional-expression#permalink-15

Essentially, any if statement containing another if statement inside it is really only 1 if there is an operator with a and 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
+5
source

getattr, , :

if getattr(house, 'garage', "") == '3 car':
    # proceed

house "", getattr , "3 ".

+6

All Articles