rlms
rlms

Reputation: 11060

Structuring function definitions

I currently have some code like this:

def print_to_window(text):
    window.print_text(text)
    do_other_stuff()

class WithMethodsThatCallprint_to_window:
    something()

class ThatAlsoHasMethodsThatCallprint_to_window:
    something()


# actual game code starts  
window = Window()
a = WithMethodsThatCallprint_to_window()
while True:
    get_input()
    do_stuff()

Calling Window opens the window, which I don't want to happen when I import the module for testing.

I'd like to restructure this to have the "actual game code" in a main function, and then do if __name__ == "__main__": main(). However, I can't work out how to do this.

If I just move the code after #actual game code starts into a function, then window is no longer a global variable, and print_to_window can't access it.

However, moving print_to_window into the main function causes the same problem with the classes that use it.

How should I restructure the code?

Upvotes: 0

Views: 31

Answers (1)

Dettorer
Dettorer

Reputation: 1336

You can define the name window at the global level, then assign it to an object in the main function:

window = None

def main():
    global window
    window = Window()
    # do things
    print_to_window("some text")

if __name__ == "__main__":
    main()

Edit: forgot the "global window" in main, allowing print_to_window to see the modified window.

Upvotes: 1

Related Questions