What is the difference between .locals import * and import local

Viewed 86

I am writing a code for flappy bird and I was watching a tutorial on collision and they used:

from pygame.locals import *

Why don't they just use:

from pygame import local

What is the difference and how does it change the code? Does it import all of that library or just a specific bit. As I thought you would just use import pygame for that?

2 Answers

Let's understand it by a example

I have Directory named myApp and inside it I have 2 files

~app.py ~helper.py

In helper.py my code is

abc1 = 'hi'
abc2 = 'bye

In app.py my code is

from helper import *
print(abc1)
print(abc2)

So by use of from helper import * I can import all variables and functions from it but if I use from helper import abc1 it only import abc1 value

The first one imports everything from pygame.locals. You can then access elements of the pygame.locals without prefixing with the module name.

from pygame.locals import *
print(K_a)  # 97 = ascii code of 'a'

The second one imports the module locals from pygame. You can basically access the same things but now you have to use the module name as a prefix.

from pygame import locals
print(K_a)  # NameError: name 'K_a' is not defined
print(locals.K_a)  # 97 = ascii code of 'a'

The second form is preferable because then you do not have the risk of hiding definitions in pygame.locals as below:

from pygame.locals import *
K_a = 21  #  hide K_a from pygame.locals
Related