[Python-ideas] Infix functions

Andrew Barnert abarnert at yahoo.com
Tue Feb 25 01:11:19 CET 2014


On Feb 24, 2014, at 7:28, Steven D'Aprano <steve at pearwood.info> wrote:

> but really, these are just jokes. I'm still no closer to actual 
> use-cases.

I will repeat one that I already posted, but try to put it differently: a using function that wraps a with statement.

Every kind of statement in Python would sometimes be useful as an expression. You can always wrap the statement in a function, but it looks ugly--even with Nick's concise lambda proposal. For example, lets say we wrapped with, try/except, and if/else in functions named using, catch, and cond:

    data = using(:?.read(), open(path))
    buf = catch(:read_file(path), (FileNotFoundError, :'')
    b = cond(a, :1/a, :NaN)

All of these are possible today, but were not sufficient to curb the desire for with, except, and if expressions. One was already added, one is under consideration, and the last gets suggested at least once/year.

But if you could infix those functions:

    data = :?.read() `using` open(path)
    buf = :read_file(path) `catch` FileNotFoundError, :''
    b = a `cond` :1/a, :NaN

Would they then be good enough to obviate the need for new syntax?

I assume not having to add a corresponding expression for every statement is a desirable goal. The only question is whether this would help achieve that goal.

> Any infix binary operator a `op b can be written as a function of two 
> arguments, op(a, b).

Of course. The whole point of the idea--in the very first paragraph of the initial post--is that a `op` b would be compile to the exact same code as op(a, b). (Others have suggested that maybe a method would be better, but that doesn't change the point.) This is pure syntactic sugar for those functions, nothing else.

> 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.

The question is not whether they can be written as functions, but whether those functions' calls can be read more easily with infix syntax.


More information about the Python-ideas mailing list