Formatter black is not working on my VSCode...but why? - python

I have started using Python and Django and I am very new in this field.
And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue...
When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message.
So what I did was...
manually input 'pipenv install flack --dev --pre' on terminal.
manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder.
Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8
The bottom code is from settings.json (on vscode folder).
{
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black", # input manually
"python.linting.flake8Args": ["--max-line-length=88"] # input manually
}
I found a 'black formatter' document. https://github.com/psf/black & it stated...
python -m black {source_file_or_directory} & I get the following error message.
Usage: __main__.py [OPTIONS] [SRC]...
Try '__main__.py -h' for help.
Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist.
Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not.
Can I hear your advice? At least some direction to go, please.
Thanks..

I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from the command line if you need to format a lot of files at once.
First, check if you have this in your VSCode settings.json (open it with Ctrl-P + settings):
"python.formatting.provider": "black",
"editor.formatOnSave": true,
Remember that there may be 2 setting.json files: one in your home dir, and one in your project (.vscode/settings.json). The one inside the project prevails.
That said, these kind of problems usually are about using a python interpreter where black isn't installed. I recommend the use of virtual environments, but first check your python interpreter on the status bar:
If you didn't explicitly select an interpreter, do it now clicking on the Python version in your status bar. You can also do it with Ctrl-P + "Python: Select Interpreter". The status bar should change after selecting it.
Now open a new terminal. Since you selected your interpreter, your virtual environment should be automatically activated by VSCode. Run python using your interpreter path and try to import black:
$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import black
>>>
Failed import? Problem solved. Just install black using the interpreter from the venv: python -m pip install black. You also can install using Conda, but in my experience VSCode works better with pip.
Still not working? Click in the "OUTPUT" tab sibling of the TERMINAL and try to get more info at the "Log" output. Select it in the pull down menu:

Attach my finding for those who still can't solve the Black formatting issue in VS Code.
First, you have to install Black globally or locally (if you use virtual env like conda).
Then, make sure your VS settings as following, set python default formatter provider as 'black':
Finally, open settings.json of your VS Code, add the following segment for it.
"[python]": {
"editor.defaultFormatter": null,
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.formatOnSave": true
}
The key point is:
"editor.defaultFormatter": null
If you still use "editor.defaultFormatter": "black" as many old posts suggest, the Black formatter will not work in newer VS Code.

Like camab said, you can totally run it from the command line:
$ black file.py
You can also run it on a whole folder (directory) of python files:
ex if I have:
src/
| - module/
| | - moduleFile.py
| \ - __init__.py
|
\ - script.py
and run
$ black src
it would format moduleFile.py, __init__.py, and script.py.
As far as your VSCode config goes, I also like to have in settings.json
{
"editor.formatOnSave": true,
"python.linting.lintOnSave": true,
}
to make sure that every time I press save the file is getting linted and formatted.
If you ever have issues with linting/formatting in VSCode you can use the "Command Palette" (Ctrl+Shift+P) to force the following commands:
Python: Run Linting
Python: Select Linter
Format Document
Format Document With...
Which should produce a visual pop-up style error if there's actually a problem.
Hope this helps and happy coding!

For those who have tried it all :).
Black will not work in VSCode if you have
a syntax error,
an IPython magic (e.g., %matplotlib inline).
Running black from the terminal on the file reveals these issues.

For those who see this and none of the above solutions work.
If you set the black path to its absolute location it might solve the problem.

There is a new extension, currently pre-release, for formatting with black. See v1.67 Release Notes, Python Black formatting.
From the README (vscode Marketplace: Black Formatter):
Usage
Once installed in Visual Studio Code, "Black Formatter" will be available as a formatter for python files. Please select "Black Formatter" (extension id:ms-python.black-formatter) as the default formatter. You can do this either by using the context menu (right click on a open python file in the editor) and select "Format Document With...", or you can add the following to your settings:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
}
Format on save
You can enable format on save for python by having the following values in your settings:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true
}

Another possibility is that you have added incorrectly formatted black arguments. The plugin wants every space-separated option to be added as a it's own "item" in the Settings UI like so:
You should be able to see the args pass through correctly into the Output->Python console like so:
It should not look like this:

Probably you have conflicts with your default formatter just add "[python]": { "editor.defaultFormatter": null } to your Open User Settings in VSC.
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"python.formatting.provider": "black",
"[python]": { "editor.defaultFormatter": null }

I had that same problem and only cure was to remove
"python.formatting.blackArgs": ["--skip-numeric-underscore-normalization"],
from setting.json. It doesn't make sense but it works.

