D-string vs str.dedent()

I like the idea and I would like that this syntax could be added by formatters or other tools.

Problem:

I have some files where i have source code in my tests for example:


def test_something():
    code = """\
a=1+2
b=3+4
"""
    ...

I would like if the source code could be converted automatically to the new syntax.
The requirement for such a change would be string == formatting_algo(string)

But I think there would be an problem with the .dedent() approach in combination with f-strings.

def test_something():
    var="(1+\n2)"  # line break without indentation in this string

    code1 = f"""\
        a=1+{var}
        b=3+4
""".dedent()

code2 = f"""\
a=1+{var}
b=3+4
"""
    
    assert code1 == code2  # would fail
    ...

This would mean that .dedent() could not be used by tooling to automatically indent the f-strings.
It would also mean that it is not possible to change the indentation for a f-string which is already indented with .dedent()

For this reason, I would prefer the d"", because it applies the dedent before the variable replacement.

But I would also recommend you to ask someone who writes formatter for his opinion.

1 Like