upvote
I find that decision a bit odd given that accumulating a string with a loop is also quadratic in Python if you use = instead of +=, or even if you use += when the left operand isn't provably unshared. I don't believe removing loops was seriously considered.

The footgun isn't `reduce` in particular, but failing to use `join`.

reply
I suppose `reduce` as built-in is the footgun because it's too easy to reach for. Now if someone doesn't know about `join` perhaps they look up how to do it because they think 'surely there's a better way than a loop without an import'.
reply
Doesn't reduce force the accumulator to be shared though? Both the reduce and the lambda are holding onto references to acc, which defeats any "single reference" optimizations.
reply
The problem with:

    ret = ""
    for s in strings:
        ret += s
is that it re-allocates O(n) times, even if ret is referenced only once.
reply
If the s are small the usual geometric buffer growth mitigates that. Of course you can compute the final buffer size in this case, but often you have a bunch of dynamically-generated strings of different sizes.
reply

  def reduce(acc, f): 
    for v in self:
      acc = f(acc, v)
    return acc
The current acc goes out of scope each time you call f. There's no shared reference (assuming f doesn't sneak store it elsewhere, which for string combining, f should just be `return a+b`?).
reply
The binding for acc in the reduce call is still active during the f call, which means there are at least two references to acc.
reply
Why is it still active? Even an interpreter with no lookahead could see that it goes out of scope immediately when f returns (it gets shadowed on that line), so as long as there's no guarantee about when finalizers get called, it should be able to mark it dead inside of reduce as soon as it's passed to f. Like move semantics here should be a general pattern for optimization, no?
reply
Does Python actually do that? If the f call throws, you can still observe the (unchanged) binding of acc in reduce.
reply
Fair, I suppose there's no end to the level of insanity that a programmer can do in a dynamic language. I'd think it could perhaps still look to see there's no catch, but maybe eval makes even that impossible.
reply
It might - let's assume it does. My point is that it's better to use the explicit optimized method for joining strings in a performance-sensitive context than to try to meet the conditions for an implicit optimization.
reply
So rather than provide a runtime or compiler optimization, we force the programmer to do it by hand. This is why I don’t like Python philosophically.
reply
I don't believe Python had a compiler in 2006...
reply
Python has always had a bytecode compiler that did some minor optimizations, since its inception in the 90's. The issue is that optimizations are very hard to do correctly in the compiler because Python is so dynamic. Any piece of code could suddenly redefine mytype.__add__() and so forth.
reply
It had a runtime
reply
This always feels odd to me. It would seem a fairly straight forward optimization of the interpreter to special case the different types that it can reduce.

That is, why couldn't they have done the essentially same trick that you reference for += with reduce?

reply
There is no such trick. Python is only now getting those sort of JIT style optimizations, and that one in particular still hasn't hit. Do not use += on strings in a loop unless you are certain the iteration count will be small.

There is an optimization for lists, and maybe that's what GP is remembering. l += is functionally different from l = l +. The former mutates l, whereas the latter creates a new l. The difference matters when the line above is m = l. The mutation version will mutate m as well (they're the same reference), the creates new version will not. This optimization can just as easily turn into a footgun if the programmer is unaware of it, and in that sense is unpythonic.

reply
Python has optimized string appending in the form of:

s = s + "foo"

and

s += "foo"

Since 2005 with the release of Python 2.4:

https://docs.python.org/3/whatsnew/2.4.html#optimizations

reply
I’m not a fan of this kind of “fancy” optimization anyway.

It’s too fragile. I may make some innocuous change, now the compiler cannot recognize the pattern and performance falls off the cliff.

I’d rather have the reliabile performance than the absolute fastest possible result. Then if there’s an issue I can catch and fix it reliably with profiling, not deal with a heisenbug based on whether the compiler can match the pattern.

reply
That sounds nice but in practice it’s probably not super helpful. Yes you could make a special case for reducing “+” over integers. But in python you can generally not promise that all the inputs are strictly integers, and you can’t even promise that your “+” function has no side effects.
reply
[flagged]
reply
2006...would that have been Mondrian?
reply
Yes!
reply
Maybe you are misremembering the story? += deferred concatenation requires lazy strings and that didn't come until 10-15 years later. However, concatenating string lists with sum() was a common Python idiom at the time and it indeed incurred O(n^2) complexity. Gvr's reduce dislike was more about its syntax. It doesn't mesh well with Python's lambda syntax.
reply
> += deferred concatenation requires lazy strings and that didn't come until 10-15 years later.

CPython's += does not perform deferred concatenation and CPython does not use lazy strings. The optimization uses an eager in-place realloc if the string's ref-count is 1. This remains the optimization used even to this day and was introduced in 2005:

https://docs.python.org/3/whatsnew/2.4.html#optimizations

>However, concatenating string lists with sum() was a common Python idiom at the time

It could not possibly have been a common Python idiom since sum() explicitly rejected strings by throwing a TypeError. This was explicitly special cased to avoid the degenerate performance and the TypeError even has an error message saying "TypeError: sum() can't sum strings [use ''.join(seq) instead]".

>Gvr's reduce dislike was more about its syntax. It doesn't mesh well with Python's lambda syntax.

No it had nothing to do with mixing with lambda syntax, on the contrary GvR actually wanted to remove reduce and lambda (and map and filter as well). Here is the actual article by GvR regarding removing reduce, absolutely nothing in it involves how it mixes with lambda expressions.

https://www.artima.com/weblogs/viewpost.jsp?thread=98196

>So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

reply
Yes thanks for finding the Python 2.4 release page which shows the optimization! So I remembered correctly -- Python already had that optimization back then. (There seems to be a large amount of confusion on that in this subthread)

And the March 2005 Artima post is also a very good reference! That actually predates my story, since Guido hadn't joined Google by then. I recall that he joined in December 2005.

So maybe the bug I remember was more of a "push" in the direction he had already thought of, not the direct inspiration.

It's clear from the blog post that he disliked all of map / filter / reduce, and then I'm sure that users or python-dev pushed back on removing them, so he settled for banishing reduce() to the stdlib.

reply
The way I understand it, the map,filter,reduce functions in python exist as pythonic language constructs:

-map: [x*2 for x in xs]

-filter: [x for x in xs if x%0==2]

-reduce: ummm..

Maybe something like:

sum = x+ret for x in xs from ret=0

reply
That one is built in:

  sum([1, 2, 3]) == 6
reply
Maybe the closest is 'join' similar to `",".join([...])`? If we could replace the string with an operator
reply