Trimmed multiline string

Yes, this has come up before. - It is tracked as https://bugs.python.org/issue36906 - I’m in favor of solving it at the language level.

inspect.cleandoc() and textwrap.dedent() are not solutions. They have a run-time cost and the process is forced to carry the burden of the extra padded string data around with it in memory.

I’d like it if all docstrings were treated this way by default (without a prefix) but I’m assuming there are objections to a context dependent semantic change. Practicality beats purity is my response even if I don’t expect to win that one.

Options for dedicated syntax (the actual desire):

  1. Add yet another letter prefix such as t or m or d or c (and argue about which letter).

  2. Reuse the backquote (backtick) character now that we have removed it as a token and feature in Python 3. We could introduce a ``` token that acts as an auto-cleandoc’d or dedent’d multi-line string. (the other letter prefixes would apply to it). I intentionally recommend not supporting a single backquote, only a new triple tick token. That way it avoids python 2 ` repr vs python 3 syntax concerns.

A drawback to all options: Yet more new syntax.

Drawback on #1: The letter prefix makes no sense on a single quote string, but we’ve not differentiated between single or triple quotes when it comes to prefixes in the past. It’d be a no-op on single line string literals unless we decided to break that rule.

Drawback on #2: An sad downside to ``` is that it is virtually impossible to represent within most markdown documentation rendering engines. And markdown is crazy-popular. They don’t have a way - or don’t have a consistent way - to escape a triple backquote within the middle of their own multi-line. :confused:

>>> def castle_argh(self):
...    return ```multi-line
... 
...    dedented string.
...    ```
... 
>>> castle_argh()
'multi-line\n\ndedented string\n'

That only renders in here Discourse today because i added the REPL prefixes on the line. I can’t write a cut and pasteable code snippet using those. <pre> tags appear to work here, but lose syntax highlighting. And there seem to be 183 markdown renderer implementations out there (Github itself applies multiple to the same files!), each of which varies its behavior between one another and over time.

Upside to #2: People are already used to reading ``` as a multi-line block thanks to markdown! :slight_smile:

Example implementations in PRs along with a PEP laying this out would help.

2 Likes