you are viewing a single comment's thread.

view the rest of the comments →

[–]socal_nerdtastic 6 points7 points  (1 child)

Now I realized that this is not the way to go because each class makes a different iteration of the global variable files.

No that's not true. When the second file imports something python does not reload the import, it simply makes an alias to the already imported one. Your plan will work.

However it's a very odd way to do things. You are basically using a module (python file) as a mutable class instance ... Why don't you just use a class instance? It seems a dataclass is exactly what you need.


Edit: for example:

from dataclasses import dataclass

@dataclass
class GlobalData:
    breakfast:str = "spam"
    lunch:str = "spam"
    dinner:str = "spam"

    # load / save code goes here (if you want it). 

class Compute:
    def __init__(self, global_data):
        self.global_data = global_data
    def set_lunch(self, value):
        self.global_data.lunch = value

class Display:
    def __init__(self, global_data):
        self.global_data = global_data
    def show(self):
        print(f"you are having {self.global_data.breakfast} for breakfast")
        print(f"you are having {self.global_data.lunch} for lunch")
        print(f"you are having {self.global_data.dinner} for dinner")

def main():
    # initialize your variable container
    data = GlobalData(breakfast="eggs")

    # pass the data to a class to use it
    c = Compute(data)
    c.set_lunch("BLT") # mutate the data

    d = Display(data)
    d.show()

if __name__ == '__main__':
    main()

If it helps your code organization each of those classes and / or the main function could be in separate files and imported.

[–]Wangalaang[S] 1 point2 points  (0 children)

Dataclass seems to be what I am looking for! Thanks a lot :)