[Python-ideas] Infix matrix-multiply, but not general infix operators?

Steven D'Aprano steve at pearwood.info
Thu Mar 20 11:24:44 CET 2014


On Thu, Mar 20, 2014 at 12:41:40AM -0700, Jared Grubb wrote:

> A couple months back, Andrew Barnet brought up the idea of adding a 
> way to apply functions in an infix style. It really didnt gain much 
> traction. (Subject line "Infix Functions")
> 
> Nathaniel Smith has just proposed a PEP to add an infix matrix 
> multiply operator, and everyone seems to love it.
> 
> I honestly am surprised at the difference in reaction. Why are we so 
> quick to add a single-purpose punctuation mark, but reject a named 
> infix operator that works for many general cases? Is the 
> matrix-multiply use case so special?

Yes.

Every day, there are probably thousands of numpy users (to say nothing 
of other matrix-multiplication library users) who do matrix 
multiplication. I can't think of the last time I've wanted to invent my 
own infix operator, and if I ever did, I'd probably be the only person 
using it. I don't think I'm too unusual. Custom infix operators for 
arbitrary functions are extremely niche, because apart from matrix 
multiplication, nearly all the common, useful ones are already 
available. We have + - * / & ^ | etc., that covers the common cases. The 
ones remaining are (apart from matrix multiplication) uncommon.

The beauty of infix operators is that they give an extremely compact 
representation, which is valuable for mathematics but not so much for 
general purpose computing. Consequently, it would be useful to write 
something like:

    matrix @ vector

versus

    matrix.mult(vector)

because the symbol for the operator is so compact. Having to write it 
as this instead:

    matrix`mult`vector

saves you one character over the method syntax, or even costs you one 
character if you write it like this:

    matrix `mult` vector

which is not enough of a saving over the method syntax to make it 
worthwhile. Having operators like + and * is a good thing, but if we 
didn't have them, and had to write this instead:

    x`plus`y
    a`times`b

there'd be no advantage to using pseudo-operators as shown. You might 
as well use regular method calls:

    x.plus(y)
    a.times(b)

(which you'll note is already pseudo-infix). So, in my opinion, until 
such time as Python supports Unicode symbols (around Python 5000 
perhaps?) as operators, there is no point in trying to fake them with 
spelled-out names. If you're going to use a spelled-out name, use a 
method, or function.



-- 
Steven


More information about the Python-ideas mailing list