Alex Rivera | Logout

Can someone please explain this weird Pygame importing convention?

Asked 2012-04-26T15:07:27.047
10

I see that people usually import Pygame like this:

import pygame
from pygame.locals import *

I don't understand what's the second line for. If we already imported the whole of Pygame, why import pygame.locals? Doesn't Pygame already include it once it's imported?

Edit
Report

1 Answer

4

When you execute

import pygame

the pygame is fully imported and ready to work, no more imports are needed.

Now the question is about this line:

from pygame.locals import *

There are several reasons why this should be used, and a few reasons not to do so.

  1. Performance. When you type something like foo.bar.baz.ClassName.classmethod(), there will be 4 lookups in the namespace, which cost some time. The more such lines in code, the more unnecessary waste of time.
  2. Simplicity. When you write tutorials, you try to explain things as simple as it possible. So the less code, the better tutorial.
  3. Ease. When you type your code, you spread it to different files. Because it is easier to work with smaller side-files, and then import all of them in the main. But you completely understand what you are importing.
  4. Namespase pollution. When you import everything from module into globals, you are more limited in the choice of global variables. For example, from struct import * you can't name your function as pack. So, before use such imports, you should explore the module. What does it contain? What does it import by itself?
  5. Mess. When you use such imports many times, from foo import * and from bar import * and from baz import *, some variables or constants may be shaded or overwritten. In this example, foo.version is overwritten with bar.version, now named as version. So, foo.checkversion() will not work correctly anymore.

The proper way is to import the commonly used functions in explicit form, or make them a quick reference, especially when you do not know the module well.

For example:

from foo.bar.baz impor
answered 2012-04-26T23:30:07.867

Your Answer