The Python Oracle

Change global variable in a module from a function defined in another module

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 Change Global Variable In A Module From A Function Defined In Another Module
00:57 Answer 1 Score 3
01:22 Accepted Answer Score 4
02:24 Thank you

--

Full question
https://stackoverflow.com/questions/3593...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #global

#avk47



ACCEPTED ANSWER

Score 4


The issue has to do with the main.py file being loaded twice. It first gets loaded as __main__ when you run it as a script. It also gets imported by other.py as its regular name main.

The two copies are completely separate from each other, and have separate global variables! When other.check calls main.shutdown to modify the isRunning global variable, it only changes the main.isRunning version, not __main__.isRunning. The main function is checking __main__.isRunning which doesn't ever get changed.

There are several ways you can fix this. The best is probably to get rid of your circular import in some way. While circular importing can work OK in Python, it's often a symptom of bad design. It's a very bad idea to use it with any module that may be run as a script.




ANSWER 2

Score 3


Try this:

import other


def main():
    while other.run():
        # some logic here
        other.check()

if __name__ == '__main__':
    main()

other.py

import main

isRunning = True
def run():
    return isRunning

def check():
    global isRunning
    someCondition = #some logic to check the condition
    if someCondition:
        isRunning = False

If I was you I would use objects and classes..., global methods and variables are not "debug and maintenance friendly"