New syntax for safe attribute and safe subscript access

Title: Proposal: Introducing Safe Attribute and Subscript Access in Python

Hello fellow Pythonians –

I’d like to propose two new syntactic features for Python: safe attribute and subscript access operators: a?.b and a?[b]. They’re designed to simplify and improve the readability of code that needs to handle None values gracefully.

Current Situation Currently, accessing an attribute or subscript of a None object requires explicit checks, often leading to verbose code like value = a.b if a is not None else None. That case alone isn’t so bad, but it gets a lot more annoying with nested access. Similarly, repeated nested indexing (say, into a json with very flexible structure) can also be cumbersome: request_dict.get('args', {}).get('position', {}).get('x_coordinate').

Proposal Introduce two new operators:

  • Safe Attribute Access (a?.b): This operator would return None if a is None, otherwise it would return a.b. This is akin to the Optional Chaining in JavaScript.
  • Safe Subscript Access (a?[b]): Similar to the attribute access, this operator would return None if a is None, otherwise it returns a[b].

Both would only be allowed in Load contexts: not Store or Delete. So a?.b = 3 and del a?.b would not be allowed.

Benefits

  • Improved Readability: Reduces boilerplate code and makes the author’s intentions clearer.
  • Error Prevention: Helps avoid common AttributeError or TypeError that occur when trying to access properties of None.

Example Usage

config = get_config()  # Might return None
first_dog = config?.get('animals')?.get('dogs')?[0]

matrix = get_matrix()  # Might return None
element = matrix?[0][1]

Implementation details

I’ve taken a stab at implementing these:

I have not modified cpython before; I won’t take any offense if this is running afoul of some important considerations and we opt for better implementations.

Looking forward to hearing your feedback!

1 Like

Are you aware of PEP 505 PEP 505 – None-aware operators | peps.python.org ? If you’re looking for an easy way to find prior discussions on this subject, that would be something to search for.

1 Like

Thanks for the suggestion. I went on a bit of a tour starting at that PEP. Looks like the latest discussion of operators like the ones I suggested is here.

There are a lot of arguments in that thread that I respect. I found Steve Dower’s post especially compelling. He argues that operators like ?[ shift expectations around use of the language towards being more unexplained-None-friendly. Seems like a real worry to me: if anyone doubts that Python features change the culture around the data that Python code operates on, they need look no further than the introduction of type hinting.

I do think that this comes into conflict with this argument from you, Chris. At the risk of putting words in your mouth, it sounds like you’re saying that Python is already permissive enough that it allows for plenty of bad code patterns, and that this is a cost intentionally paid to enable other good use cases. Also seems reasonable.

So on this point, I want to defer to others. A crux here might be pinpointing how opinionated a language Python should be, and that feels well above my pay grade.

1 Like

Yes. You can ALWAYS write bad code, and restricting language features to prevent bad code is as ineffective in programming as it is in Newspeak. But the benefit of flexibility is huge.

1 Like