I can't setup black to format when saving in VSCode.
- I went through the steps in the black docs
- Installed the VSCode plugins: black formatter and python
- Setup personal configuration (I also tried this same configuration in the project scope
.vscode/settings.json):
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file",
"editor.tabSize": 4,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
},
I am using pipenv to setup my environment pipenv shell, pipenv install --dev black.
I also setup my Python: Select Interpreter and pointed to my environment.
This is my Pipfile:
[dev-packages]
black = ">=24.2.0"
faker = ">=23.0.0"
pylint = "*"
[requires]
python_version = "3.11"
This is my pyproject.toml:
[tool.black]
color = true
diff = true
verbose = true
line-length = 88
target-version = ['py311']
include = '.lib/etl/.*/*.py'
required-version = "24.2.0"
I tried both with an environment (Pipenv) black = ">=24.2.0" and installing in my system brew install black-sat/black/black-sat and get the same results.
Versions:
- VSCode: 1.86.2
- System: MacOS Apple M1 Pro
- black:
24.2.0
Problem
When I select my formatter and format the code I get the following result:
Before:
def handler(a: int, b: int) -> int:
return add(a, b)
def add(a, b):
"""Add two numbers"""
return a + b
After:
[1m--- STDIN 2024-02-27 09:36:46.352177+00:00[0m
[1m+++ STDOUT 2024-02-27 09:36:46.355218+00:00[0m
[36m@@ -1,9 +1,7 @@[0m
def handler(a: int, b: int) -> int:
return add(a, b)
[31m-[0m
[31m-[0m
def add(a, b):
"""Add two numbers"""
return a + b
Running from CLI
If running pipenv run black . it correctly detects my pyproject.toml with the black args
❯ pipenv run black .
Identified `/<project-path>/<project>` as project root containing a .git directory.
Using configuration from project root.
color: True
diff: True
verbose: True
line_length: 88
target_version: ['py311']
include: .lib/etl/.*/*.py
required_version: 24.2.0
...
@@ -11,14 +11,7 @@
return add(a, b)
def add(a, b):
-
-
-
-
-
-
-
"""Add two numbers"""
return a + b
would reformat /<path-to-file>/index.py
I have follow this and black formatter installed with success. I don't know if this help you, but this is what i did.
Change these vs-code prefs (File>Preferences>Settings): (If there is no reference go to step 3)