[Python-ideas] Implicit string literal concatenation considered harmful?

Stefan Behnel stefan_ml at behnel.de
Sat May 11 12:00:36 CEST 2013


Steven D'Aprano, 11.05.2013 07:53:
> In principle, the keyhole optimizer could make that assumption. In
> practice, there is a limit to how much effort people put into the
> optimizer. Constant-folding method calls is probably past the point of
> diminishing returns.

Plus, such an optimisation can have a downside. Contrived example:

    if DEBUG:
        print('a'.replace('a', 'aaaaaaaa').replace('a', 'aaaaaaaa')
              .replace('a', 'aaaaaaaa').replace('a', 'aaaaaaaa')
              .replace('a', 'aaaaaaaa').replace('a', 'aaaaaaaa'))

Expanding this into a string literal will trade space for time, whereas the
original code clearly trades time for space. The same applies to string
splitting. A list of many short strings takes up more space than a split
call on one large string.

May not seem like a major concern in most cases that involve string
literals, but we shouldn't ignore the possibility that the author of the
code might have used the explicit method call quite deliberately.

Stefan





More information about the Python-ideas mailing list