I’m writing a python program in which I need to overload the >> operator. The problem that I’m facing is that this operator need to be right associative. So if I do the following
A >> B >> C >> D >> E
I want this to be parsed as
(A >> (B >> (C >> (D >> E))))
From what I understand, in python this operator is left associative and so I would get,
((((A >> B) >> C) >> D) >> E)
Is there anyway to change the default associativity of an operator in python when you do operator overloading?
This can be done…but it will require a bit of effort. The basic idea is to use the right shift operator to create and update a new type of object that defers the actual computation.
For instance, let’s say that your variables above: A, B, C, D, and E are all objects of type Actual. We’ll introduce a new class Deferred that is produced by the rshift operation on an instance of Actual. Deferred also implements the rshift operator, which updates the object and returns itself.
(BTW, For the remainder of this answer, I’m assuming that A, B, C, D, and E are immutable and that the rshift operation produces a new object.)
Would be computed like …
F maintains a cached instance of Actual, that is computed from the reverse sequence. Furthermore, F implements the same interface as Actual, so that methods invoked on an instance of Deferred are delegated to the cached instance of Actual.
I don’t know the kind of computation you’re doing, so in the following example, I make up something kind of trivial, just to demonstrate that the when the deferred computation is actually performed, they are reversed.