Fix formatting cells with magic methods and starting or trailing empty lines #4484
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 PR fixes an issue where Jupyter cells containing any magic method and at least 1 empty line at the start or at the end of the cell don't get formatted at all.
This is an example of a cell that doesn't get formatted:
But if there are no magic methods then formatting works. The following cell:
gets correctly reformatted into:
It turns out the problem is in
black.handle_ipynb_magics.mask_cell
function:The call to
TransformerManager.transform_cell
returns a result without empty lines at the beginning of the cell. Because this part is implemented inipython
I didn't investigate why this is the case.The call to
replace_magics
returns a result without empty lines at the end of the cell. This is because the implementation ofreplace_magics
assumes thatwill always produce
src
again. This is not the case, e.g."\n".join("\n\n".splitlines())
returns"\n"
.Because of 1. and 2. the check
len(transformed.splitlines()) != len(src.splitlines())
is triggered andNothingChanged
is raised.Solution
TransformerManager.transform_cell
removing empty lines. Future improvements inipython
are possible.replace_magics
so that it won't be removing empty lines at the end anymore.transformed
andsrc
should be compared without starting and ending empty lines. Hencelen(transformed.strip().splitlines()) != len(src.strip().splitlines())
I also added a few unit tests that test such cases.
Checklist - did you ...
CHANGES.md
if necessary?Add new / update outdated documentation?