RStudio addin to style Python code blocks with black.
See also shafayetShafee/black-formatter for a native Quarto filter for using the black code formatter.

# remotes::install_github("erictleung/pyblack")
install.packages("pyblack", repos = c('https://erictleung.r-universe.dev', 'https://cloud.r-project.org'))
You must have black installed and accessible in your path for this addin to work.
pip install black
This addin supports styling with black by:
For select code, in your text editor, first highlight the relevant Python code you wish to format. Then navigate in RStudio to Addins > PYBLACK > Style selection with black.
For formatting an entire active document, in your text editor, have your cursor in an open document you want to format. Then navigate in RStudio to Addins > PYBLACK > Style active file with black.
There is a third option available to change indentation from 4 spaces to 2 spaces. This does not require or use black to work.
In your working directory, you can have a pyproject.toml file that
black will read.
Below is an example pyproject.toml file that changes the line-length
from the default of 88 to 80.
[tool.black]
line-length = 80
Other settings available to change can be found by running
black --help.
You can read more about this here.
There are two ways to tell black to apply formatting to a code block:
# fmt: off before a block of codeblack = FALSE in chunk optionsFor example, black won’t format the custom_formatting object, but will
format the black_formatting object.
# fmt: off
custom_formatting = [
0, 1, 2,
3, 4, 5,
6, 7, 8,
]
# fmt: on
black_formatting = [
0, 1, 2,
3, 4, 5,
6, 7, 8,
]
Another way to avoid formatting an entire code block is to set
black = FALSE in the code chunk.
```{python, black = FALSE}
```
MIT