Thursday, October 17, 2013

Custom Unicode Operators in Python

Ferdinand Jamitzky has an interesting hack that adds custom operators to Python using the | bitwise-or operator on both sides of the custom operator. This technique can also be leveraged by the PythonJS compiler to support custom operators, by pre-processing the source before it is turned into an AST, custom operators defined by the special decorator @custom_operator("operator-name") can be automatically replaced in the source with |'operator-name'|. See this commit.


@custom_operator( 'XXX' )
def operatorX(x,y):
 return x | y

@custom_operator( 'YYY' )
def operatorY(x,y):
 return x | y

def test():
 a = 1 |'operatorX'| 2 |'operatorY'| 3
 print a
 b = 1 XXX 2 YYY 3
 print b
The above gets translated by PythonJS into this intermediate form:
    a = operatorY( operatorX( 1, 2 ), 3 )
    print a
    b = operatorY( operatorX( 1, 2 ), 3 )
    print b

Unicode Example ⊖

We can also use unquoted unicode strings as operator names, this example uses the circled minus operator ⊖ directly in our Python code. The @custom_operator decorator marks this operator to call the symmetric_difference function. See this commit.

@custom_operator( '⊖' )
def symmetric_difference(a,b):
 d = []
 for v in a:
  if b.count(v): pass
  elif d.count(v): pass
  else: d.append( v )
 for v in b:
  if a.count(v): pass
  elif d.count(v): pass
  else: d.append( v )
 return d

def test():
 sdiff = [1,2,3] ⊖ [2,3,4]
 print sdiff
 for v in sdiff:
  print v

No comments:

Post a Comment