On 21 September 2015 at 14:27, Chris Angelico email@example.com wrote:
On Mon, Sep 21, 2015 at 8:55 PM, Paul Moore firstname.lastname@example.org wrote:
There seem to be a few main use cases:
- 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.
Agreed, that's not what should happen.
It's hard to give examples without going into specific cases, but as an example, look at dict.get. The user can supply a "what to return if the key doesn't exist" argument. OK, many people leave it returning the default None, but they don't *have* to - dict.get itself doesn't do "useful value or None", it does "useful value or user-supplied default".
All I'm saying is that people should look at *why* their functions return None instead of a useful result, and see if they can do better. My contention is that (given free rein) many times they can. Of course not all code has free rein, not all developers have the time to look for perfect APIs, etc. But in that case, returning a placeholder None (and accepting a little ugliness at the call site) isn't an impossible price to pay.
Nothing more than "I don't think the benefit justifies adding a new operator to Python".