Python Black code formatter doesn't format docstring line length

Question:

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?

Asked By: Daniel O.

||

Answers:

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!

Answered By: ichard26
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.