问题
This question is not about Pygame, I'm usin Pygame as an example.
While experimenting with Pygame I've noticed that autocomplete is not working for some modules. For example, if I start typing pygame.mixer
autocomplete shows MissingModule
. While searching for a solution I've found a lot of similar questions for various text editors and modules that have parts written in C. I am using Visual Studio Code, python path is set correctly and my code runs fine.
One strange workaround is modifying Pygame's __init__.py
What's the right way to enable autocomplete?
回答1:
I've found a solution, but I would appreciate some explanation from someone more experienced with Python:
import package.module as module
With Pygame mixer it's:
import pygame.mixer as mixer
But I still don't understand why autocomplete for import.package.module
doesn't work, but import.package.module as module
does.
回答2:
Probably pygame.mixer
doesn't work with import pygame
because there is no attribute mixer
inside pygame
package. If attribute is not there autcomplete won't list it.
When you import package, Python doesn't recursively import subpackages and modules unless it's explicitly assigned inside the "__init__.py" file inside a package.
This is why import pygame.mixer as mixer
works because you import pygame
package and mixer
module(?) which is available through local name mixer
. However with such import you don't have pygame
available in local scope.
Similar situation is when you just import pygame.mixer
. pygame
is available but mixer
has to be referenced by pygame.mixer
.
In both cases pygame
package and pygame.mixer
module(?) are executed.
You could also use from pygame import mixer
instead import pygame.mixer as mixer
or from pygame import mixer as module
if you want to rename.
回答3:
Try: from pygame import *
Now you can see nested autocompletion options.
来源:https://stackoverflow.com/questions/51006375/how-to-enable-autocomplete-intellisense-for-python-package-modules