r/Python • • 2d 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.

339 Upvotes

85 comments sorted by

106

u/skjall 2d 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 2d ago

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

4

u/covmatty1 2d ago

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

2

u/cip43r 2d ago

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

13

u/skjall 2d ago edited 2d 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 2d 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.

6

u/thisismyfavoritename 2d ago

opt-in rust like monadic optional would be even better

4

u/JanEric1 2d ago

How exactly would that look?

1

u/RingularCirc 2d 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.

76

u/aes110 2d 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)

42

u/cipri_tom 2d 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!

3

u/darthwalsh 2d 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.

3

u/larsga 1d 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 2d ago

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

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

3

u/Igggg 2d ago

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

See PEP-645

1

u/BeamMeUpBiscotti 1d 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

3

u/Brian 1d ago

I don't think that'd really solve it, since if the issue is confusion coming from typescript, it still exists just from the existance of the syntax, rather than just a lack of other syntax. Also, x? would be a much bigger deal than something that only exists in an annotation, so does seem a bit much for the gain.

I'm not sure that "potentially confuse typescript coders" is really that big a deal. However, having 3 separate ways to spell the same thing would be a bit much, so withdrawal makes sense.

1

u/BeamMeUpBiscotti 1d ago

yeah i don’t buy the Typescript argument that much either, there is a cost to new syntax but we shouldn’t let another language constrain us

1

u/mgedmin 12h ago

Wow, 2020! I wasn't paying attention to proposed but not accepted PEPs back then, explains why I missed it.

1

u/SCD_minecraft 2d ago

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

29

u/Sin-nie 2d ago

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

99

u/attoPascal 2d ago

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

12

u/pingveno pinch of this, pinch of that 2d 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 2d ago

Gotcha, thanks

23

u/Temporary_Pie2733 2d ago

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

32

u/FI_Stickie_Boi 2d ago

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

2

u/Sin-nie 2d ago

Thanks

9

u/pacific_plywood 2d ago

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

1

u/Electrical_Fox9678 2d ago

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

3

u/JanEric1 2d ago

Falsely bit non-none values.

40

u/Ran4 2d ago

The same year most stopped writing python by hand :(

16

u/pkmnrt 2d 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 2d ago

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

2

u/BossOfTheGame 2d ago

Exactly my feeling. Bittersweet.

-8

u/eatsoupgetrich 2d ago

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

16

u/TPECKA180 2d 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/tangerinelion 2d 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.

3

u/Wonderful-Wind-5736 1d 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 1d ago edited 1d 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

7

u/Nooooope 2d 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.

33

u/rghthndsd 2d ago

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

42

u/JanEric1 2d ago

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

60

u/teerre 2d 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

29

u/KeytarVillain 2d 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.

2

u/Darwinmate 2d ago

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

8

u/RingularCirc 2d 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.

1

u/M4mb0 2h ago edited 2h ago

x if x is not None else y also has a tendency to require 3-5 lines rather than 1 if the variable names get too long or function call is involved: https://play.ruff.rs/7d482090-e75b-4c1e-8401-c04b6ff37e5b

Shrinking the whole if x is not None else to just ?? prevents that.

14

u/DoctorNoonienSoong 2d 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.

20

u/djingo_dango 2d ago

This is extremely readable

8

u/TSM- 🐱‍💻📚 2d 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 2d ago

Agree.

import this

-1

u/rghthndsd 2d 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.

2

u/TheBlackMafia 1d 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 1d 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/M4mb0 2h ago

??= suggests inplace assignment a la +=, -=, *= and /= but it can't as it will potentially change the reference.

2

u/HovercraftOptimal971 1d 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.

9

u/MorrarNL 2d ago edited 2d 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...

35

u/JanEric1 2d ago edited 2d 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.

6

u/caks 2d 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 2d 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 2d ago

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

5

u/SkezzaB 2d 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 2d ago

such good news!

2

u/DeaD_EyE_1 2d 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/Charming_Couple_6782 1d 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/Internal_Pay4861 13h ago

The or operator watching everyone replace it with something more specific.

1

u/Uncreativite 2d ago

fuckin finally

0

u/def__eq__ 2d 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 2d ago

Love this, it’s about time

0

u/EternityForest 1d 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 1d ago

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

-5

u/Grouchy-Friend4235 2d 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] 1d ago

subcumb to anything proposed to them

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

edit: typo

-4

u/Short_Inspection_746 2d ago

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

4

u/JanEric1 1d 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

-1

u/Short_Inspection_746 1d 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 1d 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 1d 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++.

1

u/M4mb0 1h ago edited 1h 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.

You're not supposed to use these language features rampantly, but when they are apprpropriate. One appropriate usage of walurs is this pattern

if (var := getattr(obj, name, None)) is not None:

which one can find being used everywhere

1

u/M4mb0 2h ago

If personally find "val if val is not None else default" far more readable that using '??'

Even for:

class Foo:
    def method(self, some_optional_argument: str | None):
        value = (
            some_optional_argument
            if some_optional_argument is not None
            else "DEFAULT_VALUE"
        )

vs

class Foo:
    def method(self, some_optional_argument: str | None):
        value = some_optional_argument ?? "DEFAULT_VALUE"

?