On 3/14/2018 8:18 AM, Facundo Batista wrote:
Hello!

What would you think about formally descouraging the following idiom?

     long_string = (
         "some part of the string "
         "with more words, actually is the same "
         "string that the compiler puts together")

-1

We should write the following, instead:

     long_string = (
         "some part of the string " +
         "with more words, actually is the same " +
         "string that the compiler puts together")


Note that there's no penalty in adding the '+' between the strings,
those are resolved at compilation time.

Not always, as Eryk Sun discussed.

When f-strings are thrown into the mix, as when creating multi-line messages with interpolated values, not even true in 3.7. Compare the following:

>>> def f():
        x = input('x:')
        print(f'a{x}bc' 'def')

>>> dis.dis(f)
  2           0 LOAD_GLOBAL              0 (input)
              2 LOAD_CONST               1 ('x:')
              4 CALL_FUNCTION            1
              6 STORE_FAST               0 (x)

  3           8 LOAD_GLOBAL              1 (print)
             10 LOAD_CONST               2 ('a')
             12 LOAD_FAST                0 (x)
             14 FORMAT_VALUE             0
             16 LOAD_CONST               3 ('bcdef')
             18 BUILD_STRING             3
             20 CALL_FUNCTION            1
             22 POP_TOP
             24 LOAD_CONST               0 (None)
             26 RETURN_VALUE

>>> def f():
        x = input('x:')
        print(f'a{x}bc' + 'def')

>>> dis.dis(f)
  2           0 LOAD_GLOBAL              0 (input)
              2 LOAD_CONST               1 ('x:')
              4 CALL_FUNCTION            1
              6 STORE_FAST               0 (x)

  3           8 LOAD_GLOBAL              1 (print)
             10 LOAD_CONST               2 ('a')
             12 LOAD_FAST                0 (x)
             14 FORMAT_VALUE             0
             16 LOAD_CONST               3 ('bc')
             18 BUILD_STRING             3
             20 LOAD_CONST               4 ('def')
             22 BINARY_ADD
             24 CALL_FUNCTION            1
             26 POP_TOP
             28 LOAD_CONST               0 (None)
             30 RETURN_VALUE

The '+' prevents compile time concatenation of 'bc' and 'def' and adds a load and binary add.

--
Terry Jan Reedy

_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to