[SciPy-user] Infix operators

Robert Kern rkern at ucsd.edu
Thu Feb 17 04:25:36 CST 2005

There is a disturbingly cool hack now available at the ASPN Python 
Cookbook site:


Given a binary function, you can make something that sort of looks like 
an infix operator that calls the function. I'll give the code here 
incorporating some of the suggestions from the comments.

# ----%<--------------
class Infix(object):
     def __init__(self, function):
         self.function = function
     def __ror__(self, other):
         return Infix(lambda x, other=other: self.function(other, x))
     def __or__(self, other):
         return self.function(other)
     def __call__(self, val1, val2):
         return self.function(val1, val2)
# ----%<--------------

Now one can do things like:

from scipy import *
dot = Infix(dot)
div = Infix(linalg.solve)
lsdiv = Infix(linalg.lstsq)
conv = Infix(signal.convolve)

A |dot| B
A |dot| transpose(B) |dot| C
A |div| B
A |lsdiv| B
x |conv| y

I'm not entirely sure that I recommend the use of this hack in 
production code, but when I'm constructing some expressions in ipython, 
I have found that it is quite annoying to realize halfway through that I 
need another dot( at the beginning of a line and have to double-check 
the balancing of parens at the end.

Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

More information about the SciPy-user mailing list