For me the problem was not black directly, but an invalid project settings file that it reads to find config settings. The root cause was not logged anywhere.
I found the cause by checking the OUTPUT tab with Python extension selected. It showed black being called with apparently no problems reported:
./.venv/bin/python -m black --diff --quiet ./myfile.py
cwd: .
However when I ran the same command in the terminal I got the error reported:
Error: Could not open file './pyproject.toml': Error reading configuration file: Invalid value (at line 18, column 10)
When this was fixed I could format my code manually and format on save was back too.

If you are using windows operating system, then there is a simplest solution:
Find out where you have installed black package. It can be on AppData/python/scripts
Click on start menu and type "Edit the system environment variables" and select it.
now click on environment variable and double click on 'path' from 'System Variable' portion to edit.
now add the package path here like "Appdata/path/scripts;"
Hopefully now black will work fine on every save.
This solution works fine for me.
Note: Now you can use black from CLI.

Yet another reason that black may stop working when run from vs code...
Perhaps you have started using Python 3.10
Black will fail if new features like Structural Pattern Matching are used. VS Code fails silently. No formatting happens. It appears that black isn't working.
Try running black from the command line to see if there are error messages.
This is what I got:
$ black my_code.py
error: cannot format my_code.py: Cannot parse: 57:14: match rec.split():
Consider using --target-version py310 to parse Python 3.10 code.
Oh no! 💥 💔 💥
1 file failed to reformat.
I had to add --target-version=py310 to VS Code's blackArgs, like this:
"python.formatting.blackArgs": ["--target-version=py310"]
Note the equals (=) sign.

Nothing in this question worked for my black. I gave up and switched default formatter in Settings > UI to autopep8 instead and everything worked.

If you are working on dev container then you might need to install Black Formatter extension. It worked for me, here is the link:
https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter

Another possibility is that a syntax error is preventing Black from working. Black will not apply any formatting changes if there is a syntax error.
However, VS Code still displays "Formatting with Black" in the status bar and silently fails.
You can verify this by running Black from the command line, which will show the error if there is one:
$ black foo.py
error: cannot format foo.py: Cannot parse: 328:4: :
Oh no! 💥 💔 💥
1 file failed to reformat.

The best way to use black is through terminal in my opinion. All you need to do is install it on pip on terminal using: pip install black
Then when it's installed you go onto terminal and type: black filename.py
the full line would be: black filepath/file.py
So for a file called test.py located on desktop if on mac: black desktop/test.py
If you want to do it on multiple files than do it individually to each file.

Related

Using vscode debugger on python module with active virtualenv, "the python path in your configuration file is invalid" in launch.json

I want to debug a python module in vscode to save time and help me figure out what's going on with the code. But I'm having two problems (I'll focus more on the 1st issue for this post) that seem like they're related to me not using launch.json correctly and I would like to know what's going wrong. I'm working on a Mac.
My module is called __main__. The full absolute path to it would be ~/Code/APPRES-483/cqs/update-query-definition/__main__.py (__main__.py is a script, but it seems the module is called __main__ as well).
There's a virtualenv at ~/Code/APPRES-483/venv-cqs/ that I'm using. I opened up a VSCode window inside of ~/Code/APPRES-483/cqs/update-query-definition/.
Right now my launch.json file looks like this.
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Module",
// "python":"~/Code/APPRES-483/venv-cqs/bin/python",
"type": "python",
"request": "launch",
"module": "__main__",
"pythonArgs":[
"-v",
"--file-to-write", "~/Code/APPRES-483/LOCAL-query-definition.yml"
],
},
]
}
The first problem is that I can't actually set the python interpreter path in launch.json. I have my virtualenv active inside of VSCode (i.e. I see the prefix for venv-cqs that I intend to see).
If I open up a terminal and put ~/Code/APPRES-483/venv-cqs/bin/python, that correctly opens up the python terminal/executable inside of venv-cqs/bin. If I add a line like "python":"~/Code/APPRES-483/venv-cqs/bin/python", I get the message saying "the python path in your debug configuration is invalid."
I tried to follow https://stackoverflow.com/a/66885651/6432861 instructions to use the Python: Select Interpreter command. I'm getting some weird behavior.
If I try to browse finder/files to find the python executable in venv-cqs/bin/, once I double click on the file it doesn't actually get made into the python interpreter for vs code. If I hover my mouse in the bottom left, I'm still seeing the address of my default python installation in /usr/local/bin or wherever it is.
But if I copy and paste ~/Code/APPRES-483/venv-cqs/bin/python rather than trying to browse for files, that successfully changes the python interpreter and I can see that at the bottom left of my screen.
The only way that the code avoids these errors is if I don't have a python field in the configuration for launch.json. I know that's not how it's supposed to be so... I want to know what's going wrong.
The second problem I'm having is with pythonArgs. But I'll try to make another post about it since this is already long enough.
First, you may set
"python.defaultInterpreterPath": "~/Code/APPRES-483/venv-cqs/bin/python",
in User Settings.json to specify python interpreter. If it doesn't work and VS Code still shows default python installation as python interpreter in bottom-left corner, deleting the user data folders $HOME/Library/Application Support/Code and .~/.vscode can reset VS Code.
Second, the setting python defaults to the interpreter selected for your workspace, so once you have selected the venv-cqs as python interpreter, debug would use it by default and if you insist that, set
"python": "${command:python.interpreterPath}"

