All the Python docs I've read appear to indicate that, side-effects aside, that if you import module A and then reference A.a, you are referencing the same variable as if you wrote "from A import a".
However, that doesn't appear to be the case here and I'm not sure what's going on. I'm using Python 2.6.1.
If I create a module alpha.py:
bravo = None
def set_bravo():
global bravo
bravo = 1
Then create a script that imports the module:
import sys, os
sys.path.append(os.path.abspath('.'))
import alpha
from alpha import bravo
alpha.set_bravo()
print "Value of bravo is: %s" % bravo
print "Value of alpha.bravo is: %s" % alpha.bravo
Then I get this output:
Value of bravo is: None
Value of alpha.bravo is: 1
Why is that?
The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.
Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .
This happens because when Python imports a module, it runs all the code in that module. After running the module it takes whatever variables were defined in that module, and it puts them on the module object, which in our case is salutations .
from ... import ...
always binds immediately, even if a previous import
only imported the module/package.
EDIT:
Contrast the following:
import alpha
alpha.set_bravo()
from alpha import bravo
print "Value of bravo is: %s" % bravo
print "Value of alpha.bravo is: %s" % alpha.bravo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With