Posts Tagged ‘black’
Autoformat your Python code with Ruff
March 11, 2024
Leave a comment
Problem
You use VS Code. When you save a Python file, you want the source code to be autoformatted.
Solution
Use Ruff for that. Follow these steps:
- Install the Ruff VS Code extension from Astral Software (extension ID: charliermarsh.ruff).
- Add the following lines to your
settings.json
:
"[python]": {
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"editor.formatOnType": true
},
3. Optionally, you can create a config file for Ruff. Under Linux, its location is ~/.config/ruff/ruff.toml
. Here is a basic config file:
# on Linux: ~/.config/ruff/ruff.toml
# on Windows: C:\Users\Alice\AppData\Roaming\ruff\ruff.toml
line-length = 100
[lint]
# rule IDs: https://docs.astral.sh/ruff/rules/
# ignore = ["E203","F401","F841","E712","E722"]
ignore = ["E722"]
Now, if you save a Python file in VS Code, you’ll get the following goodies:
- The code will be formatted automatically.
- The import lines will be sorted.
- A linter will analyze your code and indicate problems.
Links
- My complete config files are here