[Python-ideas] In-place assignment for "boolean or"?
Steven D'Aprano
steve at pearwood.info
Mon Mar 26 09:41:19 EDT 2018
On Mon, Mar 26, 2018 at 01:48:34PM +0100, Cammil Taank wrote:
> Hi,
>
> I find a common idiom in Python is:
>
> x = x or 'some other value'
I don't find it very common. I don't think I've ever used it or seen it.
I've occasionally used:
spam = eggs or 'something'
but mostly I use:
result = function(eggs or 'something')
(and even that is quite unusual). But others may use it more often.
> This is highly reminiscent of the problem inplace operators solve.
Not really: the other augmented operators all connect to ordinary
operators that can be overloaded. But `or` is special, it's a
short-cutting operator that is treated specially by the interpreter.
And even if x is mutable, there's no way to make this an in-place
operation. After `x = x or y`, there are only two possibilities:
- x is still a reference to whatever it was before the operation;
- or x now refers to the same object as y.
So this is very different behaviour to (say) += and the other augmented
operators.
> Would it be a good idea to consider an inplace operator for this, perhaps:
>
> x or= 'some other value'
Mixing a keyword with a symbol like that looks really weird.
Others may disagree, but to me, this pattern isn't common enough to
justify specialist syntax. I might be a little less negative if the
syntax didn't look so strange to me.
But only a little.
--
Steve
More information about the Python-ideas
mailing list