Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyGame Local Variables

Tags:

python

pygame

This is (I assume) a basic question, but I can't seem to figure it out.

Given the following code:

from src.Globals import *
import pygame
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# This is a list of 'sprites.'
block_list = pygame.sprite.Group()

def update_screen():
    # Loop until the user clicks the close button.
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        # Clear the screen
        screen.fill(WHITE)

        for i in blocks:
            block_list.add(block)

        block_list.draw(screen)

        # Limit to 20 frames per second
        clock.tick(20)

        # Update the screen with what we've drawn.
        pygame.display.flip()

    pygame.quit()

Everything works fine. I can call the function update_screen in a thread and have it work correctly. However, if I move done = False above the function declaration, then I get the error: UnboundLocalError: local variable 'done' referenced before assignment.

My question is: why is it that I can safely have clock, and block_list outside of the function, but not done?

like image 655
Teknophilia Avatar asked Apr 10 '26 16:04

Teknophilia


1 Answers

After moving done variable above function you have to explicitly point interpreter that done variable within function is global

done = False
def update_screen():
    # Loop until the user clicks the close button.
    global done
    while not done:
    # .......

You have to identify variable with global in case if you have direct assignment to that variable, for instance a = 10. In code snippets above everything works fine for clock and block_list because there are no direct assignments to that vars within function body.

That's required because all variables, which value has been assigned in function body is treated as function local vars.

You can find more info by urls below:

  • Execution Model, official documentation
  • Short Description of the Scoping Rules?
  • A Beginner’s Guide to Python’s Namespaces, Scope Resolution, and the LEGB Rule
like image 151
Andriy Ivaneyko Avatar answered Apr 17 '26 11:04

Andriy Ivaneyko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!