Python Forum

Full Version: Python reading variable in another py file wrongly
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have 2 .py files below (Both shortened and include the problem sections):
engine.py
import events

running = False;

def start():
    boot() #Can be safely ignored all it does is call pygame.init()
    running = True;

    while running:
        events.update_events()
        if events.exit_request is not None:
            running = False

    #Logic here

    shutdown()
events.py
import pygame

exit_request = None

def update_events():
    for event in pygame.event.get():
        if(event.type == pygame.QUIT):
            exit_request = event
While I am using pygame, that isn't where the problem lies, I have tested it and the problem is that if I access the exit_request variable in the events file from engine.py, it will always show up as None even if there is an exit event, but if I print exit_request from inside events.py, it will show up appropriately as pygame_exit_blah blah blah if the user clicked the x button, but like I said will show up as "None" if printed from engine.py. Does anyone know why this is happening?
This is a scope problem and has nothing to do event_request being in another file. You would have the same probem if this were all in one file.

The problem is you have two exit_request variables. One in events and one in events.update_events. If you want these to reference the same thing you need to rewrite update_events like this:
def update_events():
    global exit_request
    for event in pygame.event.get():
        if(event.type == pygame.QUIT):
            exit_request = event
This tells Python to use events.exit_request instead of creating events.update_events.exit_request when you do this:
exit_request = event
By default assignment inside a function creates a new variable. If this were not the case there would be no way to make "local" variables. To prevent this from happening you need to define the variable as "global".
(Nov-20-2020, 11:17 PM)deanhystad Wrote: [ -> ]This is a scope problem and has nothing to do event_request being in another file. You would have the same probem if this were all in one file.

The problem is you have two exit_request variables. One in events and one in events.update_events. If you want these to reference the same thing you need to rewrite update_events like this:
def update_events():
    global exit_request
    for event in pygame.event.get():
        if(event.type == pygame.QUIT):
            exit_request = event
This tells Python to use events.exit_request instead of creating events.update_events.exit_request when you do this:
exit_request = event
By default assignment inside a function creates a new variable. If this were not the case there would be no way to make "local" variables. To prevent this from happening you need to define the variable as "global".
THANK YOU SO MUCH! IT WORKED!!!