The ‘standard’ needs updating to several pythons ago. Only one call is needed if one saves it with a parenthesized assignment expression.
>>> def f(x): return x
...
>>> fv if (fv := f(3)) is not None else 'def'
3
>>> fv if (fv := f(None)) is not None else 'def'
'def'
>>> fv if fv := f(None) is not None else 'def' # No parens fails.
SyntaxError: expected 'else' after 'if' expression
This is more general than the proposal as it works for any test of the captured (here ‘fv’) value. Capturing a subexpresson within a conditional expression is a prime intended use of assignment expressions. The more usual form, with a full if-else statement, would be
>>> x = 3
>>> if (fv := f(x)) is not None:
... fv
... else:
... 'default'
...
3 # or 'default' with x = None.
It just looks a bit weirder with the condition in the middle.
Great point. You’re right. It can process every condition (not only None).
But it’s also a little long, isn’t it?
There are many ways to do it, but my purpose is providing a simpler and clearer way for None.
No, the expression form is just fine. Assignment expressions are familiar from C and maybe other languages. Along with augmented assignment, they solve many instances of repeated expressions.
None is not special enough for a special syntax. Such would only encourage more overuse of None. IMO, many uses are as well or better handled with a class null value – such as ‘’ for strings.
And I would also say that the most common use-case for None-coalescing is argument defaults that are inexpressible as values, which might be something I’ve looked into before.
I have not a strong opinion about it. As other people pointed out, I don’t use a if a is not None then bso often. PEP 505 is much more interesting IMHO.
Anyway, I think it can’t hurt
Side note: None is obviously special. The real question is: is it special enough?
Thank you for your opinion.
“I think it can’t hurt” is warm for me.
Yeah, None is undoubtedly special, though someone doesn’t think so.
They think it’s just a common value, but I don’t. I can’t imagine that Python without None.
You correctly reported that this has two problems: 1) the expression is written twice, which is tedious and error prone; 2) the expression is executed twice, which may be a mistake. (If a second execution is wanted, for the side effect, eliminating it is a mistake.)
This problem is ubiquitous in programming and the standard solution, in Python and similar languages, is to save the result of the first computation and replace the second instance of the expression with the name of the saved result. In older Python, this required a preliminary assignment and two uses of the saved reference.
val = get_value()
value = val if val is not None else default
The once controversial walrus operator condenses this to one line.
I never said None is not special, just that I do not think it special enough, given one solution already, to add a second new syntax.
More importantly, ??= provides atomicity that the manual if x is None: x = default cannot offer – no race condition between the check and the assignment, which matters in concurrent contexts.
Just take note that this atomicity would not be a given in free-threaded Python: it has to be explicitly specified in the PEP and implemented in the underlying code. The new syntax, however, would allow the atomicity, which the `if ..: …=…` form doesn’t.
Many cases could simply use if not value, but instead None is used, which requires additional handling. I frequently see the pattern jobs: list | None, but in many cases the distinction is not actually used in practice, since empty lists and missing values are treated the same[1]. In such cases, None becomes largely redundant. We should aim to reduce such patterns rather than encourage them through dedicated syntax.
From Python 3.15, sentinel built-in function can be used to create a more meaningful sentinel than None.
I always check for the case when the jobs list is empty, but there is no handling for that case. ↩︎
This is because there are cases where not testing for None leads to nasty and hard to find bugs.
The use of None meaning supply the default is common pattern.
And the default may well not be 0 or 0.0 so the API wants to know the difference between 0 and use the default.
I agree that None is important when it acts as a sentinel for default behavior. I was specifically thinking of the cases where that distinction isn’t used, and both None and [] are effectively equivalent in downstream logic.
None is significantly clearer than using some kind of implicit sentinel because None is immediately obvious to the reader of code as representing an omitted or defaulted argument whereas the reader has to check that -1 or [] has special handling as an implicit default.
Yes, explicit sentinels have their place: typically when None can’t be used. For example when None is itself a useful non-sentinel value to pass. But when None can be used, you should use that over your own sentinel.
That said I am sympathetic to the overuse of None, but using implicit sentinels is generally inferior, and using explicit sentinels is generally only superior when using None is impossible or complicated.
But when you’re trying to find a bug or unexpected behaviour, if None is used instead of [], that can be a significant time saver - a whole class of unexpected causes is immediately ruled out if you see [] where it should have been None or a non-empty list, or conversely if you see None, and you know the code never got to the list comprehension.
jobs = get_jobs() # list
for job in jobs:
...
# or simply
for job in get_jobs():
...
This alternative is clearly bloated and becomes a time-wasting approach in practice:
jobs: list | None = None
jobs = get_jobs() # list | None
if jobs is not None:
for job in jobs:
...
All I remember when reading such code are checks like is None, is not None, and variables that can be a type or None. This is very distracting and not helpful.
Also, all the examples in the original post are simply the result of poorly planned function design, not an issue with Python itself. It is similar to dict.get always returning None when a key is missing, instead of accepting a default value. It is much easier to add a default argument than to introduce syntax for each workaround for poor design.
So, the real question is whether we truly need all these None values or if better design would avoid them. For example, is dict.get() accepting a default value unusual, or is it the correct design choice? If it is correct, why do we not apply it consistently?
data = api.get(key) ?? cache.get(key) ?? fallback_value # !!! weird Cache usage
# default argument
data = api.get(key, cache.get(key, fallback_value));
class C:
job_queue: JobQueue | None
def get_jobs(self, from, to) -> list | None:
if self.que_loc is None
return None
return [self.job_queue.find(t) for t in range(from, to)]
(Trying to translate to the paradigm of job-getting, and simplifying).
Yes we could instead have written
class C:
job_queue: JobQueue | None
def get_jobs(self, from, to) -> list:
if self.que_loc is None
return []
return [self.job_queue.find(t) for t in range(from, to)]
Or we could even have made the a NO_JOB_QUEUE: JobQueue sentinal instance so that the attribute on the class itself is never None, and it would have made the code look “cleaner”. Say like this:
class C:
job_queue: JobQueue
def get_jobs(self, from, to) -> list:
return [j for t in range(from, to) if (j:=self.job_queue.find(t)) is not None]
Can you still tell what’s happening here, and what happens if job_queue is disabled in the settings? This would have made the development process hell.
The bloat of if ... is not None is expressive. It tells me there are 2 paths the code can take, and I can parse it without thinking about it particularly deeply.
All that said, the main place where I would use None-coalescing operators is in functions with essentially late-bound function argument defaults, and I’d far prefer PEP 671 over this proposal.
Agreed. But you wouldn’t (shouldn’t?) use a null-coalescing operator there - the if ... return is more expressive (IMO, at least) than anything you could have done with an expression.
+1
Having said that, I don’t particularly object to the null-coalescing operator/assignment. I just think they would be used far more rarely in practice than people are claiming. It feels a bit like the assignment expression - the debate over that was hugely divisive, and it was made to feel like a critical feature[1], but since it’s been added to the language, I’ve hardly ever seen it used in the wild. It’s useful, and worth having, but nowhere near as important as the debates tried to present it. I believe it’s the same here.
To the point where it pushed Guido to resign as BDFL! ↩︎
class JobQueue(list):
pass
class C:
def __init__(self, job_queue: JobQueue):
self.job_queue = job_queue
def get_jobs(self, start, stop) -> list:
return self.job_queue[start:stop]
# Create a JobQueue and add some jobs
queue = JobQueue()
queue.extend(["job1", "job2", "job3", "job4", "job5"])
# Create class C with the queue
c = C(queue)
# Get a slice of jobs
print(c.get_jobs(1, 4))
This also makes get_jobs redundant, since you can access job_queue directly.
I do not see the need for Optional here if the job queue is part of the object’s normal state. An empty list should represent “no jobs,” while failure or inability to retrieve jobs should be handled explicitly (for example, at the boundary via an exception or normalization step), rather than propagating None through the code. This avoids spreading None checks throughout the logic.
If nullability is required by external systems (such as SQL NULL values or API responses), it should be treated as a boundary concern and translated into a well-defined internal model in Python, rather than allowing Optional to leak into core domain types.