pythonmethod-chainingnull-coalescing-operatornull-coalescing

None propagation in Python chained attribute access


Is there a null propagation operator ("null-aware member access" operator) in Python so I could write something like

var = object?.children?.grandchildren?.property

as in C#, VB.NET and TypeScript, instead of

var = None if not myobject\
              or not myobject.children\
              or not myobject.children.grandchildren\
    else myobject.children.grandchildren.property

Solution

  • No. There is a PEP proposing the addition of such operators but it has not (yet) been accepted.

    In particular, one of the operators proposed in PEP 505 is

    The "None-aware attribute access" operator ?. ("maybe dot") evaluates the complete expression if the left hand side evaluates to a value that is not None