One source of difficulty with this question is that you have a program called bar/bar.py : import bar imports either bar/__init__.py or bar/bar.py , depending on where it is done, what makes it a little cumbersome to keep track of a - bar.a
Here's how it works:
The key to understanding what is happening is the realization that, in __init__.py ,
from bar import a
essentially doing something like
a = bar.a
and defines a new variable ( bar/__init__.py:a , if you want). So your from bar import a in __init__.py binds the name bar/__init__.py:a to the original bar.py:a ( None ) object. That is why you can do from bar import a as a2 in __init__.py : in this case it is clear that you have both bar/bar.py:a and the different variable name bar/__init__.py:a2 (in your case the names of two variables just happen both of them are a , but they still live in different namespaces: in __init__.py they are bar.a and a ).
Now that you do
import bar print bar.a
you get access to the variable bar/__init__.py:a (since import bar imports your bar/__init__.py ). This is the variable you are modifying (up to 1). You do not touch the contents of the variable bar/bar.py:a . Therefore, when you subsequently perform
bar.foobar()
you call bar/bar.py:foobar() , which accesses the variable a from bar/bar.py , which is still None (when foobar() defined, it binds the variable names once and for all, therefore a in bar.py is bar.py:a , and not any other variable a defined in another module, since all imported modules can have many variables a ). Therefore, the last conclusion is None .
Eric O Lebigot Aug 21 '10 at 9:05 a.m. 2010-08-21 09:05
source share