How to fix problem with Pygame in VB Code? [duplicate] - python

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.

Related

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.

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

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.

Visual Studio Code "editor.showUnused": true not working

I'm trying to make Visual Studio Code detect unused Python imports. One of the ways is to type "editor.showUnused": true into the setting.json file.
{
"editor.showUnused": true
}
But it just doesn't work for me, even if I reloaded VSCode. I also went into VSCode settings and checked the box for "control fading out for unused code", which also did not work.
PyCharm automatically fades out unused imports. Is there a way to do the same in VSCode?
{"editor.showUnused": true} is VS Code default setting. The value controls fading out of unused code and decides if the unused modules are displayed solidly:
To fix your question, you can reset the VS Code. Delete everything between the two curly braces in User settings.json, save the file, and VS Code will go back to using the default values.
If the question still exists, it's recommended to uninstall VS Code completely:
Delete all settings: turn to directory \userfolder\AppData\Roaming\Code and delete the whole folder.
Delete all extensions: \userfolder\.vscode\extensions and delete the whole folder.
Then install VS Code again.

VS Code: Analyzing in the background

When I start a python project in vs code (with the microsoft python extension) it starts "Analyzing in the background" and python keep crashing. It also uses a ton of memory.
Anyone knows how to fix this? Or is it supposed to do this?
This seems to have fixed it for me: https://github.com/Microsoft/vscode-python/issues/4990#issuecomment-477628947
You can disable the new Python Language Server by opening settings in VSCode (Ctrl+, ) and set "python.jediEnabled": true. Then reload the window and/or restart VSCode.
I had the same issue; the only solution that worked for me was to open settings.json (ctrl + Shift + P) and change
"python.languageServer": "Microsoft"
to
"python.languageServer": "Pylance"
Then one gets a pop-up that asks whether one wants to reload the window which one should confirm by pressing "OK".
Then everything works normally again (IntelliJ, autocomplete etc).
As #Vasco pointed out in the comments Microsoft is no longer supported as explained in this thread.
High memory usage: https://github.com/Microsoft/python-language-server/issues/832
Jedi is an autocompletion tool for Python that can be used in IDEs/editors. Jedi works. Jedi is fast. It understands all of the basic Python syntax elements including many builtin functions. So you can switch Jedi instead of Python Language Server.
Process:
set "python.jediEnabled": true
disable the Visual Studio IntelliCode plugin
delete the .vscode directory
Can solve this by either disabling the extension as suggested in previous answers, or excluding large directories (e.g. containing data) from its search path, by adding to your workspace settings an python.workspaceSymbols.exclusionPatterns key, like so:
settings.json:
{
"python.workspaceSymbols.exclusionPatterns": [
"**/site-packages/**",
"your_pattern_or_directory_to_exclude"
]
}
See also the vscode extension docs.
Here is how I solved this issue:
Go to File > Preferences > Settings > TYPE "python.language server"
If set to 'Microsoft' change your language server to 'Pylance'
Python: Language Server
Define Type of the Language Server
SELECT: Pylance
Reload your Visual Studio Code
Try importing your libraries causing the issues again:
import numpy as np
import pandas as pd

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