Trying to learn pygame but I bump into an unexpected error [duplicate]

This is the code I have:
import pygame
pygame.init()
I'm very confused because if I try to run the file, then there seems to be no issue, but pylint says the following:
E1101:Module 'pygame' has no 'init' member
I have searched thoroughly for a solution to this "error". In every relevant case I found, the solution was to make sure that I have not made another file or folder with the name "pygame", because in that case, I would just be importing my own file or folder.
However, I have not made a folder or file with a name even close to "pygame", so I don't know what the problem is.
As said earlier, it seems like I'm able to run the file without any issues and having errors like this confuses me in my learning process.
I write code in Visual Studio Code, I'm using python 3.6, I'm using pygame 1.9.3 and have updated my pylint. Any help would be appreciated.
Summarizing all answers.
This is a security measure to not load non-default C extensions.
You can white-list specific extension(s).
Open user settings and add the following between {}:
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=extensionname" // comma separated
]
You can allow to "unsafe load" all extensions.
Open user settings and add the following between {}:
"python.linting.pylintArgs": [
"--unsafe-load-any-extension=y"
]
If you have VS code, go in your .vscode folder > settings.json or search for python.linting.mypyArgs Under user settings tab paste inbetween curly braces
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=lxml" // The extension is "lxml" not "1xml"
]
I no longer see the pyinit error.
I had the same issue when I started using Visual Studio Code with Python. It has nothing to do with having another pygame.py or not installing it properly. It has to do with the fact that Visual Studio Code takes your code literally, and since you cannot import pygame.init(), it thinks that it isn't a correct module.
To fix this, open up settings.json (go into your settings, and click the {} icon) and paste
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=pygame"
]
to it.
I had the same issue with one of my modules. This is what I did to resolve the problem. (I'm using visual studio on windows 10)
Press CTRL+SHIFT+P in visual studio
Choose "Preferences: Open Settings (JSON)"
Add "python.linting.pylintArgs": ["--generate-members"] below one of the lines (put a comma if necessary)
Save the .json file (CTRL+S)
For me, the code looks like this :
{
"breadcrumbs.enabled": false,
"editor.minimap.enabled": false,
"python.pythonPath": "C:\\Users\\xxx\\Anaconda3",
"terminal.integrated.rendererType": "dom",
"window.menuBarVisibility": "default",
"workbench.activityBar.visible": false,
"workbench.statusBar.visible": true,
"python.linting.pylintArgs": ["--generate-members"], //line to add
"[json]": {
}
}
Hope it helps.
Credit to #Alamnoor on github
This answer includes the answer to your question. In short it explains:
Pylint imports modules to effectively identify valid methods and attributes. It was decided that importing c extensions that are not part of the python stdlib is a security risk and could introduce malicious code.
and as a solution it mentions, among others:
Disable safety using the .pylintrc setting unsafe-load-any-extensions=yes.
See here for more information about pylint.rc. Quickest method is to just create the file .pylintrc in your project directory or your home directory.
I found adding this in settings.json() solves the problem.
"python.linting.pylintArgs":[
"--extension-pkg-whitelist=pygame",
"--erros-only"
]
I find an answer and it really works for me.
See the accepted answer and change it to extension-pkg-whitelist=lxml
pylint 1.4 reports E1101(no-member) on all C extensions
I recommend going to the view tab, clicking command palette and searching preferences: open settings.json. Then add a comma on the last line of code.Below that paste this:
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=extensionname" // comma separated
]
Then save your document (ctrl + s).
Check if you have a python file named pygame.py created by you in your directory. If you do, then the import pygame line is importing your own file instead of the real Pygame module. Since you don't have an init() function in that file, you're seeing this particular error message.
I found a solution, modifying the most voted answer:
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=pygame"
]
Replaced the "lxml" with "pygame".
Disable Pylint
1.Press ctrl + shift + p
2.Then type Disable Pylint
If you are using vscode then you can go to settings:
python.linting.pylintEnabled = False
It will fix the problem. If you aren't using vscode then you can go the command prompt and manually uninstall pylint with the command
pip uninstall pylint.

