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

Andrew Barnert abarnert at yahoo.com
Fri Mar 21 04:40:46 CET 2014


On Mar 20, 2014, at 19:49, Chris Angelico <rosuav at gmail.com> wrote:

> On Fri, Mar 21, 2014 at 12:28 PM, Brandon W Maister <bwmaister at gmail.com> wrote:
>> We could, hypothetically, create an "operators" dict (or dicts) alongside
>> locals and globals. Then, if an unexpected token shows up in operator
>> position (which is probably well-defined?) before a SyntaxError is raised
>> the token is looked up in the operators dict.
> 
> The SyntaxError is raised at compilation time; locals and globals are
> at run time. The only way that would work is if you do something like
> this:
> 
> operators["b"] = lambda left, right: whatever
> import module_using_b

Or, alternatively, instead of a SyntaxError this would compile into a call to b, which would then give a NameError at runtime. And I suppose you could argue that's just taking dynamic typing one step further. But I seriously doubt anyone actually wants typos like "esle" to compile successfully...

Also, imagine what it would look like to chain these:

    spam spam eggs baked beans spam spam

Maybe the parser can figure out that the spam, baked, and spam are operators and the spam, eggs, beans, and spam are operands, but what hope does any human have? Obviously that example is over the top, but try it with a tree constructor or the other examples from this thread and it's still painful.

The Haskell-style backticks solve all of these problems: the coder can't accidentally write an infix operator when he meant something else, the parser can distinguish infix operators from typos at compile time, and the reader can tell (unless he's stolen Tim's monitor grit) which things are operators and which are operands. (Of course you could deliberately confuse people with weird spacing, but Python doesn't have to make it impossible to write intentionally obfuscated code, it just has to avoid making it easy to write accidentally obfuscated code.)


More information about the Python-ideas mailing list