Reversed ops in operator module

It would be nice to have reversed operations available in the stdlib operator module, e.g.

def radd(x, y):
    return y + x

This is easy to implement as e.g. a lambda, but that causes problems when you need to check something like if op is operator.eq: which is a pattern that shows up frequently in dispatching code.

xref Upstream roperator? · Issue #51898 · pandas-dev/pandas · GitHub

1 Like

Why would it be ‘nice’, especially when you can trivially implement such?

The operator module exposes the C functions that implement the operators. Each C function calls the normal and reversed dunder methods as appropriate. There are no reversed functions to expose.

IOW, a+b is compiled, in CPython, to a binary add functions that may call either a.__add__(b) or b.__radd__(a) or both as appropriate and necessary.

2 Likes

It would be nice because I suspect others have the same need to implement this, even though it is trivial. Opened this issue to check this suspicion.

Why not just call add(y, x)?

Saying “It would be nice” isn’t an explanation of why you need this, it’s an opinion, and one which often receives the answer “No it wouldn’t”.

It’s not clear why you would need this at all, let alone why it needs to be supplied by Python. As you say, you can trivially write functions

def radd(x, y):
    return y + x

and use them. If you need to check when dispatching, if op is radd will work.

Note that many operators are commutative, that is:

a <op> b == b <op> a

and so you don’t need a reversed version.

  • + is commutative for numeric and matrix addition
  • + is not commutative for string or list concatenation
  • * is commutative for numeric multiplication
  • and list replication eg 3*[1, 2, 3] == [1, 2, 3]*3
  • but not for matrix multiplication
  • division, subtraction and exponentiation are not commutative
  • bitwise operators & | and ^ are commutative

Julia defines a \ operator
which roughly does the reversed version of /:

> 3 \ 6
2.0

but Julia natively supports matrices where this would be far more useful.