Can someone explain this weird Pygame import agreement?

I see that people usually import Pygame as follows:

import pygame
from pygame.locals import *

I do not understand what the second line is for. If we have already imported all Pygame, why import pygame.locals? Does Pygame include it after importing it?

+5
source share
6 answers
import pygame

imports the pygame module into the pygame namespace.

from pygame.locals import *

copies all the names in pygame.locals to your current namespace. This is not necessary, but saves you typing.

+6
source

Actually, from pygame docs :

, Pygame. pygame. pygame.locals Pygame 'from pygame.locals import *'.

, , import pygame. , :

>>> import pygame
>>> from pygame.locals import *
>>> set(dir(pygame.locals)).issubset(set(dir(pygame)))
True

, pygame.locals import pygame. , pygame! pygame.

+5

import pygame

pygame , .

:

from pygame.locals import *

, , .

  • .. - foo.bar.baz.ClassName.classmethod(), 4 , . , .
  • .. , , . , .
  • .. , . -, . , .
  • .. , . , from struct import * pack. , . ? ?
  • . , from foo import * from bar import * from baz import *, . foo.version bar.version, version. , foo.checkversion() .

, , .

:

from foo.bar.baz import a_very_useful_function

import foo.bar.baz
quick_referenced_fn = foo.bar.baz.a_very_useful_function

quick_referenced_fn - foo.bar.baz.a_very_useful_function foo.bar.baz, .

+2
import pygame
from pygame.locals import *

http://www.pygame.org/docs/tut/ImportInit.html

- . pygame pygame. script.

+1

Pygame ?

. .

stefanos-imac:python borini$ touch a/__init__.py
stefanos-imac:python borini$ touch a/b.py
stefanos-imac:python borini$ echo "print 'hello' " >a/b.py 
stefanos-imac:python borini$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
>>> import a.b
hello
>>> 
+1

I would not worry about that. I know you were told that imports are *bad. This is true to some extent, unless Pygame developers defined an attribute __all__into which they entered all these handy dandy constants, and they are. Thus, they made this particular import *safe.

*refers to the attribute __all__, so find the source code pygame.localsfor all the constants included in the attribute __all__.

0
source

All Articles