RFC -- custom operators

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 7 03:58:25 EDT 2018


Request for comments -- proposal to allow custom binary operators.

I'll looking for comments on custom binary operators: would it be useful, 
if so, what use-cases do you have?

The most obvious and often-requested use-case would be for a form of 
logical operator (AND, OR, XOR) that is distinct from the bitwise 
operators & | ^ but unlike the standard `and` and `or` operators, calls 
dunder methods.

The proposal is to add custom operators. A placeholder syntax might be:

    spam OP eggs

which would then delegate to special dunder methods __OP__ or __ROP__ 
similar to existing operators such as + and similar.

I don't want to get into arguments about syntax, or implementation 
details, unless there is some interest in the functionality. Please focus 
on *functional requirements* only.

(1) This proposal requires operators to be legal identifiers, 
    such as "XOR" or "spam", not punctuation like % and
    absolutely not Unicode symbols like ∉

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

(3) This only proposes binary infix operators, not unary
    prefix or postfix operators;

    infix:    argument1 OP argument2
    prefix:   OP argument
    postfix:  argument OP

(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?

(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?

    # Left-associative:
    a OP b OP c    # like (a OP b) op c

    # Right-associative:
    a OP b OP c    # like a OP (b op c)

In the last case, that would make chained custom operators intentionally 
ambiguous (and hence a SyntaxError) unless disambiguated with parentheses:

    # Non-associative:
    a OP b OP c    # SyntaxError
    (a OP b) OP c  # okay
    a OP (b OP c)  # okay


(8) This does not propose to support short-circuiting operators.


I'm not interested in hearing theoretical arguments that every infix 
operator can be written as a function or method call. I know that. I'm 
interested in hearing about use-cases where the code is improved and made 
more expressive by using operator syntax and existing operators aren't 
sufficient.

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


Thoughts?



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list