Steve D'Aprano, you're the "master". What's wrong with this concatenation statement?

Stephen Hansen me+python at ixokai.io
Tue May 10 12:42:58 EDT 2016


On Tue, May 10, 2016, at 09:16 AM, DFS wrote: 
> But no, "master", your answers are incorrect.  What's wrong with that 
> concat statement is that += concatenation is frowned upon by python's 
> creator, and is not recommended (in PEP8):
> 
> <quote>
> Code should be written in a way that does not disadvantage other 
> implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and 
> such).
> 
> For example, do not rely on CPython's efficient implementation of 
> in-place string concatenation for statements in the form a += b or a = a 
> + b . This optimization is fragile even in CPython (it only works for 
> some types) and isn't present at all in implementations that don't use 
> refcounting. In performance sensitive parts of the library, the 
> ''.join() form should be used instead. This will ensure that 
> concatenation occurs in linear time across various implementations.
> </quote>

You once again misread PEP8. 

Not one of Steven's answers used string concatenation, except for the
implicit literal concatenation, which all other implementations support.

Note:

> sSQL = """line 1
> line 2
> line 3"""

No concatenation. One string literal. Works in all implementations.

> sSQL = "line 1\nline 2\nline 3"

No concatenation. One string literal. Works in all implementations.

>
> sSQL = ("line 1\n"
>         "line 2\n"
>         "line 3")

Concatenation occurs at compile time, implicitly. Works in all
implementations.

The PEP says when building a string dynamically (that is, adding
together two strings that exist and are separate), use "".join() in
performance sensitive places. It says don't combine two strings with the
addition operator -- because while that's sometimes efficient in
CPython, the language doesn't guarantee it.

You'll notice that the one time Steven combined two strings, it was
implicitly at compile time.

In every Python implementation, it is guaranteed that:

>>> a = "a" "a"
>>> b = "aa"

Are the same. Two+ string literals are implicitly combined into one at
compile time.

> 'master craftswoman' my ass...

Yes, you're being that. Please stop.

-- 
Stephen Hansen
  m e @ i x o k a i . i o



More information about the Python-list mailing list