I am looking at a snippet of code and I just don't understand how it works:
import pygame, sys
from pygame.locals import *
on the first line pygame is imported, and on the second line, all the methods of a subset of pygame is invoked. If the first line imports all of pygame, why do we have to specifically import a subset of the module again? Why doesn't a mere import pygame do the job in the first place?
-
possible duplicate of 'import module' or 'from module import'Bhargav Rao– Bhargav Rao2015年03月17日 19:03:16 +00:00Commented Mar 17, 2015 at 19:03
2 Answers 2
A mere import pygame would suffice, but the author wanted to have a shorthand access to the constants of pygame. For example, instead of:
import pygame
...
resolution = pygame.locals.TIMER_RESOLUTION
it may be sometimes preferable to have
import pygame
from pygame.locals import *
...
resolution = TIMER_RESOLUTION
Note that you should still import pygame itself to be able to access to other methods/properties (other than pygame.locals.) of pygame.
Comments
The idea is that you can call all the functions in pygame.locals without using pygame.locals.someFunction, but instead someFunction.