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 returnNone
ifa
isNone
, otherwise it would returna.b
. This is akin to the Optional Chaining in JavaScript. - Safe Subscript Access (
a?[b]
): Similar to the attribute access, this operator would returnNone
ifa
isNone
, otherwise it returnsa[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
orTypeError
that occur when trying to access properties ofNone
.
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:
- Safe attribute access: Implement unoptimized safe attribute access (#2) · nishu-builder/cpython@bbda7e5 · GitHub
- Safe subscript: Safe subscript implementation (#3) · nishu-builder/cpython@7dd54ef · GitHub
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!