Skip to content

Add ability to preserve some whitespace in textwrap.dedent #133090

@Ashark

Description

@Ashark

Feature or enhancement

Proposal:

From textwrap.dedent() documentation (https://docs.python.org/3/library/textwrap.html):

Remove any common leading whitespace from every line in text.
Note that tabs and spaces are both treated as whitespace,

Sometimes, I want to use textwrap.dedent(), but at the same time, I want it to not cut-off some "wanted" whitespace.

For example, in some places of my project, I want to form a multiline string, where each string is starting with a "\t". Like this:

Attempting to use like this:

                logger_module.warning(textwrap.dedent(f"""\
                    \tr[b[*] Unable to move {old_source_dir}
                    \tr[b[*] to {fullpath}
                    \tr[b[*] Error: {e}
                    \ty[b[*] Will proceed, generating a new source dir."""))

Unfortunately (and expectedly), it removes all leading whitespaces with the starting tabulation symbols.

In my specific project (kde-builder), as a workaround, I could use "]" in the beginning of lines (in the project, the "]" in string is treated as escape sequence for unsetting colored output).
This way, as textwrap.dedent considers "]" as non-whitespace, it preserves the following "\t".

My workaround:

                logger_module.warning(textwrap.dedent(f"""\
                    ]\tr[b[*] Unable to move {old_source_dir}
                    ]\tr[b[*] to {fullpath}
                    ]\tr[b[*] Error: {e}
                    ]\ty[b[*] Will proceed, generating a new source dir."""))

But I would like to be able to not use crutches, and instead use universal solution. For example, a dedent() method could have a parameter to preserve specific substring in the beginning:
like this: preserve_substring="\t", and so

                logger_module.warning(textwrap.dedent(f"""\
                    \tr[b[*] Unable to move {old_source_dir}
                    \tr[b[*] to {fullpath}
                    \tr[b[*] Error: {e}
                    \ty[b[*] Will proceed, generating a new source dir.""", preserve_substring="\t"))

could work as I expect.

Can this be added please?

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions