Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables between modules [duplicate]

I have not been able to find a reason why the matter does not work for me, so I would like to ask a question here.

I have 2 files:

file2.py:

def test():
    global justTry
    justTry = "hello"

and main.py:

from file2 import *

def main():
    print(justTry)

if __name__ == '__main__':
    test()
    main()

And I am getting the error: NameError: name 'justTry' is not defined. Why can't I use the justTry variable, which I declared as a global variable in the step before the listing?

like image 338
xHybrid Avatar asked Aug 28 '26 10:08

xHybrid


1 Answers

when "*importing" something, it executes the code, and copy's the globals in to your globals. but if globals get alterd later, it won't re-copy the globals. the solution is, to re-import the file after test is called

file2.py:

def test():
    global justTry
    justTry = "hello"

main.py:

from file2 import *

def main():
    print(justTry)

if __name__ == '__main__':
    test()
    from file2 import *
    main()
like image 197
jp_ Avatar answered Aug 29 '26 23:08

jp_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!