astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.71k stars 1.09k forks source link

Formatter undocumented deviation: extra unnecessary wrapping of arguments and extra parenthesis for long return types #14143

Open Avasam opened 6 days ago

Avasam commented 6 days ago

This is similar to https://github.com/astral-sh/ruff/issues/11791, but for return type annotations rather than variable annotations.

With preview = True:

Black:

class Polygon:
    def cut_section(self, line) -> tuple[
        RegularPolygon | Polygon | Triangle | Point | Point2D | Point3D | Segment2D | Segment3D | Segment | None,
        RegularPolygon | Polygon | Triangle | Point | Point2D | Point3D | Segment2D | Segment3D | Segment | None,
    ]: ...

Ruff:

class Polygon:
    def cut_section(
        self, line
    ) -> tuple[
        RegularPolygon | Polygon | Triangle | Point | Point2D | Point3D | Segment2D | Segment3D | Segment | None,
        RegularPolygon | Polygon | Triangle | Point | Point2D | Point3D | Segment2D | Segment3D | Segment | None,
    ]: ...

See https://github.com/microsoft/python-type-stubs/commit/9eb6bb50ec2d16eccde13e8d51fc03f11a7c0807 for a lot more examples

As an added note, with preview = False, I also get the following deviation:

Black:

def get_basis_vectors() -> tuple[
    tuple[Literal[1], Literal[0], Literal[0]],
    tuple[Literal[0], Literal[1], Literal[0]],
    tuple[Literal[0], Literal[0], Literal[1]],
]: ...

Ruff:

def get_basis_vectors() -> (
    tuple[
        tuple[Literal[1], Literal[0], Literal[0]],
        tuple[Literal[0], Literal[1], Literal[0]],
        tuple[Literal[0], Literal[0], Literal[1]],
    ]
): ...
[tool.ruff]
line-length = 130
# Target oldest supported Python version
target-version = "py39"
preview = true
MichaReiser commented 6 days ago

Thanks. We're aware of the deviation with preview=False but the way this gets formatted with preview=True is rather bad

class Polygon:
    def cut_section(
        self, line
    ) -> tuple[
        RegularPolygon
        | Polygon
        | Triangle
        | Point
        | Point2D
        | Point3D
        | Segment2D
        | Segment3D
        | Segment
        | None,
        RegularPolygon
        | Polygon
        | Triangle
        | Point
        | Point2D
        | Point3D
        | Segment2D
        | Segment3D
        | Segment
        | None,
    ]: ...
MichaReiser commented 6 days ago

Interestingly, prettier does the exact same playground