[Python-ideas] new operators via backquoting

Chris Rebert cvrebert at gmail.com
Wed Jan 3 01:07:31 CET 2007


In Haskell,  foo `baz` bar  means  (baz foo bar), which translates to 
baz(foo, bar) in Python. This allows Haskell programmers to use 
functions as infix operators.
If I recall correctly, in Py3k, enclosing something in backticks will no 
longer cause it to be repr()-ed, leaving the backtick without a meaning 
in Python.


Thus, I propose one of the following as the new use for the backtick (`):
[Note: In both, the characters between the backticks must be a valid 
Python identifier.]

(A)  `baz` is treated as an operator, named "baz", just as / is "div". 
foo `baz` bar  thus causes python to try to call  foo.__baz__(bar), and 
failing that, bar.__rbaz__(foo), and if both those fail, raise 
TypeError. This is, if I understand correctly, how the builtin operators 
work.

(B)  `baz` is a special way to call a callable. foo `baz` bar  is 
translated to  baz(foo, bar)  with the standard lookup rules for 
resolving "baz"


Example use cases, stolen from Haskell: The Craft of Functional Programming:
2 `max` 5  =>  5
7 `cons` tail  =>  ConsCell(val=7, next=tail)
matrix1 `crossproduct` matrix2  =>  cross-product of the matrices
[1, 2, 3] `zip` ['a', 'b', 'c']  =>  [[1, 'a'], [2, 'c'], [3, 'c']]

I believe that this would improve the readability of code, such as 
Numeric, without going off the deep end and offering programmable syntax.

- Chris Rebert



More information about the Python-ideas mailing list