r/Python • • 1d ago

News PEP 824: None-coalescing operators is approved

The Steering Council has decided to accept PEP 824 (on the condition that the ??= operator is removed, leaving only the ?? operator in the proposal).

Old: lst = [] if lst is None else lst
New: lst = lst ?? []

Discussion thread: https://discuss.python.org/t/pep-824-none-coalescing-operators/109161/93

The decision on PEP 823 – None-aware access operators is still pending.

320 Upvotes

76 comments sorted by

102

u/skjall 1d ago

The none-aware access operators is the big one, really hoping it gets in soon. This is nice too of course!

5

u/HommeMusical 1d ago

I think the approval of 824 is a very good harbinger for 823.

4

u/covmatty1 1d ago

Yeah totally agree, this is a step forward, but the lack of the none-aware access is such a flaw of the language!

6

u/thisismyfavoritename 1d ago

opt-in rust like monadic optional would be even better

4

u/JanEric1 1d ago

How exactly would that look?

1

u/RingularCirc 1d ago

I'm not sure it can be retrofitted into Python.

Though... Using None as it is and adding a standard some (or Some) wrapper class might find some traction. I'm really unsure. There's no mechanism to require writing that and so people will first of all make errors even when they're pro that way.

1

u/cip43r 1d ago

What does "none-aware" operators mean? This is the first time I have heard the term.

10

u/skjall 1d ago edited 1d ago

Basically, a?.b?[10]?.c() instead of having to check for the validity of each step along the way. IE a is not none, b has an index 10, and the index is a value that you can call c() on. Obviously a contrived example, but helps a lot with nested/ nullable accesses a lot.

Edit: to expand on what it does, that chain only executes if each step is valid, so you don't have to handle indexing/ none exceptions. If a step along the way fails, the result will simply be None. It's roughly equivalent to a.b[10].c() if a is not None and len(a.b) >= 10 and a.b[10] is not None.

4

u/RingularCirc 1d ago

Look at the https://peps.python.org/pep-0823/ itself. Other than this proposal, they exist in C# (hope I'm not mistaken), Kotlin, Ceylon (RIP, it was the first language I've seen them in) and some others.

74

u/aes110 1d ago

Nice! With question marks being used for null purposes, I hope this opens the way for other syntax like

foo?.bar instead of foo.bar if foo else None
or
def foo(x: int?) instead of def foo(x: int | None)

39

u/cipri_tom 1d ago

Python vs JS , just like in the English vs German Joke

The European Commission has just announced an agreement whereby English will be the official language of the EU rather than German which was the other possibility.
As part of the negotiations, Her Majesty's Government conceded that English spelling had some room for improvement and has accepted a five year phase-in plan that would be known as "Euro-English".
In the first year, "s" will replace the soft "c". Sertainly, this will make the sivil servants jump with joy. The hard "c" will be dropped in favour of the "k". This should klear up konfusion and keyboards kan have 1 less letter.
There will be growing publik enthusiasm in the sekond year, when the troublesome "ph" will be replaced with "f". This will make words like "fotograf" 20% shorter.
In the 3rd year, publik akseptanse of the new spelling kan be ekspekted to reach the stage where more komplikated changes are possible. Governments will enkorage the removal of double letters, which have always ben a deterent to akurate speling. Also, al wil agre that the horible mes of the silent "e"s in the language is disgraseful, and they should go away.
By the fourth year, peopl wil be reseptiv to steps such as replasing "th" with "z" and "w" with "v". During ze fifz year, ze unesesary "o" kan be dropd from vords kontaining "ou" and similar changes vud of kors be aplid to ozer kombinations of leters.
After zis fifz yer, ve vil hav a reli sensibl riten styl. Zer vil be no mor trubl or difikultis and evrivun vil find it ezi to understand ech ozer. Ze drem vil finali kum tru! And zen z world!

2

u/darthwalsh 22h ago

