Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking existence and if exists, is a certain value

Tags:

python

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
like image 765
freb Avatar asked Aug 09 '12 22:08

freb


2 Answers

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'.

like image 137
chepner Avatar answered Sep 28 '22 07:09

chepner


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
like image 43
Mike Sherov Avatar answered Sep 28 '22 08:09

Mike Sherov