Uniform Function Call Syntax (UFCS)

Chris Angelico rosuav at gmail.com
Sun Jun 8 13:10:03 EDT 2014


On Mon, Jun 9, 2014 at 2:24 AM, jongiddy <jongiddy at gmail.com> wrote:
> A contrived example - which of these is easier to understand?
>
> from base64 import b64encode
>
> # works now
> print(b64encode(str(min(map(int, f.readlines()), key=lambda n: n % 10)), b'?-'))
>
> # would work with UFCS
> f.readlines().map(int).min(key=lambda n: n % 10).str().b64encode(b'?-').print()
>
> You can read the second form left to right

Actually, this is something that I've run into sometimes. I can't
think of any Python examples, partly because Python tends to avoid
unnecessary method chaining, but the notion of "data flow" is a very
clean one - look at shell piping, for instance. Only slightly
contrived example:

cat foo*.txt | gzip | ssh other_server 'gunzip | foo_analyze'

The data flows from left to right, even though part of the data flow
is on a different computer.

A programming example might come from Pike's image library [1]. This
definitely isn't what you'd normally call good code, but sometimes I'm
working at the interactive prompt and I do something as a one-liner.
It might look like this:

Stdio.write_file("foo.png",Image.PNG.encode(Image.JPEG.decode(Stdio.read_file("foo.jpg")).autocrop().rotate(0.5).grey()));

With UFCS, that could become perfect data flow:

read_file("foo.jpg").JPEG_decode().autocrop().rotate(0.5).grey().PNG_encode().write_file("foo.png");

I had to solve the syntactic ambiguity here by importing all the
appropriate names, which does damage readability a bit. But you should
be able to figure out what this is doing, with only minimal glancing
at the docs (eg to find out that rotate(0.5) is rotating by half a
degree).

So the proposal does have some merit, in terms of final syntactic
readability gain. The problem is the internal ambiguity along the way.

ChrisA

[1] http://pike.lysator.liu.se/generated/manual/modref/ex/predef_3A_3A/Image/Image.html



More information about the Python-list mailing list