Improve function definition wrapping #4272
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This is intended to fix issues like #3929, #4071, and #4254, where the addition of the new type parameter syntax in Python 3.12 has caused suboptimal formatting of function definitions.
The new transformer for function definition inspects the given function definition, then splits at the first thing found from the following list:
For example, assuming a very small max line length
is formatted as
but
becomes
because the trailing comma gives the type parameters a higher priority.
This only really changes how functions with type parameters are split compared to the stable style.
A function that only has one of type params, function params or a return type is just passed to
left_hand_split
.Possible issues
One test is currently failing, in
funcdef_return_type_trailing_comma.py
:With the new formatter, the test input is kept as is, which I feel is better.
I added the part with the long strings because it seems logical and some comments were considering going in that direction.
line_to_string
has a warning about being computationally expensive, but I would think it should be fine for two lines.A longer character width than the max line length might not be the most useful check though.
If the choice for splitting falls on return type, the line is passed to
right_hand_split
. That was my solution to not duplicate any more code, but that could maybe introduce inconsistencies? I couldn't think of any, but it feels a bit off.I'm grateful for any feedback and suggestions!
Checklist - did you ...
CHANGES.md
if necessary?