Re:PEP 505: Bringing None-Aware Operators to Python
by singularity2001 on Monday August 13, 2018 @03:23AM
(#17748534)
I don't think the existing pythonic way is not too verbose:
if node and node.child and node.child.attribute:
…
Re:PEP 505: Bringing None-Aware Operators to Python
by singularity2001 on Monday August 13, 2018 @03:26AM
(#17748546)
for nested loop you can do
for child in node.children or []:
for attrib in child.attributes or []:
…
Re:PEP 505: Bringing None-Aware Operators to Python
by Doxin on Monday August 13, 2018 @08:10AM
(#17749444)
That's generally considered unpythonic though. A more pythonic way to write that is
for child in node.children if node.children else []:
for attrib in child.attributes if child.attributes else []:
...
Which, granted, is a lot more verbose and probably not any more readable but at least it's not abusing the or operator.
You could surround the nested lookups in try/except and catch the AttributeError, but that could mask other errors - for instance, if you misspelled the name of one of the nested attributes (arguably, it would be better if trying to look up an attribute on None raised a different exception, rather than AttributeError).