11

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
VBobCat
  • 2,527
  • 4
  • 29
  • 56
  • 2
    Related: [Does Python have the Elvis operator?](https://stackoverflow.com/questions/48813097/does-python-have-the-elvis-operator), [Is there a Python equivalent of the C# null-coalescing operator?](https://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-sharp-null-coalescing-operator) – smci Jan 05 '20 at 12:50
  • @smci, OP is specifically asking about chained attribute access. There may well be a duplicate for that, but I don't think it's the one you've proposed. – ChrisGPT was on strike Jan 05 '20 at 12:55
  • @Chris: ok please retitle, retag and reword accordingly. (The original title was merely *"null/None propagation in Python"*) – smci Jan 05 '20 at 12:56
  • @Chris: the question title couldn't be understood without reading the body b) it has no tags by which it would be found by search. This can cause duplicates in future. – smci Jan 05 '20 at 13:00
  • @smci, we're getting in the weeds here. The question has already been improved by your edits and somewhat less by mine. Let's not argue about what it originally _was_. I'll see if I can find additional tags for it. – ChrisGPT was on strike Jan 05 '20 at 13:02
  • Thank you guys for the edits. I considered adding a #null-propagation tag but it was specific to C# and i don't have enough rep for creating a new, more generic one. That being said, I've got the answer I was looking for, and I hadn't found before using SO search. – VBobCat Jan 05 '20 at 13:08

1 Answers1

28

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

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257