[Python-ideas] Null coalescing operators

Sven R. Kunze srkunze at mail.de
Mon Sep 21 18:27:48 CEST 2015


On 21.09.2015 15:27, Chris Angelico wrote:
> On Mon, Sep 21, 2015 at 8:55 PM, Paul Moore <p.f.moore at gmail.com> wrote:
>> There seem to be a few main use cases:
>>
>> 1. Dealing with functions that return a useful value or None to signal
>> "no value". I suspect the right answer here is actually to rewrite the
>> function to not do that in the first place. "Useful value or None"
>> seems like a reasonable example of an anti-pattern in Python.
> The alternative being to raise an exception? It's generally easier,
> when you can know in advance what kind of object you're expecting, to
> have a None return when there isn't one. For example, SQLAlchemy has
> .get(id) to return the object for a given primary key value, and it
> returns None if there's no such row in the database table - having to
> wrap that with try/except would be a pain. This isn't an error
> condition, and it's not like the special case of iteration (since an
> iterator could yield any value, it's critical to have a non-value way
> of signalling "end of iteration"). I don't want to see everything
> forced to "return or raise" just because someone calls this an
> anti-pattern.

I don't think both approaches are mutual exclusive. They can both exist 
and provide whenever I need the right thing.

Depending on the use-case, one needs to decide:

If I know, the value definitely needs to be a dictionary, I use dict[...].
If I know, the value is definitely optional and I can't do anything 
about it, I use dict.get('key'[, default]).
If I definitely don't know, I use dict[...] to get my hands on a real 
example with out that key if that every happens and don't waste time for 
special-handling a possible None return value.

Best,
Sven


More information about the Python-ideas mailing list