4 ms·
I think a better example to show why you might want a ?. operator would involve nested lookups. If you have something like node.child.attribute.value, handling
by culturedsystems 8y ago
I think a better example to show why you might want a ?. operator would involve nested lookups. If you have something like node.child.attribute.value, handling potential Nones at each lookup with ifs would get very verbose very quickly (and that verbosity would be bad, as it would make it much harder to make out the main point of the code).
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).
- singularity2001 8y agoI don't think the existing pythonic way is not too verbose: if node and node.child and node.child.attribute: …
- singularity2001 8y agofor nested loop you can do for child in node.children or []: for attrib in child.attributes or []: …
- Doxin 8y agoThat'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.