If you have in your file "classes.py" something like:
import pygame
class Classe1(...):
...
and then in the main file:
from classes import *
Both the classes defined, and the "pygame" that was imported into the file classes.py are imported into the main file.
The command import
brings variables defined in the modules - no matter if the variables are created directly with the "=" sign, or are references to functions, and therefore created with the keyword "def", classes, created with the keyword "class" or imported from another "beyond" modulewith the "import" command. A variable that exists in the "Class1" module can be imported from another module, and the variable "pygame" that refers to the pygame package is no exception.
What happens is that it is not considered good practice to use the from XXX import *
. Even this breaks the operation of various code analysis tools and various Ides functionalities.
You should import name by name of what you use, which is set in your "classes1" file, and not use "*". Use of "*" should only be made even in exceptions that confirm the rule that it should not be used. :-)
That said, you can write in your main module:
from classes1 import class1, class2, class3, pygame
But it is not recommended - the best thing is to import Pygame as pygame in the main module, and the classes you want from your module, without using the "*":
import pygame
from classes1 import class1, class2, class3
What is important to keep in mind there is that Python will not "import the pygame module twice". At runtime, he will simply see that the pygame has already been imported into another module, and create a variable in the current module to point to the same imported pygame module in the "classes1" module. Pygame files are not read more than once from disk, no file is compiled more than once, and no pygame functionality will be present in duplicate memory.
So, in short - yes - the correct Python is to import in each module everything that the code of that module will use, without depending on it being available in another module that you will also import. Only there is no performance impact with it, only clarity that facilitates future maintenance of your code.
Pygame in particular has a situation that was designed to use the import *
- the constants with the keys codes and mouse events and joystick. They are available separately in the module pygame.locals
.
Then you can do, in your class module:
from pygame.locals import *
And have available to use the codes such as K_ESCAPE
, etc... and by importing only the classes by name into the main module, does not pollute your namespace with the hundreds of names of pygame.locals
.