0

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 ???

just_learning
  • 413
  • 2
  • 11
  • 24
  • 1
    I guess, `from class_2 import variable_one` should be `from file_2 import variable_one`? Otherwise, with this setup, the import won't work, won't it? –  May 19 '22 at 14:13
  • I changed it! Wrong representation because the code is much larger and I give the main idea here... Thanks! So, I correct it to my question...How can I solve this problem? – just_learning May 19 '22 at 14:16

1 Answers1

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()
  • I get this: ```from file_2 import class_2 ImportError: cannot import name 'class_2' from partially initialized module 'file_2' (most likely due to a circular import) (/home/user/Desktop/my_code/file_2.py)``` – just_learning May 20 '22 at 11:57
  • In **file_1.py** I have also ```from file_2 import class_2```. And maybe that's the problem, but I can't remove it, because it does not work.... – just_learning May 20 '22 at 12:22