print - bug or feature - concatenated format strings in a print statement

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Mar 18 09:11:49 CET 2009


On Tue, 17 Mar 2009 22:41:26 -0700, John Machin wrote:

> On Mar 18, 4:19 pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote:

>> The implicit string concatenation is actually done by the compiler; it
>> isn't an operator at all. Look:
>>
>> >>> import dis
>> >>> def f():
>>
>> ...     return "foo" "bar"
>> ...>>> dis.dis(f)
>>
>>   2           0 LOAD_CONST               1 ('foobar')
>>               3 RETURN_VALUE
>> --
> 
> I think you need better evidence than that obtained by proctologising
> about with dis.dis:
> 
> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)] onwin32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import dis
>>>> def f():
> ...    return ('foo') + ('bar')
> ...
>>>> dis.dis(f)
>   2           0 LOAD_CONST               3 ('foobar')
>               3 RETURN_VALUE


That's the keyhole optimizer in action. It replaces operations on two 
literals at compile-time whenever possible. By memory, that was 
introduced by Python 2.4, and implicit string concatenation was 
introduced way back in the mists of time. In Python 2.1 we have this:


>>> dis.dis(compile("'ab' 'cd'", '', 'single'))
          0 SET_LINENO               0

          3 SET_LINENO               1
          6 LOAD_CONST               0 ('abcd')
          9 PRINT_EXPR
         10 LOAD_CONST               1 (None)
         13 RETURN_VALUE
>>>
>>> dis.dis(compile("1+1", '', 'single'))
          0 SET_LINENO               0

          3 SET_LINENO               1
          6 LOAD_CONST               0 (1)
          9 LOAD_CONST               0 (1)
         12 BINARY_ADD
         13 PRINT_EXPR
         14 LOAD_CONST               1 (None)
         17 RETURN_VALUE



I suppose, technically, implicit string concatenation could happen inside 
the lexer, or the parser, or some other process, but I think most people 
are happy to simplify all of those as "the compiler". Whenever it 
happens, the important thing is that it is *not* at runtime. 



-- 
Steven



More information about the Python-list mailing list