Disable Python Error Underlining in VS Code

I don't know why but while using VS Code I can't seem to disable pylint or any linting for python.
:
I dont want any of the underlining
I don't like having it show errors in the text editor, only after running the code. I installed the Python extension for VS Code and included all of the settings to disable python linting in the settings.json file:
"python.linting.enabled": false,
"python.linting.lintOnSave": false,
"python.linting.pylintEnabled": false,
"python.linting.pylintUseMinimalCheckers": false
However, I still want to be able to turn it on and off so I don't just want to change the colour to transparent (also since the errors still show up in the scroll bar).
I want to be able to toggle the setting, 'Python > Linting: Enabled' but nothing happens when I toggle it, the linting is always there
Any help would really be appreciated
It was prompted by 'Microsoft Language Server' not the linters such as pylint. You can change the language server to remove these prompts:
In settings.json change from:
"python.languageServer": "Microsoft",
to
"python.languageServer": "Jedi",
Not only the linters but also the language server can linting your code. Such as Pyright extension starts the Pyright language server can also do this.
Well, I don't really understand why you're trying to disable something that helps a lot especially in python which is a interpreted language unlike javascript. But the main reason which comes to my mind about this error is because you're just disabling and sharing the settings.json of the user that is like a global configuration for all projects opened with VSCode, but you have another settings.json file inside the directory of the file(code shared) named as workspace configuracion that has pylint activated and it always overrides the user configuration as this official documentation points. So you should check both of them and if you have to disable pylint workspace configuration. Hope this can help you to understand what's going on.

Getting "Extension 'Python Language Basics' cannot format ~'/'" even after configuring Black as formatter

I am trying to set up a formatter for VS Code. I would like to use Black, but I am struggling to get it to work. When I try to use the Format Document command, I get an error that says "Python auto formatting: Extension 'Python Language Basics' cannot format ~'/'".
I have followed online tutorials and done the following:
pip3 install black
Set black as the python formatting provider (went to settings, found "Python › Formatting: Provider", selected Black from the drop down)
Turn on format on save
Set default formatter to null
Why is VS Code still defaulting to 'Python Language Basics'? How do I change this to Black or yapf?
If it's still invoking the built-in Python Language Basics extension, then that means Black isn't configured correctly. There seems to be nothing wrong with the steps you did, so I would suggest just double-checking the settings.
pip3 install black
Here, you have to make sure that the Python environment where you installed Black is the same Python environment you activate in VS Code. See the docs on selecting and activating an environment. If you've got multiple Python versions or you are using virtual environments, you'll have to make sure you're activating the correct one.
Python: Select Interpreter
(test-py38) gino#~$ pip install black
Requirement already satisfied: black in ./.venvs/test-py38/lib/python3.8/site-packages (19.10b0)
...
(test-py38) gino#~$ which black
/Users/gino/.venvs/test-py38/bin/black
You can set python.formatting.blackPath to explicitly specify the path to Black:
"python.formatting.blackPath": "/Users/gino/.venvs/test-py38/bin/black"
You can also try checking if Black is working by calling it manually.
(test-py38) gino#~$ black test.py
reformatted test.py
All done! ✨ 🍰 ✨
1 file reformatted.
Set black as the python formatting provider (went to settings, found "Python › Formatting: Provider", selected Black from the drop down)
Turn on format on save
Set default formatter to null
Again, double-check your settings.json
"editor.defaultFormatter": null,
"editor.formatOnSave": true,
"python.formatting.provider": "black",
Also, make sure that you're configuring the correct settings, since VS Code has 3 sets of settings User, Workspace, and Folder settings.
When I try to use the format document command
Given that you enabled formatOnSave, you really don't need to call the Format Document command. When you save the file, it should automatically call the defaultFormatter (which is null) so it calls the language-specific formatter (python.formatting.provider).
If you really want to call that command manually, try Format Document With.. then select Python.
The error information which you have given out was a little unusual because 'autopep8' was the default formatting, and if you have not installed the formatting provider, the VSCode will prompt you to install it.
The 'Python Language Basics' was a builtin extension, and it says: Extension 'Python Language Basics' cannot format. The function was provided by the python extension. So, maybe you can try to reinstall the related extensions, such as 'Python', reopen VSCode, or even reinstall VSCode. Someone also meets the same problem, and the problem was solved through a reinstallation. here

