views:

55

answers:

2

I'm working on a pygame project and have the main engine layed out. The problem is I hit a bug that I just can not seem to figure out. What happens is one module can't read a variable from another module.

It's not that the variable can't be read, it just sees an empty list instead of what it really is.

Instead of posting the entire source code I reproduced the bug in two small snippets that hopefully a skillful python-ist can interpret in his\her head.

Code:

main.py (This is the file that gets run) import screen

screens = [] #A stack for all the game screens

def current_screen():
    #return a reference to the current screen
    return screens[-1]

def play():
    print'play called'
    current_screen().update()

if __name__=='__main__':
    screens.append(screen.Screen())
    play()

screen.py

import main

class Screen:
    def __init__(self):
        print'screen made'
    def update(self):
        print main.screens
        #Should have a reference to itself in there

Thanks!

+3  A: 

Don't import the main script. When you run the main.py file directly, it becomes the __main__ module. When you then import main, it will find the same file (main.py) but load it a second time, under a different module object (main instead of __main__.)

The solution is to not do this. Don't put things you want to 'export' to other modules in the main script. It won't work right. Put them in a third module. Or, pass them as arguments to the functions and classes you're calling.

Thomas Wouters
Ah, that makes a lot of sense now. Thanks so much for the help!
Nick
A: 

The whole point of if __name__=='__main__': is to prevent code from being run when a module is imported. So when you import main from screen, that part isn't run and the list stays empt and play() is never called either.

THC4k