Indented multi-line strings

Chris Angelico rosuav at gmail.com
Fri Jun 1 13:34:54 EDT 2018


On Sat, Jun 2, 2018 at 2:10 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> On 1 June 2018 at 16:36, Chris Angelico <rosuav at gmail.com> wrote:
>> On Sat, Jun 2, 2018 at 12:57 AM, Paul Moore <p.f.moore at gmail.com> wrote:
>
>>> Why does this need to be a string method? Why can't it be a standalone
>>> function? Maybe you should publish an implementation on PyPI, collect
>>> some data on how popular it is, and then if it's widely used, propose
>>> it for inclusion in the stdlib at that point? By making it a string
>>> method, you're also restricting its use to users of recent versions of
>>> Python, whereas a PyPI implementation would work for everyone.
>>
>> The biggest reason to make it a string method is to give the
>> possibility of optimization. Python cannot optimize int(1.2) down to
>> the constant 1 because you might have shadowed int; but a method on a
>> string literal cannot be shadowed, and could potentially be
>> constant-folded. Include that in the initial post to preempt this
>> recommendation.
>
> So the optimisation should probably be an explicit part of the
> proposal. Without the optimisation, factors like "won't be usable in
> code that wants to support older Python", "why not just make it a
> standalone function", etc. will probably result in the proposal not
> getting accepted.

There's already an existing function, albeit not the most
discoverable. But people avoid it because it's a run-time cost, and
deleting the leading spaces in the source code eliminates that
run-time cost.

> OK, so unless the argument is "provide a string method, that's
> guaranteed to be constant folded"[1] I suspect that it's pretty
> unlikely that a proposal to add a string method that simply replicated
> the textwrap functions would get very far.
>
> [1] There's two possibilities here, of course. First, provide an
> implementation for CPython that includes the constant folding, or
> second, make constant folding a language guarantee that other
> implementations also have to implement. I doubt the second option is
> going to be practical, though.

I wouldn't make it an actual guarantee. As long as CPython has the
optimization, people will start using it; if Jython or MicroPython or
Brython does a run-time method call, so be it. It's still likely to be
faster than importing a module, but most importantly, people's code
will look better this way than manually unindented.

ChrisA



More information about the Python-list mailing list