Yes, your observations are correct. This is a consequence of the way that binding works in Python.
When one does
import foo
then foo
becomes a global name that references the module foo
. When one does
foo.bar = 7
Then the reference is followed and the object foo
is loaded. Then 7
is stored in the bar
attribute.
When another module imports foo
, it just pulls the object out of sys.modules['foo']
and gets the modified value.
When one does
from foo import bar
globals()['bar']
is set to reference foo.bar
. When one later does
bar = 7
globals()['bar']
no longer references foo.bar
but references a copy of 7
. That is, the original binding in the global scope of the importing module is simply replaced.
In the fist example, one is modifying attributes of an object that is stored in sys.modules
and will be common to all modules that have imported it. In the second example, one is modifying the global scope of the importing module.
If one was to do something along the lines of
from foo import fobaz
fobaz.foobar = 7
Then that change would be propagated to other importing modules because one is not overwriting the global reference but following it to modify an attribute of the object that it points to. So essentially, you should be able to modify mutable objects so long as you don't overwrite the global binding.
I think that something like this is the closest that you are going to be able to cleanly get to a true global in python. As a language, it greatly values namespaces.
OrderedDict
is a class within the collections
module. When you see things like x.y and something is being imported from it, that means that "y" in this case is actually a module.
You should read the docs about how import
works: here. It's long and involved but at the same time fairly straight forward in how it looks into the different packages and modules to find what should be brought into play. Specifically, the import statement itself and import system.
Best Answer
First statement imports the specified module into the current namespace.
Second statement imports everything from the specified module into the current namespace.
So 1) means you still need to explicitly reference any classes/functions etc through the module namespace
2) Means you don't
Here's a compare and contrast that shows the difference
1)
2)
Note that you can choose to import a specific symbol from a module if you want i.e.