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

DFS nospam at dfs.com
Tue May 10 12:16:19 EDT 2016


On 5/9/2016 3:53 AM, Steven D'Aprano wrote:
> On Monday 09 May 2016 09:10, DFS wrote:
>
>> sSQL =  "line 1\n"
>> sSQL += "line 2\n"
>> sSQL += "line 3"
>
> Pointlessly provocative subject line edited.


huh?  You called yourself a "master crafts/wo/man".

----------------------------------------------------------------------
DFS: "python is awesome, but too many options for doing the same thing 
also makes it difficult.  For me, anyway."

DuhPricko: "That's the difference between a master and an apprentice. 
The apprentice likes to follow fixed steps the same way each time. The 
master craftsman knows her tools backwards, and can choose the right 
tool for the job, and when the choice of tool really doesn't matter and 
you can use whatever happens to be the closest to hand."
----------------------------------------------------------------------



> Since all three lines are constants know by the programmer at the time the
> source code is written, it should be written as:
>
>
> sSQL = """line 1
> line 2
> line 3"""
>
> Or if you prefer:
>
> sSQL = "line 1\nline 2\nline 3"
>
>
> Or even:
>
> sSQL = ("line 1\n"
>         "line 2\n"
>         "line 3")
>
> taking advantage of Python's compile-time implicit concatenation of string
> constants.

or

sSQL = "line 1\n" \
          "line 2\n" \
          "line 3"



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>

https://www.python.org/dev/peps/pep-0008/#programming-recommendations



'master craftswoman' my ass...




More information about the Python-list mailing list