Your foo module and the main module that imports it (named __main__ ) have separate namespaces.
Here's what happens:
- Importing
foo sets foo global variable x to access integer 0 . - This link is copied to
__main__ as a global variable x . - You call
foo.foo() , which sets the global variable foo x to access integer 1 . - You print the global variable
__main__ x . Since you never changed what relates to this x value, it still refers to 0 , this is what is printed.
In short, importing a name into a module does not create any binding between the names in the two modules. Initially, they refer to the same value, but if one name is bound to another object, the other does not necessarily follow.
This is (one) the reason why import foo is generally a better idea. Referring to foo.x explicitly in __main__ , foo matches the global variable x exactly and will refer to the current value of the name, even if it has been changed.
source share