[formatter] Indent docstrings using configured indent_style #9173
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Ruff currently always formats docstrings using spaces for indentation. However, when
indent-style
is set to "tab", this leads to E101 (mixed indentation) linter errors.There are a few approaches to improving the situation, some of which are discussed in #8430. One option which is likely the simplest is to recommend turning off E101 when using the formatter. If this is the preferred route, then Ruff should probably also respect the
indent-width
when expanding tabs in docstrings to avoid the issue described here.This PR implements an alternative solution which indents docstrings using the configured
indent-style
. In cases where docstrings have indents that aren't a multiple of theindent-width
, this may mean E101 is still triggered in the formatted code. However, this should be very uncommon. I did a cursory check of the few codebases across GitHub that use Ruff with tabs and could not find any cases where docstrings would be negatively affected by this change.Note that this means that Ruff will format code with tabs differently than Black, which always expands tabs to 8 spaces. I think this is acceptable in this case, because Black doesn't support tabs to begin with (so there's no real compatibility issue).
There is also the question of how other tooling treats tabs in docstrings. As of Python 3.13, docstrings will be dedented to save memory. However, tabs will also unfortunately be expanded to 8 spaces by the interpreter, which will negate the memory usage savings, but this difference should also be mostly inconsequential (and this may potentially be fixed in CPython in the future.)
Closes #8430