Using global variables between files?

The problem is you defined myList from, but needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file This file is responsible for defining globals and initializing them:


def init():
    global myList
    myList = []

Next, your subfile can import globals:


import settings

def stuff():

Note that subfile does not call init()— that task belongs to


import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result

This way, you achieve your objective while avoid initializing global variables more than once.

Leave a Comment