Unicode Python Infix Operators

Custom infix operators can be emulated in Python using prettify-symbols-mode.

In your emacs config include:


(global-prettify-symbols-mode 1)
(add-hook 'python-mode-hook
          (lambda ()
            (mapc (lambda (pair) (push pair prettify-symbols-alist))
                  '(("@compose@"  . #X2218)
                    ("@pipe@"     . #Xe135)))))

Now pip install infix.

Optionally pip install toolz, a functional programming library, otherwise you can define the infix operations yourself.


import toolz.curried as tz
from infix import custom_infix as infix

@infix('__rmatmul__', '__matmul__')
def compose(a, b):
    return tz.compose(a, b)

@infix('__rmatmul__', '__matmul__')
def pipe(a, b):
    return tz.pipe(a, b)

[1, 2, 3] @pipe@ (tuple @compose@ tz.map(lambda x: x+1))

Other interesting functions - cons as ':' and concatv/itertools.chain as '++'.

I do not recommend using this trick in production but it is certainly cool to see emacs enabling these shenanigans.

comments powered by Disqus