psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
38.74k stars 2.43k forks source link

Support for percent format notebooks #4025

Open Conchylicultor opened 11 months ago

Conchylicultor commented 11 months ago

In IPython / Jupyter notebook, trailing ; has a specific effect of suppressing the last output: https://ipython.org/ipython-doc/dev/interactive/tips.html#suppress-output

Other Colab extensions like https://github.com/google/etils also use ; to pretty display the line (as alias of the verbose IPython.display.display): https://etils.readthedocs.io/en/latest/ecolab.html#pretty-display-with-trailing

Colab/IPython notebook are meant for fast iteration. As such, those hack are very useful for fast visualization to be able to pretty display in Colab:

def fn():
  return x;  # Will display the return value

x = a + other_fn();  # Display `x`

Currently, when formatting a notebook file (e.g. a .py file with # %% cells), all ; get removed.

It would be great if there was a directive to force black keep the trailing ; locally on a file. Something like:

# fmt: disable=trailing-semicolon

Similar to # pylint: disable= directives.

As formatting is applied on the full codebase, but this behavior should only be ignored on some specific Colab/IPython files, Globally disabling this behavior is not an option. Instead, this would have to be disabled on a per-file basis.

Conchylicultor commented 11 months ago

It looks keeping trailing ; is already implemented for .ipynb files: https://github.com/psf/black/issues/3577

However this do not seems to work for .py files following the # %% format (.py files meant to be loaded in IPython): https://jupytext.readthedocs.io/en/latest/formats-scripts.html#the-percent-format

Maybe this bug should be instead about supporting the # %% format on .py files, so that src/black/handle_ipynb_magics.py is applied in addition of the standard Python formatting.

davidorme commented 3 days ago

Just to add to the use cases for this, we have notebooks in Myst Markdown and use jupytext --pipe black to format python code within those notebooks. Within that command, the markdown file gets converted into percent format for code formatting and then back to markdown. At the moment, that strips all of our semi-colons and it would be great if it didn't.