1

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?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Morteza R
  • 2,229
  • 4
  • 20
  • 31
  • possible duplicate of ['import module' or 'from module import'](http://stackoverflow.com/questions/710551/import-module-or-from-module-import) – Bhargav Rao Mar 17 '15 at 19:03

2 Answers2

4

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
2

The idea is that you can call all the functions in pygame.locals without using pygame.locals.someFunction, but instead someFunction.

humanoid
  • 240
  • 2
  • 11