I’ve been considering the idea of proposing a new feature in Python - a Safe Navigation Operator, similar to what’s available in languages like JavaScript, Ruby, and C#. Before proceeding with writing a formal PEP, I wanted to bring this up here to gather initial feedback, insights, and ascertain if such an idea has been proposed or discussed before
Motivation
In Python, attempting to access an attribute or method of a NoneType object raises an AttributeError exception. This often requires writing boilerplate code to check if an object is None before accessing its attributes or methods. The Safe Navigation Operator would mitigate this by returning None if the object is None, rather than raising an exception.
For example, consider the following code:
if obj is not None and obj.attribute is not None:
print(obj.attribute)
With the Safe Navigation Operator, this can be simplified to:
print(obj?.attribute)
Specification
The Safe Navigation Operator (?.
) would be a new operator allowing attribute and method access to be short-circuited when the base object is None. If the left-hand operand is None, the expression evaluates to None; otherwise, it evaluates normally.
Benefits
- Readability: The code becomes cleaner and more readable, reducing the cognitive load required to understand the null checks.
- Conciseness: It reduces the amount of boilerplate code, leading to more concise code representation.
- Safety: Helps in avoiding
AttributeError
exceptions caused by attempting to access attributes or methods on a NoneType object.
Rationale
Languages like JavaScript, Ruby, and C# have already adopted similar operators, resulting in cleaner, more concise code. Introducing the Safe Navigation Operator in Python would offer similar benefits, enhancing code readability and maintainability.
Backward Compatibility
This change is backward compatible as the ?.
operator is not currently used in Python, and its introduction would not break existing code.
I believe this operator can be a valuable addition to the language, especially for developers coming from other languages where this is a standard feature. However, I’m interested in hearing the community’s thoughts, concerns, and feedback on this.
Is this something that Python developers would find beneficial? Are there any potential issues or conflicts that I might not have considered?