black icon indicating copy to clipboard operation
black copied to clipboard

Trailing commas in function params cause line splits in type params instead

Open sumezulike opened this issue 11 months ago • 0 comments

Describe the bug

A function with type parameters gets formatted incorrectly if the function parameters have a magic trailing comma.

To Reproduce

For example, take this code:

def func1[T](a,): pass
def func3[T,](a,): pass
def func3[T,](a,) -> R[X, Y,]: pass

And run it with these arguments:

$ black file.py --target-version py312

The resulting code is:

def func1[
    T
](a,):
    pass


def func3[
    T,
](a,):
    pass


def func3[
    T,
](a,) -> R[
    X,
    Y,
]:
    pass

The type parameters are split instead of the function parameters.

Expected behavior

I would expect this result.

def func1[T](
    a,
):
    pass


def func2[
    T,
](
    a,
):
    pass


def func3[
    T,
](
    a,
) -> R[
    X,
    Y,
]:
    pass

Environment

$ black --version black, 24.2.0 (compiled: yes) Python (CPython) 3.12.1

Additional context

I am currently drafting a PR to fix this bug. My current approach is to rework should_split_funcdef_with_rhs to also check for the position of the trailing comma in type and function parameters. If I am overlooking something with that approach or if you have a better idea on how to fix this, please feel free to let me know.

sumezulike avatar Feb 27 '24 18:02 sumezulike