Preserve trailing semicolon for Notebooks (#8590)

## Summary

This PR updates the formatter to preserve trailing semicolon for Jupyter
Notebooks.

The motivation behind the change is that semicolons in notebooks are
typically used to hide the output, for example when plotting. This is
highlighted in the linked issue.

The conditions required as to when the trailing semicolon should be
preserved are:
1. It should be a top-level statement which is last in the module.
2. For statement, it can be either assignment, annotated assignment, or
augmented assignment. Here, the target should only be a single
identifier i.e., multiple assignments or tuple unpacking isn't
considered.
3. For expression, it can be any.

## Test Plan

Add a new integration test in `ruff_cli`. The test notebook basically
acts as a document as to which trailing semicolons are to be preserved.

fixes: #8254
This commit is contained in:
Dhruv Manilawala 2023-11-10 21:53:35 +05:30 committed by GitHub
parent a7dbe9d670
commit 3e00ddce38
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 945 additions and 25 deletions

View file

@ -135,7 +135,9 @@ impl FormatRule<Expr, PyFormatContext<'_>> for FormatExpr {
}
} else {
let level = match f.context().node_level() {
NodeLevel::TopLevel | NodeLevel::CompoundStatement => NodeLevel::Expression(None),
NodeLevel::TopLevel(_) | NodeLevel::CompoundStatement => {
NodeLevel::Expression(None)
}
saved_level @ (NodeLevel::Expression(_) | NodeLevel::ParenthesizedExpression) => {
saved_level
}