[Python-ideas] allow line break at operators

Steven D'Aprano steve at pearwood.info
Sun Sep 18 04:18:59 CEST 2011


Arnaud Delobelle wrote:
> On 4 September 2011 23:39, Ben Finney <ben+python at benfinney.id.au> wrote:
>> Ben Finney <ben+python at benfinney.id.au> writes:
>>
>>> MRAB <python at mrabarnett.plus.com> writes:
>>>
>>>> As well as still limiting a comment to a line, I'd also still limit
>>>> a string literal (except a triple-quoted string literal) to a line.
>>> How many string literals do you count in the following statement? I
>>> count one:
>>>
>>>     raise HoustonWeHaveAProblemError(
>>>         "Lorem ipsum dolor sit amet,"
>>>         " consectetur adipiscing elit.")
>> The Python compiler agrees with me:
>>
>>    >>> import dis
>>    >>> def foo():
>>    ...     raise ValueError(
>>    ...         "Lorem ipsum dolor sit amet,"
>>    ...         " consectetur adipiscing elit.")
>>    ...
>>    >>> dis.dis(foo)
>>      2           0 LOAD_GLOBAL              0 (ValueError)
>>
>>      3           3 LOAD_CONST               1 ('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')
>>                  6 CALL_FUNCTION            1
>>                  9 RAISE_VARARGS            1
>>                 12 LOAD_CONST               0 (None)
>>                 15 RETURN_VALUE


Compile-time implicit concatenation of string literals is a guarantee of 
the language. Any Python implementation must do that, going back to at 
least CPython 1.5 and possibly older.


> The code object says that there's one string constant in the compiled
> function.  It says nothing (and knows nothing) about the number of
> string literals that made up this string.  In the following, how many
> string literals can you see?
> 
> 
>>>> def bar(): return "a" + "b"
> ...
> 
> Now let's look at the code object:
> 
> 
>>>> dis.dis(bar)
>   1           0 LOAD_CONST               3 ('ab')
>               3 RETURN_VALUE


I'm not entirely sure I understand your point there. That's the keyhole 
optimizer at work. It does the same thing here:


 >>> dis.dis(compile("1+1", "", "single"))
   1           0 LOAD_CONST               2 (2)
               3 PRINT_EXPR
               4 LOAD_CONST               1 (None)
               7 RETURN_VALUE


and it is an implementation feature, not a language feature. The oldest 
version I can find that does this is CPython 2.5, and there's no 
guarantee that either other implementations or future versions will do 
the same thing.



-- 
Steven




More information about the Python-ideas mailing list