Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does from ... import appear to bind to value at import time in Python?

Tags:

python

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?

like image 471
Kelly Joyner Avatar asked May 19 '12 00:05

Kelly Joyner


People also ask

What is from import * in Python?

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.

How do you fix an import error in Python?

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 .

Why is Python running a module when I import it?

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 .


1 Answers

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
like image 191
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 03:10

Ignacio Vazquez-Abrams