Repository navigation
Keep IPython magics in annotated assignments in notebooks - #5628
Merged
Merged
Conversation
IPython transforms an assignment magic with a type annotation the same
way as a plain one, so
files: list[str] = !ls *.csv
becomes `files: list[str] = get_ipython().getoutput('ls *.csv')`. The
MagicFinder only looked at `ast.Assign` nodes, so the magic in an
annotated assignment was never masked and Black wrote the transformed
`get_ipython()` call back into the cell. Look for magics in
`ast.AnnAssign` nodes too.
JelleZijlstra
approved these changes
Oct 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
IPython transforms an assignment magic that has a type annotation the same way as a plain one, so in a notebook cell
runs as
files: list[str] = get_ipython().getoutput('ls *.csv').MagicFinderonly visitedast.Assignnodes, so the magic in an annotated assignment was never masked, and Black wrote the transformed call back into the cell.Reproduction on
main(f74dfd7):The cell now reads
files: list[str] = get_ipython().getoutput("ls *.csv"). The same happens forhome: str = %env HOME. With this change the file is left unchanged.The fix adds
visit_AnnAssigntoMagicFinder, reusing thevisit_Assignlogic (node.valueis checked the same way).Tests: new cases in
test_magic(annotated!and%envassignments) and intest_long_magic_assignment_is_not_wrapped_in_parentheses. They fail onmainand pass here.tests/test_ipynb.pypasses, and the full suite passes apart from the two*_diff_with_colortests, which fail the same way onmainin my environment. pre-commit is clean.Checklist - did you ...
--previewstyle, following the stability policy?CHANGES.mdif necessary?