Python: defining my own operators?

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

Leave a Comment