I had a bit of conditional code that looked like this:
if self.above and self.above.author and self.above.author.username!=self.author.username:
"notify above.author that someone has replied to their comment"
But if there is no self.above or if either of the comments has no author then I get an error like:
AttributeError: 'NoneType' object has no attribute 'author'
or
AttributeError: 'NoneType' object has no attribute 'username'
so I can check first before looking for those attributes
if self.above:
if self.above.author:
if self.author:
if self.author.username!=self.above.author.username:
"notify about response"
else:
"notify about response"
but with all the extra ifs and the duplication of the “notify about response” code, the number of lines is more than doubled. There are a lot of times when this problem arises, so if I use the above solution it’s going to mean fifty extra lines of code to check a few simple conditions.
Is there a better way to handle this?
Factor all the object attribute lookups out into a function that handles the missing attributes gracefully. If
self.above.author.usernameis missing, that’s the same situation asself.abovebeing missing as far as you’re concerned — you don’t care where you ran out of runway, just that you did at some point.You can even put the
resolve()method somewhere on a base class, then it’s a nicer: