I found an interesting behavior in Python which I would like to fully understand.
setup.py:
good='hello'
def isGood(testGood): return testGood == good
print(isGood('hello'))
print(isGood('bye'))
good='bye'
print(isGood('bye'))
Output is:
True
False
True
main.py:
from setup import *
print(good)
print(isGood('hello'))
good='hello'
print(good)
print(isGood('hello'))
Output is:
True
False
True
bye
False
hello
False
In short: Function isGood() is sensitive to the changes of global variable 'good' when the function is used inside setup.py. However, once imported (with from setup import *), the function is no more sensitive to changes of variable 'good'. There is no difference in the behavior if declaring 'global good' (it is also not expected to make such, in this case).
How is this explained? It is if the function content (non-input variables) are "compiled" after the import. I'm looking for a source that documents this behavior (to know if it can be trusted).
When you use
from module import *
you will create duplicate instances of them locally.In your example,
good
inmain.py
is just a copy ofgood
insetup.py
, and changing it inmain.py
does not affect the variable insetup.py
.If you want to be able to access it, You can use one of these methods below:
Method 1
Use a function to set the variable:
setup.py
main.py
Method 2
Use a class to keep the variable
main.py
Method 3
Import module and access the variable
main.py