When does python compile the constant string letters, to combine the strings into a single constant string?

It happens whenever the combined string is 20 characters or fewer.

The optimization occurs in the peephole optimizer. See line 219 in the fold_binops_on_constants() function in Python/peephole.c: http://hg.python.org/cpython/file/cd87afe18ff8/Python/peephole.c#l149


@Raymond Hetting's answer is great, vote for that (I did). I'd make this a comment, but you can't format code in a comment.

If you go over the 20 character limit, the disassembly looks like:

>>> dis.disassemble(compile("s = '1234567890' + '09876543210'", "<execfile>", "exec"))
  1  0 LOAD_CONST  0 ('1234567890')
     3 LOAD_CONST  1 ('09876543210')
     6 BINARY_ADD
     7 STORE_NAME  0 (s)

But in the case where you have two string literals, remember you can leave out the + and use String literal concatenation to avoid the BINARY_ADD (even when the combined string length is greater than 20):

>>> dis.disassemble(compile("s = '1234567890' '09876543210'", "<execfile>", "exec"))
  1  0 LOAD_CONST  0 ('123456789009876543210')
     3 STORE_NAME  0 (s)

Tags:

Python