Add optional chaining of attributes

Hey everyone!

Other languages have the concept of optional chaining (javascript/swift maybe more). It enables developers to easily access nested attributes that might be null. Example of how it could be used.

from typing import Optional
class B:
    data: Optional[bool]

class A:
    container: Optional[B]

a = A()
if data := a?.container?.data:

To do something similar today.

    if data :=
except (NameError, AttributeError) as e:

Is this something to consider as an addition to python or has it already been discussed?


Maybe it’s worth giving it another go, with a reduced scope? AFAIR the most controversial part was the None aware index access ?[ ]. The ?. and ?? operators do provide quite a lot of value on there own.
?[ ] could always be done at a later point.


That’s up to you and/or anyone else who wants to write a new PEP to propose that subset of operators.

1 Like

I need to read up on my PEP 1 to move forward with this it seems :slight_smile:

As PEP 505 suggests three new operators and that might be a bit much for a single PEP would it be better to create separate PEPs for null coalescing and null aware member access? Or if I move forward with this keep it in a single PEP for these two suggestions?

It’s up to you and anyone else who wants to take this on. Since PEP 505 was technically deferred you could ask to be made a co-author and resuscitate the PEP. Otherwise you have to ask yourself if you think a single PEP has a better chance of being accepted than two separate PEPs?

1 Like