Update imported variable from another file using function

Question:

first.py:

from third import *
from second import *

while running:
    off()

second.py:

from third import *

def off():
    running = False

third.py:

running = True

The program still running and running variable is not accessed.

I want to calling a function which is in another file, the function change the boolean which is in another file. I know I can just type everything to the first file but I want separate files for functions and variables.

I expect to close the program after running.

I tried using global variables.
I read all similar questions.

Asked By: Sedus

||

Answers:

Your line: running = False doesn’t do what you want it to do.

The key to remember with python is that imports create new variables in the module that does the import. This means for variables declared in another module, your module gets a new variable of the same name. The second thing to note is that assignment only affects the variable assigned to.

Your code should look like this:

first.py:

import third
from second import *

while third.running:   # This now accesses the running variable in third
    off()

second.py:

import third

def off():
    third.running = False   # This now reassigns the running variable in third
Answered By: quamrana

In third.py,
Make A Getter Function For running Variable.
It Will Look Like:

running = True
def getRunning():
    return running

And In first.py,
It Will Look Like:

while getRunning():
    off()
Answered By: LakshyaK2011
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.