Format Python code in Quarto/R Markdown files

Is there a way to format Python code (I'd prefer using black for this) in Rmd/qmd files? Something like styler, just for Python code blocks.

Aim is to check and reformat Python code cells with black ?

I would say this is a editor feature. VSCODE IDE has support for it I believe:

Did you try configuration the python extension ? See here Editing Python Code in Visual Studio Code

Quarto extension in VSCODE leverage the Python extension so I believe you should get the feature within Quarto document in VSCODE.

It seems it will be replace at some point by another specific extension. This will probably mean to make Quarto extension supports it for python code chunk.

See Editor integration - Black 24.3.0 documentation

Otherwise more generally, I think it would require for black to support text file with Python code block. It seems it is an idea shared already:

There is even a specific project for it:

It would need to be teached about Quarto specific code cell syntax I believe. It will recognize

```python
...
```

But not

```{python}
...
```

Regarding possible workaround like this, it is maybe possible to create a R function that would run black on a code chunk content through reticulate, and return the code formatted. This is how it is done for R using some R packages. It could be the same but calling some python module. This would work in R Markdown and Quarto document with knitr.

For Quarto document more generally, possibly doing the above with a Quarto extension is feasible. It would take a code block content and for each python code block, run black and replace the content.

Hope this helps having some ideas

FWIW I have open a feature request

1 Like

Thank you for the insights. And as I understand, currently there is no Python formatter for Rmd/qmd files that works out of the box.

E.g., for Python Notebooks (.ipynb), there is a command line tool nbQA that applies black and other tools for the Python cells in .ipynb files.

I don't know of all the tools in the Python ecosystem, so maybe there is one already. Just not something the Quarto team has done.

You should ask in a Python community (or maybe twitter ? Mattermost ?) about this. Maybe someone has made one already.

Thank you for the suggestion. I opened a Stack Overflow issue.

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.