[Python-ideas] Infix functions

Stephen J. Turnbull stephen at xemacs.org
Tue Feb 25 09:43:13 CET 2014


Steven D'Aprano writes:

 > Copula are "linking verbs" like "be", "is", "was" or "becomes".
 > 
 > Under what circumstances would you want to write such operators?

For one, in establishing object identity.  "is" *is* an operator in
Python.

 > Any infix binary operator a `op b can be written as a function of two 
 > arguments, op(a, b). It's not that there are no use-cases for infix 
 > binary operators, but that all the obvious ones (such as string 
 > concatenation, comparisons, list repetition, etc.) already exist and the 
 > rest can nearly always be easily written as functions.

All the obvious ones (such as binary math operators) also can written
as functions:

    def polymorphically_add_things(x, y): 
        return x + y

We know where that leads to (hi, John McC!).  Obviously, that's not
logic you're willing to follow to the bitter end!  As for use cases,
how about DSLs:

    @make_named_operator
    def to(x, y):
        return (x, y)

    # There really oughtta be a Graph class with an appropriate repr.
    tricycle = [ 'a' `to 'b',
                 'b' `to 'c',
                 'c' `to 'a']

    whine("But, Daddy!!!!  I wanna PONEEEEEEEE!!")

(Sorry, bad cold, can't remember any use of graph theory in Monty Python.)

As I said, I dunno if easy creation of DSLs is desirable.  And of
course it's a toy example, but I don't think it's fair to hold that
against me; a real example would take up a lot of space without being
any more convincing, I suspect.


More information about the Python-ideas mailing list