RFC -- custom operators

Rhodri James rhodri at kynesim.co.uk
Tue Aug 7 07:17:08 EDT 2018


On 07/08/18 08:58, Steven D'Aprano wrote:
> Request for comments -- proposal to allow custom binary operators.
[snip]
> (1) This proposal requires operators to be legal identifiers,
>      such as "XOR" or "spam", not punctuation like % and
>      absolutely not Unicode symbols like ∉

Probably wise.  I'd personally be inclined to use expressive symbols 
because I, of course, am an entirely reasonable person whose every 
choice will be completely intuitive to everyone else (ho ho), but I can 
imagine other people succumbing to the temptation to trying turning 
Python in APL.

Also names are probably easier to parse.

> (2) For the sake of the functional requirements, assume that
>      we can parse `spam OP eggs` without any ambiguity;

Seems like a fair assumption.

> (3) This only proposes binary infix operators, not unary
>      prefix or postfix operators;
> 
>      infix:    argument1 OP argument2
>      prefix:   OP argument
>      postfix:  argument OP

Other than being easier to parse, is there any particular reason for 
this choice?

> (4) This does not propose to allow the precedence to be
>      set on a case-by-case basis. All custom operators will
>      have the same precedence.
> 
> (5) What should that precedence be?

Low.  Names, with their mandatory surrounding spaces, feel more 
separated and hence lower priority than their operands.  I would expect

   x + 1 FROBNICATE q * 4 - 2

to parse as

   (x + 1) FROBNICATE (q*4-2)

> (6) This does not propose to set the associativity on a
>      case-by-case basis. All custom operators will have
>      the same associativity.
> 
> (7) Should the operators be left-associative (like multiplication),
>      right-associative (like exponentiation), or non-associative?

Either left-associative or non-associative, probably the latter.  Most 
operators that I can think of are left-associative, but you probably 
want non-associative to avoid subtle bugs with more naturally 
right-associative operators.

> (If there aren't any such use-cases, then there's no need for custom
> operators.)

I can't think of any use cases I actually want off-hand.  The sorts of 
things I might apply new operators to are various bits of byte buffer 
mangling, and most of those feel more pythonic as iterative processes.

-- 
Rhodri James *-* Kynesim Ltd



More information about the Python-list mailing list