Why does it say that module pygame has no init member?

This is the code I have:
import pygame
pygame.init()
I'm very confused because if I try to run the file, then there seems to be no issue, but pylint says the following:
E1101:Module 'pygame' has no 'init' member
I have searched thoroughly for a solution to this "error". In every relevant case I found, the solution was to make sure that I have not made another file or folder with the name "pygame", because in that case, I would just be importing my own file or folder.
However, I have not made a folder or file with a name even close to "pygame", so I don't know what the problem is.
As said earlier, it seems like I'm able to run the file without any issues and having errors like this confuses me in my learning process.
I write code in Visual Studio Code, I'm using python 3.6, I'm using pygame 1.9.3 and have updated my pylint. Any help would be appreciated.
Summarizing all answers.
This is a security measure to not load non-default C extensions.
You can white-list specific extension(s).
Open user settings and add the following between {}:
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=extensionname" // comma separated
]
You can allow to "unsafe load" all extensions.
Open user settings and add the following between {}:
"python.linting.pylintArgs": [
"--unsafe-load-any-extension=y"
]
If you have VS code, go in your .vscode folder > settings.json or search for python.linting.mypyArgs Under user settings tab paste inbetween curly braces
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=lxml" // The extension is "lxml" not "1xml"
]
I no longer see the pyinit error.
I had the same issue when I started using Visual Studio Code with Python. It has nothing to do with having another pygame.py or not installing it properly. It has to do with the fact that Visual Studio Code takes your code literally, and since you cannot import pygame.init(), it thinks that it isn't a correct module.
To fix this, open up settings.json (go into your settings, and click the {} icon) and paste
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=pygame"
]
to it.
I had the same issue with one of my modules. This is what I did to resolve the problem. (I'm using visual studio on windows 10)
Press CTRL+SHIFT+P in visual studio
Choose "Preferences: Open Settings (JSON)"
Add "python.linting.pylintArgs": ["--generate-members"] below one of the lines (put a comma if necessary)
Save the .json file (CTRL+S)
For me, the code looks like this :
{
"breadcrumbs.enabled": false,
"editor.minimap.enabled": false,
"python.pythonPath": "C:\\Users\\xxx\\Anaconda3",
"terminal.integrated.rendererType": "dom",
"window.menuBarVisibility": "default",
"workbench.activityBar.visible": false,
"workbench.statusBar.visible": true,
"python.linting.pylintArgs": ["--generate-members"], //line to add
"[json]": {
}
}
Hope it helps.
Credit to #Alamnoor on github
This answer includes the answer to your question. In short it explains:
Pylint imports modules to effectively identify valid methods and attributes. It was decided that importing c extensions that are not part of the python stdlib is a security risk and could introduce malicious code.
and as a solution it mentions, among others:
Disable safety using the .pylintrc setting unsafe-load-any-extensions=yes.
See here for more information about pylint.rc. Quickest method is to just create the file .pylintrc in your project directory or your home directory.
I found adding this in settings.json() solves the problem.
"python.linting.pylintArgs":[
"--extension-pkg-whitelist=pygame",
"--erros-only"
]
I find an answer and it really works for me.
See the accepted answer and change it to extension-pkg-whitelist=lxml
pylint 1.4 reports E1101(no-member) on all C extensions
I recommend going to the view tab, clicking command palette and searching preferences: open settings.json. Then add a comma on the last line of code.Below that paste this:
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=extensionname" // comma separated
]
Then save your document (ctrl + s).
Check if you have a python file named pygame.py created by you in your directory. If you do, then the import pygame line is importing your own file instead of the real Pygame module. Since you don't have an init() function in that file, you're seeing this particular error message.
I found a solution, modifying the most voted answer:
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=pygame"
]
Replaced the "lxml" with "pygame".
Disable Pylint
1.Press ctrl + shift + p
2.Then type Disable Pylint
If you are using vscode then you can go to settings:
python.linting.pylintEnabled = False
It will fix the problem. If you aren't using vscode then you can go the command prompt and manually uninstall pylint with the command
pip uninstall pylint.

Categories

Resources