> On Jan 19, 2020, at 12:57, Steven D'Aprano <[email protected]> wrote:
>
> On Sun, Jan 19, 2020 at 02:37:14PM -0500, David Mertz wrote:
>> The "fluent interface" (https://en.wikipedia.org/wiki/Fluent_interface) is
>> popular in many programming languages, including in the sort of
>> "mini-language" Pandas, within portion.
>
> I can't speak about Pandas, but what the OP is expecting to do is not a
> fluent interface. It's just method chaining. We do method chaining all
> the time with immutable "value objects" like strings:
>
> result = mystring.upper().strip().center(width).encode('utf-8')
>
> and nobody blinks an eye or calls it unpythonic.
It’s not even immutable that’s the key thing here, but nonmutating. Even on
mutable types, Python encourages you to chain up nonmutating operations. And it
goes beyond linear chaining; you can compose any nonmutating method calls,
function calls, operators, and comprehensions you want. And it only becomes
unpythonic it if gets too complicated to eye-parse. But you can’t compose
mutating method calls, you have to imperatively chain them up as separate
statements.
You can even see this in the OP’s problem. He didn’t want to mutate
list(range(10)); that’s a garbage value. But he did want to get the value
that’s list(range(10)) with the list [10] stuck on the end, and Python does
make that trivial:
list(range(10)) + [10]
You might not want to do that if 10 is an arbitrarily large user-supplied
value, because that extra copy could be a serious performance cost. But in most
such cases the list is a serious performance cost in the first place, and you
really just wanted to use the range itself as an Iterable and itertools.chain
it.
When you have a nonmutating algorithm, you usually can compose it up roughly
the same way you would in Haskell; when you have an in-place algorithm you
usually can write it as a chain of imperative statements roughly the same way
you would in C. Python only gets in your way when you have a mishmash of the
two where it would make sense to write confusing things like `lst.sort() +
lst.remove(10)` or a comprehension that mutates as it goes. Good uses of that
kind of mishmash do exist, but aren’t that common.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/CNXO2YF5PANA6MX6TJUETDA7YVFVANGN/
Code of Conduct: http://python.org/psf/codeofconduct/