[Python-ideas] Dart like multi line strings identation

Chris Angelico rosuav at gmail.com
Sun Apr 1 08:55:34 EDT 2018


On Sun, Apr 1, 2018 at 10:36 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> And that *mental complexity* is (in my opinion) the biggest issue with
> adding a new d-prefix, and why I would rather make it a method.
>
> Another big advantage of a method is that we can apply it to
> non-literals too.

I'd like to expand on this a bit more.

Current string prefix letters are:

* u/b: completely change the object you're creating
* f: change it from a literal to a kind of expression
* r: change the interpretation of backslashes
* triple quotes: change the interpretation of newlines

All of these are significant *to the parser*. You absolutely cannot do
any of these with methods (well, maybe you could have u/b done by
having a literal for one of them, and the other is an encode or decode
operation, but that's a pretty poor hack).

But dedenting a string doesn't change the way the source code is
interpreted. So it's free to be a method - which is far easier to add
to the language. All you need is ".dedent()" to be syntactically
parsed as a method call (which it already is), and every tool that
processes Python code will correctly interpret this.

So here's what, IMO, Marius can push for:

1) A method on Unicode strings which does the same as textwrap.dedent()
2) A peephole optimization wherein certain methods on literals get
executed at compile time.

The latter optimization would also apply to cases such as " spam
".strip() - as long as all it does is return another constant value,
it can be done at compile time. Semantically, though, the part that
matters is simply the new method. (Sadly, this can't be applied to
Decimal("1.234"), as that's not a method and could be
shadowed/mocked.)

While I wouldn't use that method much myself, I think it's a Good
Thing for features like that to be methods rather than functions
stashed away in a module. (How do you know to look in "textwrap" for a
line-by-line version of x.strip() ??) So I would be +1 on both the
enhancements I mentioned above, and a solid -1 on this becoming a new
form of literal.

ChrisA


More information about the Python-ideas mailing list