[Python-Dev] Usage of += on strings in loops in stdlib

Xavier Morel python-dev at masklinn.net
Tue Feb 12 23:33:56 CET 2013


On 2013-02-12, at 22:40 , Ned Batchelder wrote:
> But the only reason "".join() is a Python idiom in the first place is because it was "the fast way" to do what everyone initially coded as "s += ...".   Just because we all learned a long time ago that joining was the fast way to build a string doesn't mean that "".join() is the clean idiomatic way to do it.

Well no, str.join is the idiomatic way to do it because it is:

> idiomatic |ˌidēəˈmatik|
> adjective
> 1 using, containing, or denoting expressions that are natural to a native speaker 

or would you argue that the natural way for weathered python developers
to concatenate string is to *not* use str.join?

Of course usually idioms have original reasons for being, reasons which
are sometimes long gone (not unlike religious mandates or prohibitions).

For Python, ignoring the refcounting hack (which is not only cpython
specific but *current* cpython specific *and* doesn't apply to all
cases) that reason still exist: python's strings are formally immutable
bytestrings, and repeated concatenation of immutable bytestrings is
quadratic.

Thus str.join is idiomatic, and although it's possible (if difficult) to
change the idiom straight string concatenation would make a terrible new
idiom as it will behave either unreliably (current CPython) or simply
terribly (every other Python implementation).

No?


More information about the Python-Dev mailing list