Search code examples
pythonshareglobal

Using global variables between files?


I'm bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.

What I did was define them in my projects main.py file, as following:

# ../myproject/main.py

# Define global myList
global myList
myList = []

# Imports
import subfile

# Do something
subfile.stuff()
print(myList[0])

I'm trying to use myList in subfile.py, as following

# ../myproject/subfile.py

# Save "hey" into myList
def stuff():
    globals()["myList"].append("hey")

An other way I tried, but didn't work either

# ../myproject/main.py

# Import globfile    
import globfile

# Save myList into globfile
globfile.myList = []

# Import subfile
import subfile

# Do something
subfile.stuff()
print(globfile.myList[0])

And inside subfile.py I had this:

# ../myproject/subfile.py

# Import globfile
import globfile

# Save "hey" into myList
def stuff():
    globfile.myList.append("hey")

But again, it didn't work. How should I implement this? I understand that it cannot work like that, when the two files don't really know each other (well subfile doesn't know main), but I can't think of how to do it, without using io writing or pickle, which I don't want to do.


Solution

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

    # settings.py
    
    def init():
        global myList
        myList = []
    

    Next, your subfile can import globals:

    # subfile.py
    
    import settings
    
    def stuff():
        settings.myList.append('hey')
    

    Note that subfile does not call init()— that task belongs to main.py:

    # main.py
    
    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.