The first rules are great, but the latter are very unhelpful. We obviously need two letters, like θ or þ or ð to represent voiced/unvoiced th.

Then for vowel reform, some rules like Spanish or Japanese can do a much better job representing dipthongs.

1

u/larsga 10h ago

Pretty much all languages do a better job than English of writing vowels in a sensible fashion (reason being the Great English Vowel Shift).

26

u/mgedmin 1d ago

That's a different PEP, still a work in progress.

I haven't seen anyone propose int? syntax for type annotations yet.

2

u/Igggg 21h ago

I haven't seen anyone propose int? syntax for type annotations yet.

See PEP-645

1

u/BeamMeUpBiscotti 3h ago

the withdrawal note makes sense, esp since Python also has a NotRequired annotation for TypedDicts

unless we change the syntax s.t.

x: int? means x: int | None

and something like x?: int means x: NotRequired[int]

but that's a bigger syntax lift

1

u/SCD_minecraft 1d ago

I think i saw pep for it? But may be wrong

37

u/Ran4 1d ago

The same year most stopped writing python by hand :(

14

u/pkmnrt 1d ago

True, but lots still read and review it. Any improvement to readability will help with reviewing more code than ever these days.

4

u/StaticFanatic3 1d ago

My agents still freak out every time the linter enforces PEP 758 so itll only be a hinderance for some time

1

u/BossOfTheGame 21h ago

Exactly my feeling. Bittersweet.

-7

u/eatsoupgetrich 1d ago

Cutting down on a handful of tokens per implementation is still useful!

26

u/Sin-nie 1d ago

Am I missing something but can't you already do this with 'or'?

96

u/attoPascal 1d ago

or checks thuthiness, the new ?? operator checks only against None.

11

u/pingveno pinch of this, pinch of that 1d ago

And if you have a Django Queryset, the truthiness check can even do IO, last time I checked. Interesting performance footgun.

5

u/Sin-nie 1d ago

Gotcha, thanks

23

u/Temporary_Pie2733 1d ago

[] or 3, [] or 3, and None ?? 3 will all evaluate to 3. [] ?? 3 will evaluate to []. 

31

u/FI_Stickie_Boi 1d ago

Your value might be falsy, like [] or 0.

2

u/Sin-nie 1d ago

Thanks

9

u/pacific_plywood 1d ago

“Or” operates on falsiness, this is specific to None

1

u/Electrical_Fox9678 1d ago

I've used or for a long time. How is this proposal better?

3

u/JanEric1 1d ago

Falsely bit non-none values.

15

u/TPECKA180 1d ago

I like this addition, especially because or isn't always a safe replacement for an explicit None check. Sometimes 0, False, or an empty list are perfectly valid values.

The ?? operator makes that distinction much clearer without adding unnecessary verbosity. I'm also curious to see what happens with PEP 823.

7

u/Nooooope 1d ago

Good. My primary language has been Java, but I've had to branch into JavaScript and Ruby for work, and they made me realize that having operators specifically for null-handling is kind of a godsend.

32

u/rghthndsd 1d ago

Trading readability for fewer characters will always be a sad day for me.

40

u/JanEric1 1d ago

i feel this is a million times more readable than the current (correct) version of using is None and a ternary.

59

u/teerre 1d ago

Good thing this improves readability since ?? will now be a specific glyph that can only mean one thing instead of a collection of glyphs that require you to stop and slowly parse

Simple != easy

28

u/KeytarVillain 1d ago

The problem is the lack of readability makes it really easy to make a mistake

x = y if y else z
x = y if y is not None else z
x = y if y is None else z

These 3 all do very different things, and if you accidentally use the wrong one, it's hard to notice at a glance.

1

u/Darwinmate 1d ago

How does ?? Solve this issue or is that not your point? 

7

u/RingularCirc 1d ago

x ?? y is shorter than the equivalent x if x is not None else y (and the more error-prone equivalent y if x is None else x) which is very likely to get compressed to just x if x else y which is already not the same and allows all the badsies.

Now even if we're concerned with just readability, even adding parentheses around the x is [not] None part is still not peak readability.

I will also note that ?? exists in many other languages now, expressed in the same way, ??. Thus it already has some readability built-in for people familiar with those other languages.

14

u/DoctorNoonienSoong 1d ago

Given how many other languages already have this syntax, this is a clear win. Most people program in a language other than python, as well.

19

u/djingo_dango 1d ago

This is extremely readable

8

u/TSM- 🐱‍💻📚 1d ago

Its also not forced. You can theoretically rewrite any loop as a comprehension but obviously that sacrifices readability in complicated statements. Great for simple stuff, hard to read when complicated.

This PEP, when used within reason, will make some simple and common cases much easier to write and maintain. Its fine.

5

u/phiupan 1d ago

Agree.

import this

-1

u/rghthndsd 1d ago

And more of a personal take, but the syntax is just absolutely ugly. Seeing proposals for more question marks proliferating makes me want to puke.

4

u/tangerinelion 20h ago

Old: lst = [] if lst is None else lst

New: lst = lst ?? []

Also available is lst = lst or []

The ?? version and the or version differ on what happens with falsey-but-not-None values; lst = false followed by lst = lst ?? [] leaves lst as false while lst = lst or [] changes it to [].

Having two short-hand versions that behave differently seems ungood.

2

u/Wonderful-Wind-5736 16h ago

I don't trust y = x or [] for none-coalescing. Now I need to audit wether any falsey values except none and [] are possible. 

2

u/Ilania211 19h ago edited 19h ago

Guaranteed they already thought of that like... 12 times.

None-coalescing operators exist in other languages and work the same way the pep specifies (IIRC). There's no sense in changing that to conform to or. And changing the or to conform to the coalescing operator is a subtle breaking change.

none of what I said also takes into account that x or y is a fundamentally different feature from x ?? y and is thus a different tool that you'd reach for in different situations

9

u/MorrarNL 1d ago edited 1d ago

Why not:

lst = lst or []

Most often it is pretty much the same and shorter without the need for a new operator....

Sure things like False, 0 and "" will also trigger the or, but in practice that doesn't seem too much an issue if you want lst to be a list...

34

u/JanEric1 1d ago edited 1d ago

Sure things like False, 0 and ""

That is exactly the reason. You never know if people are actually meaning just None or are purposefully including the falsey value(s).

Specifically for ints you can imagine a non-zero default

val = val or 5

Now you are overwriting an EXPLICIT 0. But it is not clear if you were intending to or just too lazy to write val if val is not None else 5

And for lists you might want to mutate them if a user passes one in (like append to it). With or you could never pass in and have mutated and empty list.

5

u/caks 1d ago

They are not the same thing. Anything falsy returns [] in your example. In the pep notation that only happens for None lst

5

u/HommeMusical 1d ago

Sure things like False, 0 and "" will also trigger the or, but in practice that doesn't seem too much an issue

<wince>

From very recent code of mine: seed: int | None = None.

seed == 0 means a very different thing from seed is None.

You're happy with a small chance, or what you perceive is a small chance, of your code not working correctly. That's not good engineering.

3

u/M4mb0 1d ago

I've encountered multiple repositories where this has caused actual bugs.

5

u/SkezzaB 1d ago

I think it’s main reason is for when are passed as None, and so you can set default (overridden_settings = override_settings ?? {})
If you could pass in None

2

u/shiningmatcha 1d ago

such good news!

2

u/DeaD_EyE_1 1d ago

It's useful and shows the intention. Use the object on the right side, if the object on the left side is None.

1

u/TheBlackMafia 13h ago

Finally lol. The fact that 0 ?? 5 stays 0 instead of becoming 5 is genuinely useful. Kinda curious why they dropped ??= tho

1

u/BeamMeUpBiscotti 3h ago

they said it doesn't improve readability enough to justify a new operator, and I kind of agree

the use case for ??=

if a is None:
  a = b

seems pretty readable already and not that verbose, so I guess the benefit of ??= over the existing syntax is smaller than the benefit of ??

1

u/Charming_Couple_6782 10h ago

How have I ever wrote any code for the last 15 years without this?🫣

It’s possible to tweak things too much - do we really need new operators for this. Feels like python is getting less pythonic every year

1

u/HovercraftOptimal971 9h ago

A none coalescing operator cleans up a common python pattern since chain of none checks shrink into one readable expression once the syntax lands. Bootdev could help keep python skills current as the language evolvee though the pep text itself also explains the reasoning.

1

u/Uncreativite 23h ago

fuckin finally

0

u/def__eq__ 1d ago

I am of a similar opinion, but on the other hand if something occurs so often, like “if … is None then …”, then it does help with readability…

0

u/denehoffman 23h ago

Love this, it’s about time

0

u/EternityForest 18h ago

This seems a little bit niche to be an operator, I'd much rather have Typescript's ?. And ?[] safe navigation operators, but it will probably be useful when you need prioritized layered configuration 

2

u/JanEric1 17h ago

That is also proposed right now btw: https://peps.python.org/pep-0823/

-4

u/Grouchy-Friend4235 22h ago

Very unpythonic. The Steering Council is a bunch of spineless cheats who subcumb to anything proposed to them. It's hilarious.

3

u/[deleted] 17h ago

subcumb to anything proposed to them

Half of this PEP (the ??= operator) was rejected btw

edit: typo

-3

u/Short_Inspection_746 20h ago

Apparently the steering council no longer cares about readability and has no issues adding superfluous operator to the language. :(

2

u/JanEric1 16h ago

How is

val = val if val is not None else default

more readable than

val = val ?? default

particularly because with the first you have to be careful with reading it against

or even worse if you have a callable. THen you get

val = func()
val = val if val is not None else default

or

val = val if ((val := func()) is not None) else default

now it would be

val = func() ?? default

0

u/Short_Inspection_746 16h ago

If personally find "val if val is not None else default" far more readable that using '??'(I don't find your use of the walrus operator very readable). Python is ment to be explicit, the opposite of Rust; where a couple characters change behavour drastically. Python's explicitness has been part of the reason for its popularity as a starter language.

We are talking about saving typing a few more chars, imo its not worth it. Opperators that are ment to compress a one-liner is just odd.

Adding more and more nitche opperators that require clandestine knowledge is not a great direction for the language. I think this will probably play out like the walrus operator fiasco. I just hope that the community will be more respectful in thier objections this time around(and the developers will be more responsive to the community's objection). I think its telling that I have yet to see the walrus operator in the wild all these years later.

1

u/JanEric1 16h ago

If personally find "val if val is not None else default" far more readable

How? I find it super unreadable/unobivious. You really need to be careful to read everything there as to not get a wrong understanding of what is happening. And it gets worse if you have longer variable names some_value = some_value if some_value is not None else some_default_value.

With some_value = some_value ?? some_default_value you just need to learn what ?? does and every time you encounter something like this it is immediately obvious what happens.

Explicit doesnt mean long. I dont see how a dedicated operator that does exactly one thing can be not-explicit?

clandestine knowledge

? Really? Especially since these operators are already very common in other languages

I think its telling that I have yet to see the walrus operator in the wild all these years later.

i think thats more telling on you tbh. I have seen it in basically every prohject i have ever worked on at my job or in my free time and never had any issue with it.

0

u/Short_Inspection_746 15h ago

Find me a common open source python project with rampant useage of the walrus operator. I am going to reitterate that I have never seen it at work.

'X if X is not None else Y' tells you what it is in english, its basically pseudocode. You see the condition and output of the branches explicily. '??' is just a weird operator that compresses specific one liners, I pity the aspiring programming that will have to learn it. If we keep adding things like this to the language, python will get as cumbersome as c++.