Uniform Function Call Syntax (UFCS)

Ian Kelly ian.g.kelly at gmail.com
Sun Jun 8 12:38:43 EDT 2014


On Sun, Jun 8, 2014 at 9:56 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Paul Sokolovsky <pmiscml at gmail.com>:
>
>> Python already has that - like, len(x) calls x.__len__() if it's
>> defined
>
> In fact, what's the point of having the duality?
>
>    len(x) <==> x.__len__()
>
>    x < y <==> x.__lt__(y)
>
>    str(x) <==> x.__str__()

Python prefers having functions for operations that are common to a
lot of types rather than methods.  This allows for consistency of
interface -- think of len() as the interface and .__len__() as the
implementation. If .len() were the interface then it would be easy
(and probably all too common) for Python programmers to change those
interfaces in subclasses.  It also means that if you want to pass the
len function itself around, you just pass around len and know that it
will work generally -- instead of passing around list.len and hoping
that whatever it gets applied to is a list.

This is a fair point against UFCS -- if x.len() comes to mean len(x)
then it both makes it easy to change that interface (at least for the
x.len() spelling) and makes it easier to pass around the function's
implementation rather than its interface.

> What do you think? Would you rather write/read:
>
>    if size + len(data) >= limit:
>
> or UFCS-ly:
>
>    if size.__add__(data.__len__()).__le__(limit):

You may be misunderstanding the proposal.  The UFCS style of that would be:

    if size + data.len() <= limit:



More information about the Python-list mailing list