reset password
Author Message
rabbott
Posts: 1649
Posted 15:38 Apr 02, 2019 |

This discussion explains how infix operators may be defined in Python. It's considered a hack, but it works. Seems to me that it's a hack in much the same way that decorators might be called a hack. Yet decorators are now an accepted Python feature.

Last edited by rabbott at 20:59 Apr 02, 2019.
rabbott
Posts: 1649
Posted 22:41 Apr 02, 2019 |

I updated the discussion with an addendum that suggests somewhat simpler code. It seems to work properly. Does anyone see why the more complex version might be better? (I don't. But let me know if you do.)

rabbott
Posts: 1649
Posted 10:23 Apr 03, 2019 |

An even simpler version in Addendum 2 (on page 3).

Last edited by rabbott at 10:37 Apr 03, 2019.
jungsoolim
Posts: 38
Posted 22:00 Apr 04, 2019 |

This is so cool!!!

Just added two more:

 

from operator import mul # mul is the Python name for the * function.

class Infix:
  def __init__(self, function):
      self.fn = function

  def __ror__(self, l_arg):
      """ For | on the left """
      # r_arg and l_arg are for right and left arguments
      return \
            Infix(lambda r_arg, fn=self.fn, l_arg=l_arg: fn(l_arg, r_arg))

  def __or__(self, r_arg):
      """ For | on the right """
      return self.fn(r_arg)

  def __rxor__(self, l_arg):
      """ For | on the left """
      # r_arg and l_arg are for right and left arguments
      return \
            Infix(lambda r_arg, fn=self.fn, l_arg=l_arg: fn(l_arg, r_arg))

  def __xor__(self, r_arg):
      """ For | on the right """
      return self.fn(r_arg)

  def __rlshift__(self, l_arg):
      """ For | on the left """
      # r_arg and l_arg are for right and left arguments
      return \
            Infix(lambda r_arg, fn=self.fn, l_arg=l_arg: fn(l_arg, r_arg))

  def __rshift__(self, r_arg):
      """ For | on the right """
      return self.fn(r_arg)

if __name__ == '__main__':
    x = Infix(mul)
    print(2 | x | 4)
    print(2 ^ x ^ 4)
    print(2 << x >> 4)