Jan-20-2021, 07:02 PM
In Python each code file is a "module". Modules each have a namespace. You can access these variables if you have access to their namespace. When you do "import module" you are gaining access to the module's namespace.
I have three files;
test1.py:
Also notice that "from test1 import x' does not work the same as explicitly using the namespace (test1.x). It would appear that "from test1 import x" creates a new variable in the current module's namespace. This was verified by checking the variable id.
I have three files;
test1.py:
x = 10 def printx(): print(x)test2.py
import test1 def printx(): print(test1.x) def setx(value): test1.x = valuetest3.py
import math import test1 import test2 from test1 import x print(x, test1.x) test1.printx() test2.printx() print('test2.setx(42)') test2.setx(42) print(x, test1.x) test1.printx() test2.printx() print('test1.x = PI') test1.x = 'PI' print(x, test1.x) test1.printx() test2.printx() print('x = math.pi') test1.x = math.pi print(x, test1.x) test1.printx() test2.printx()When I execute test3.py I get this:
Output:========== RESTART: C:\Users\hystadd\Documents\python\sandbox\junk.py ==========
10 10
10
10
test2.setx(42)
10 42
42
42
test1.x = PI
10 PI
PI
PI
x = math.pi
10 3.141592653589793
3.141592653589793
3.141592653589793
Notice that I can set the value of test1.py from modules test1, test2 or test3. When I change the value of test1.x the change can be seen in test1, test2 and test3.Also notice that "from test1 import x' does not work the same as explicitly using the namespace (test1.x). It would appear that "from test1 import x" creates a new variable in the current module's namespace. This was verified by checking the variable id.
Output:>>> id(x)
140721929705408
>>> id(test1.x)
2714390832848
This could be an issue if you use from..import.. and expect to be able to change an immutable variable.