None propagation in Python chained attribute access [duplicate]
Asked Answered
S

1

14

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
Schlimazel answered 5/1, 2020 at 12:46 Comment(6)
Related: Does Python have the Elvis operator?, Is there a Python equivalent of the C# null-coalescing operator?Lindbom
@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.Daugherty
@Chris: ok please retitle, retag and reword accordingly. (The original title was merely "null/None propagation in Python")Lindbom
@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.Lindbom
@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.Daugherty
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.Schlimazel
D
31

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

Daugherty answered 5/1, 2020 at 12:51 Comment(2)
Is it still not implemented in 2023?Learning
@SaeedNeamati, correct. PEP 505 is deferred, meaning "Inactive draft that may be taken up again at a later time".Daugherty

© 2022 - 2024 — McMap. All rights reserved.