Python Black code formatter doesn't format docstring line length?
Asked Answered
F

1

31

I am running the Black code formatter against a Python script however it doesn't reformat the line length for docstrings. For example, given the following code:

def my_func():
    """
    This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring.
    """
    return

When running Black against this script, the line length does not change. How can I ensure docstrings get formatted when running Black?

Fragrant answered 3/2, 2022 at 5:26 Comment(1)
Does this help? https://mcmap.net/q/430508/-python-black-doesn-39-t-wrap-long-linesCheapen
S
44

maintainer here! :wave:

The short answer is no you cannot configure Black to fix line length issues in docstrings currently.

It's not likely Black will split or merge lines in docstrings as it would be far too risky, structured data can and does exist in docstrings. While I would hope the added newlines wouldn't break the consumers it's still a valid concern.

There's currently an open issue asking for this (although it also wants the line length limit for docstrings and strings to be 79) GH-2289, and specifically for docstrings GH-2865. You can also read GH-1713 which is about splitting comments (and likewise has mixed feelings from maintainers).

For the time being, perhaps you can look into https://github.com/PyCQA/docformatter which does seem to wrap docstrings (see the --wrap-descriptions and --wrap-summaries options)


P.S. if you're curious whether we'll add a flag to split docstrings or comments, it's once again unlikely since we seek to minimize formatting configurability. Especially as the pre-existing flags only disable certain elements of Black's style (barring --line-length which exists as there's no real consensus what it should be). Feel free to state your arguments in the linked issues tho!

Substantialize answered 8/2, 2022 at 21:36 Comment(1)
Maybe we could have just a little indicator on VSCode showing us where it exceeds 72 characters so we can split to next line where we see the indicator?Bosanquet

© 2022 - 2024 — McMap. All rights reserved.