Why does import ... seem to bind to value during import in Python?

All the Python docs I read show that the side effects are aloof, that if you import module A and then refer to Aa, you are referring to the same variable as if you wrote "from A import a".

However, this does not seem to be the case, and I'm not sure what is happening. I am using Python 2.6.1.

If I create an alpha.py module:

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 this?

+5
source share
2 answers

from ... import ...always linked immediately, even if the previous one importimported only 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
+5
source
0

All Articles