Uniform Function Call Syntax (UFCS)

jongiddy jongiddy at gmail.com
Sun Jun 8 12:24:56 EDT 2014


On Sunday, 8 June 2014 13:06:08 UTC+1, Paul Sokolovsky  wrote:
> 
> Getting x.foo() to call foo(x) is what's bigger problem, which has
> serious performance and scoping confusion implications, as discussed in
> other mails.

The performance hit will only occur when the attribute access is about to throw an AttributeError.  Successful attribute accesses would be just as fast as before.  And the cost of a symbol lookup is usually considered cheap compared to a thrown exception, so I don't believe there is a serious performance implication.

As to the scoping confusion, I repeat that Python benefits from the fact that most modules will only have the builtins and local functions to worry about.  This is a small enough space for users to manage.  There's no surprises waiting to occur when the user adds or removes normal imports (a problem that can occur in D).

> > It also adds
> > significant readability improvements by putting function-call chains
> > in order.
>
> Not sure what exactly you mean, but the order is usually pretty obvious
> - Python follows mathematical notation for function calls, and OO
> standard notation for method calls, one known from primary school,
> another from secondary (hopefully). They can be reordered with
> parentheses, which is also well-known basic math technique.

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, and arguments like b64encode's b'?-' are near the function call, making it a lot more obvious with which function this obscure argument is used.

Note, I'm not suggesting either of these examples is good programming, but the same problem does occur in more reasonable scenarios - I just made this example a little extreme to emphasise the readability benefits.



More information about the Python-list mailing list