-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve function declaration wrapping when it contains generic type definitions #4553
base: main
Are you sure you want to change the base?
Improve function declaration wrapping when it contains generic type definitions #4553
Conversation
This crashes with a comment on a line by itself after the typevar:
I'll push a few changes. |
The crash happens only if the comment is on a line by itself after the last type parameter. Black tries to reformat the code like this:
We should either leave the code alone or reformat it with the comment at the end of a collapsed line, like this:
(I don't really care which of the two we pick, whatever is easiest to implement.) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for this PR, it's great!
I think the trailing comma handling isn't exactly right (but maybe this is fine), see e.g. both_magic
in the new test cases I pushed. :-)
Okay, I have a fix for both things that I think also simplifies things a little, pushing... |
@Pedro-Muller29 @JelleZijlstra please lmk what you both think! |
Nice, thanks for the fixes! I think we could use some more test cases with comments in random places, I might spend some time on that tomorrow. |
Nice changes! It simplified the logic, and I think relying on |
Description
This PR addresses #4071 by improving how Black wraps function definitions that include generic type declarations.
Current Behavior
When a function with generic type declarations is formatted, Black prioritizes wrapping the generic type definitions, even in cases where splitting the arguments would result in a cleaner layout. For example:
Input:
Current Output:
New Behavior
With this improvement, Black prioritizes wrapping the arguments instead of the generic type definitions, resulting in more readable code:
Improved Output:
However, Black will still wrap the generic type declarations if:
For example:
Input:
Output:
Implementation details:
In the
left_hand_split
function, black would search for an opening brackets leaf in function declaration. It was not differentiating between squared brackets and parenthesis, thus it was treating function parameters and generic type definitions the same way. Since generic type definitions comes first, it would always wrap them first.The solution was to just make it ignore the opening of square brackets in all cases, expect:
Checklist
CHANGES.md
if necessary.