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?
http://www.pygame.org/docs/tut/ImportInit.html
The first line here is the only necessary one. It imports all the available pygame modules into the pygame package. The second line is optional, and puts a limited set of constants and functions into the global namespace of your script.
Actually, from the pygame docs:
So all these constants are already there when you use
import pygame
. We can see this if we do this:So,
pygame.locals
is a subset ofimport pygame
.. So absolutely no point doing it if you have already imported pygame! Apart from it allows you to access them without thepygame
prefix.imports the pygame module into the "pygame" namespace.
copys all names in pygame.locals into your current namespace. This is not neccessary, but saves you typing.
I would not worry about it. I know you may have been told that
*
imports are bad. That is true to some extent, unless Pygame developers specifically defined the__all__
attribute, in which they've put all those handy-dandy constants in, and they have. So, that way they made this particular*
import safe.The
*
relates to the__all__
attribute, so search thepygame.locals
source code for all the constants included in the__all__
attribute.Nope. Not necessarily.
When you execute
the pygame is fully imported and ready to work, no more imports are needed.
Now the question is about this line:
There are several reasons why this should be used, and a few reasons not to do so.
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.from struct import *
you can't name your function aspack
. So, before use such imports, you should explore the module. What does it contain? What does it import by itself?from foo import *
andfrom bar import *
andfrom baz import *
, some variables or constants may be shaded or overwritten. In this example,foo.version
is overwritten withbar.version
, now named asversion
. 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:
or
Here
quick_referenced_fn
is stillfoo.bar.baz.a_very_useful_function
and works in the namespace offoo.bar.baz
, but interpreter knows its address directly and will not make additional lookups.