Add explanation to `operator` docs about intentionally excluding short-circuit operators

Following discussion on PEP 824 here about whether a new None-coalescing operator should be added to the operator module in the standard library it was pointed out that short-circuit operators are intentionally not implemented there (because it’s not possible with a function to perform the short-circuit behaviour). I would like to propose that the docs for operator might benefit from a few lines making it explicit which python operators are not implemented for this reason and why. One can imagine users going to the docs expecting to find a function for a and b and wondering why it’s not there.

I don’t think this needs a discussion here, a simple PR should suffice.

I mean, there’s still arguably some value in having them, with the caveat that they won’t be short-circuting.

The operator module pre-dates comprehensions, when you were more likely to do map(operator.add, zip(sequence_1, sequence_2)) than [a + b for a, b in zip(sequence_1, sequence_2)], and having operators to “select first truthy argument” (or) and “select last truthy argument” (and) would still have been valuable. Less so now, since the usual convention is to use comprehensions (which ought to be more performant as well, but don’t hold me to that).

More likely the reason those aren’t there is because the name of the operation is a keyword, so it would have to be a different name (operator.and_, etc.), at which point the comprehension is looking much better.

Basically, the places where you need to use the operator module are where it’s being passed as an argument to be called by some other algorithm, and so short-circuiting isn’t going to be assumed anyway. You’d have to pass and or or using lambda a, b: a and b.

I’m not particularly interested in making the case for somehow adding and_, or_ and not_ (though if there’s obvious precedent for this, maybe it’s easy), but I don’t see a reason to omit coalesce just because of the lack of short-circuiting.

Agreed, but that’s a debate for the original thread. If the conclusion there is that short circuit operators shouldn’t be added to operator, then a PR is all that’s needed. I don’t see the value in having part of that discussion here, though.

I assumed they weren’t needed because of all (and) and any (or) being builtins?

4 Likes

TypeError: add expected 2 arguments, got 1

Should be map(operator.add, sequence_1, sequence_2)

Those already exist. For the “bitwise” operations.

Those only return True or False, not one of the arguments. And they do check the last element if it comes to that.

@Stefan2 if we’re talking coalesce, this would be closer

def first_true(iterable, default=False, predicate=None):
    "Returns the first true value or the *default* if there is no true value."
    # first_true([a, b, c], x) → a or b or c or x
    # first_true([a, b], x, f) → a if f(a) else b if f(b) else x
    return next(filter(predicate, iterable), default)
1 Like

We still have is_, is_not and more recently the is_none and is_not_none functions. OTOH, most functions correspond to overridable dunders and thus can be used in functional code. Note that not_ is already added as well.

Some are weird though to have in operator IMO such as countOf or indexOf. Now as observed, adding and_ and or_ would make the module more complete but it could definitely trick people into thinking that there will be short circuiting, in which case their performances will be affected. So I prefer documenting why it’s better to use explicit keywords rather than a function call for those cases.

OTOH, we can add the functions and note that they won’t be performing short-circuiting. FTR, we still didn’t add the identity function (there is an open PR but no consensus about) even if it’s necessary in some functional progrmaming context, so I would rather support a doc update first.

Thanks. That’s actually what I had initially, then I doubted myself and edited it :wink:

(Emphasis mine) Really? If anyone thinks that function arguments could possibly be short-circuiting, they’ve simply developed an innacurate mental model of the language, which means they’re going to do a lot of things that hurt performance. You can write code that looks like functional programming with functions, but that’s not enough of what Python’s for to expect it to optimise for it. Passing callables as first-class values is something that is very natural, though, so operator adds value by providing that for some things that can’t be “named” easily.

And the point of my post was to emphasise that the operator functions are normally used on values that are already calculated, either because they belong to a sequence or have already been passed through some kind of indirection.

Huh, I haven’t seen this PR, but it seems like an easy thing to add. Presumably the contentious part is “everyone can just write it themselves” and somehow that is more important this time than every other operator function that would also be a one-liner.

I do get less excited about a single argument operator, just because it less substitutible than a two argument operator (most of the other single argument operators return bool, so one that returns the original type can’t be substituted), but it does make sense as an alternative to neg and pos (but only those?).

The value here is that it’s easy for a function to expect a callable of a certain shape, and the operator module has a lot of those callables. Adding uncommon shapes doesn’t add as much value as adding alternatives to the existing shapes.

Just to point out, operator.and_ and operator.or_ already exist. They are functions for the bitwise & and | operators. This discussion was quite confusing to read with existing names being used as placeholders for functions being proposed.

2 Likes

Likely this.

Thank you, I should have checked more carefully the existing functions. In this case, I have no good names for the keywords to propose then. Maybe logical_and and logical_or but it’s not ideal.

2 Likes

operator versions of and and or could potentially be

def trueand[L, R](left: L, right: Callable[[], R]) -> L | R:
    return left if not left else right()

def trueor[L, R](left: L, right: Callable[[], R]) -> L | R:
    return left if left else right()

but I don’t think these would be that useful, even if they existed.

(edit: type annotations were included to make it clear that right is a lambda or other callable, and that it returns L | R rather than bool. I’m not advocating for type annotations in the CPython repository, just to be clear.)

@abkwreu How about return left and right() and return left or right()?