Search code examples
pythonblack-code-formatter

Getting Black Python code formatter to align comments


Yes, I'm, of the understanding that black gives very little leeway in getting it to act differently but I was wondering about the best way to handle something like this (my original code):

@dataclass
class Thing1:
    property1: int                    # The first property.
    property2: typing.List[int]       # This is the second property
                                      # and the comment crosses multiple lines.

Now, when I run that through black, it gives me:

@dataclass
class Thing1:
    property1: int  # The first property.
    property2: typing.List[int]  # This is the second property
    # and the comment crosses multiple lines.

which is not really laid out as I'd like.

Is there a way to get black to keep the comments lined up? I don't care which column it starts in per field, but it would be nice to return to the readable nature, with the comments within each field being lined up:

@dataclass
class Thing1:
    property1: int  # The first property.
    property2: typing.List[int]  # This is the second property
                                 # and the comment crosses multiple lines.

If there's no way to do this, I'll probably either place multi-line comments before each field, or ensure all comments fit on the one line and add lengthier explanatory notes at the end of the dataclass definition:

@dataclass
class Thing1:
    property1: int  # The first property.

    # This is the second property and the comment, while it can
    # have more characters, still crosses multiple lines.
    property2: typing.List[int]

@dataclass
class Thing2:
    property1: int  # The first property.
    property2: typing.List[int]  # This is the second property.

    # Note that the comments above now fit on the same line as the
    # field, and this comment here is meant to provide any needed
    # multi-line detail for ALL fields in this class.

That at least is still somewhat local to the data fields. But I'd rather find a way to have it line up comments similar to what I originally had, if possible.

Happy to entertain any suggestions.


Solution

  • You can wrap your block with # fmt: on/off, so Black doesn't touch it.

    # fmt: off
    @dataclass
    class Thing1:
        property1: int               # The first property.
        property2: typing.List[int]  # This is the second property
                                     # and the comment crosses multiple lines.
    # fmt: on
    

    I usually prefer to relocate the comments and stick with default Black formatting.