Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone please explain this weird Pygame importing convention?

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?

like image 574
corazza Avatar asked Apr 26 '12 15:04

corazza


People also ask

What does import pygame mean?

import pygame from pygame.locals import * 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.

What does from pygame locals import * mean?

from pygame. locals import * copys all names in pygame. locals into your current namespace. This is not neccessary, but saves you typing.

How do I import imports into pygame?

Open a terminal, and type 'sudo apt-get install idle pygame', enter your password and type 'y' at the prompts, if necessary. 2. After the installation completes, enter 'python' in the terminal to launch Python. Verify that it's using version 2.7 or newer, then at the Python prompt enter 'import pygame'.


2 Answers

import pygame

imports the pygame module into the "pygame" namespace.

from pygame.locals import *

copys all names in pygame.locals into your current namespace. This is not neccessary, but saves you typing.

like image 136
ch3ka Avatar answered Oct 14 '22 06:10

ch3ka


Actually, from the pygame docs:

This module contains various constants used by Pygame. It's contents are automatically placed in the pygame module namespace. However, an application can use pygame.locals to include only the Pygame constants with a 'from pygame.locals import *'.

So all these constants are already there when you use import pygame. We can see this if we do this:

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

So, pygame.locals is a subset of import pygame.. So absolutely no point doing it if you have already imported pygame! Apart from it allows you to access them without the pygame prefix.

like image 36
fraxel Avatar answered Oct 14 '22 05:10

fraxel