'I cannot get the correct value of a modified global variable (from a class) to another class in separate files

So, I have:

file_1.py

variable_one = 20

and I also have:

file_2.py

class class_2():
    def do_something_2(self):
        ...
        from file_1 import variable_one
        variable_one = 100
        print("variable_one = ", variable_one) # 100
        ...

and that:

file_3.py

class class_3():
    def do_something_3(self):
        ...
        from file_2 import variable_one
        print("variable_one = ", variable_one) # 20
        ...

The problem is that although file_2.py changes the variable_one, in the file_3.py I don't get the number 100 but the number 20. variable_one in file_1.py is defined as global. I have tried a recently opened thread, which works for what I asked there but the current problem is a bit different in the current thread (here: Cannot access global variable inside a parent class (python)). I have also tried this suggestion: Working with global variables in multiple classes and multiple modules and I got this:

AttributeError: module 'class_2' has no attribute 'variable_one'

Any idea how to read the correct (modified global variable in file_2.py) from class_3 ???



Solution 1:[1]

I don't get why this should be useful, but here's why it doesn't work like you're trying:

variable_one is only set in file_2.py, if you call class_2.do_something(). To fix this, you have to define variable_one in the constructor of class_2.

from file_1 import variable_one
class class_2:
    def __init__(self):
        self.variable_one = variable_one + 1
    def do_something_2(self):
        pass

Now variable_one is set, when you create an object of type class_2. That's why you cannot import variable_one, as it's not global, just in the scope of class_2.

If you now do the following, you should have access to variable_one from file_3.py:

from file_2 import class_2
class class_3:
    def do_something_3(self):
        c2 = class_2()
        # Now prints variable_one from file_1 incremented by '1' (see file_2)
        print("variable_one =", c2.variable_one)

c3 = class_3()
c3.do_something_3()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ð᠍᠍