Python: defining my own operators?

cwj picture cwj · May 31, 2009 · Viewed 52.3k times · Source

I would like to define my own operator. Does python support such a thing?

Answer

Ayman Hourieh picture Ayman Hourieh · May 31, 2009

While technically you cannot define new operators in Python, this clever hack works around this limitation. It allows you to define infix operators like this:

# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8

# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
print [1,2,3] <<isa>> []
# => True