[Python-ideas] Function composition (was no subject)

Steven D'Aprano steve at pearwood.info
Sun May 10 11:57:30 CEST 2015


On Sun, May 10, 2015 at 07:25:31PM +1000, Chris Angelico wrote:

> strings = [
>     "String one",
>     "String two is a bit longer"
>     "String three",
>     "String four"
> ]
> 
> How many strings are there in my list? Clearly the programmer's
> intention is to have four, but that's not what ends up happening. (Now
> imagine there are actually hundreds of strings, and one gets selected
> at random every time you do something.

If you are embedding hundreds of strings in the source, instead of 
reading them from a file, you deserve whatever horribleness you get :-)


> Have fun figuring out why, just
> occasionally, it prints out two messages instead of one.

That would actually be pretty easy to solve. When you get the unexpected 
"String two is a bit longerString three" message, just grep through the 
file for the first few words, and lo and behold, you are missing a 
comma.

But your point about syntactically meaningful whitespace is otherwise a 
good one. Python doesn't give whitespace in expressions any particular 
meaning, except as a separator. I'd be very dubious about making 
function composition an exception. 


> So I would strongly suggest having some sort of operator in between.
> Okay. Can I just say something crazy? (Hans: I love crazy!) How about
> using a comma?
> 
> >>> (fn1, fn2, fn3, ...)('string to be piped')
> 
> Currently, this produces a runtime TypeError: 'tuple' object is not
> callable, but I could easily define my own callable subclass of tuple.

There's lots of code that assumes that a tuple of functions is a 
sequence:

for f in (len, str, ord, chr, repr):
    test(f)

so we would need to keep that. But we don't want a composed function to 
be a sequence, any more than we want a partial or a regular function to 
be sequences. If I pass you a Composed object, and you try slicing it, 
that should be an error.


-- 
Steve


More information about the Python-ideas mailing list