Home > Software engineering >  Global shared variable
Global shared variable

Time:10-04

In my project, I would like to have a global "Filemanager", so that I always access up-to-date information. I have written a nice short example to explain my problem since I don't want to paste my entire code here.

I have two files:
main.py

class GlobalList:

    def __init__(self):
        self.pool = []

    def add(self, toadd):
        self.pool.append(toadd)

global list
list = GlobalList()
list.add("Test from main")

from other_file import add_sth
add_sth()

list.add("Hello again from main.py")

other_file.py

def addme():
    global list
    list.add("Hello from other_file.py")

This does NOT work since the addme function cannot access the global "list" variable.
I also tried "importing" the list from the main module using

from main import list

def addme():
    list.add("Hello from other_file.py")

Which to no surprise doesn't work because it throws a circular import error.

I really don't want to pass the "list" object to every function requiring it because then every function would have a lot of parameters.

CodePudding user response:

We can easily break that recursive import by putting the GlobalList in a different file from main.py.

global_list.py

class GlobalList:

    def __init__(self):
        self.pool = []

    def add(self, toadd):
        self.pool.append(toadd)

glist = GlobalList()

other_file.py

from global_list import glist

def add_sth():
    glist.add("Hello from other_file.py")

main.py

from global_list import glist
glist.add("Test from main")

from other_file import add_sth
add_sth()

glist.add("Hello again from main.py")

print(glist.pool)

Which outputs

['Test from main', 'Hello from other_file.py', 'Hello again from main.py']

CodePudding user response:

Much as I want you to pass GlobalList around, to solve your exact problem at the moment you should put this code:

class GlobalList:

    def __init__(self):
        self.pool = []

    def add(self, toadd):
        self.pool.append(toadd)

global_list = GlobalList()

into, say, Global.py

Then all your other files should start with:

from Global import global_list

and access it like: global_list.add("Test from main")

  • Related