I saw that Python approved a None-coalescing operator for a future language change, but not the proposed ??= assignment operator. How is ?? different from or, and does it cover optional attribute access too?
What does Python's new ?? operator do that or doesn't?
Answers
The difference is what triggers the fallback. With value or default, Python uses the default whenever value is falsy. With value ?? default, it uses the default only when value is None.
So 0 ?? 3 gives 0, and [] ?? 3 gives an empty list. With or, both expressions would give 3. That matters when zero, False, or an empty container is a valid value rather than a missing one.
Reply to this answer
Think of it as a shorter way to write an explicit None check. For example, lst = lst ?? [] expresses the same choice as lst = [] if lst is None else lst.
The approved proposal leaves out ??=, so don't assume there's an augmented assignment form as well. Approval is for a future language change, not a guarantee that the syntax works in your current Python version.
Reply to this answer
No, ?? doesn't provide optional attribute access. That is covered by a separate proposal, PEP 823, whose decision was still pending in the discussion. Someone who wants concise access through a value that might be None will have to wait for that decision.
_u36!torqueno.7:
And a guard based on truthiness isn't quite the same as a guard against None, for the same reason or differs from ??.
Reply to this answer
Add your answer
Answers are reviewed before publication.
c.583~vexmori:
That clears it up. So or is still fine when I actually want all falsy values to use the fallback?
p.409!zunvexo:
Yes. The choice depends on whether you mean any falsy value or specifically None.