Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module `operator` in python has no `rfloordiv`?

Suppose I have s class, that has members op, left, right (this is related question to How to assign an operation like sum or substitute, etc., to a variable ). So, in op I store an operator, for example - operator.add, operator.radd, etc. But I want to store operator.rfloordiv and there's no such member in this class? :\ But I can overload __rfloordiv__, so it does exist at all.

The idea is to apply op to left and right when needed.

My approach is as follows: store some special string in my op and then, before applying op, to check if op is string. If so, write an ugly if-else statement, to check for all - rfloordiv, rmod, rtruediv. If not - just apply op with both parameters. But this is damn ugly..

Is there a better way to achieve this?

I know that this could be done with lambda function, but if I do it like this, is there any way to see what is this lambda function (for the moment, when I need to see what is op, I check it in an if statement like this: if self.op is operator.radd: .., but what if op is lambda function ? )

like image 718
Kiril Kirov Avatar asked May 23 '26 08:05

Kiril Kirov


1 Answers

Most magic operator methods come in two flavours: the plain variant and the variant prefixed with r (example __add__() and __radd()__). If you try to add the objects a of type A and b of type B, Python first calls A.__add__(a, b). If this returns the special value NotImplemented, B.__radd__(b, a) is called.

Both those magic methods corresond to operator.add in the operator module. Similarly, the magic methods __floordiv__() and __rfloordiv__() correspond to operator.floordiv.

like image 128
Sven Marnach Avatar answered May 25 '26 08:05

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!