Take a look to this code:
>>> class c(object):
... pass
...
>>> a=c()
>>> if a.b.c:
... print 'hello'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'c' object has no attribute 'b'
Quiet! this is not the question. Please, continue reading:
When someone develops enterprise software (with django for example) must write business rules. This rules looks like
if invoice.customer.adress.country in ...:
invoice.makeSomeSpecialOffer()
But some times, one of the objects involveds on expression don't exists. Then, to avoid errors I sould rewrite sentence as:
if invoice.customer and
invoice.customer.adress and
invoice.customer.adress.country and
invoice.customer.adress.country in ...
This is less readable! (also you can try with hasattr but is alse less readable).
My work arround is enclose if statement into a try, but there is a more elegant or pythatonic way to avoid this kind of errors? Which is your favorite technique?