If you modified your subtwo.py this way then it will work
import subone
print subone.a
When you do subone.a in subtwo.py, you are trying to access the namespace subone in subtwo.py and in the namespace "subone", there should be a attribute "a".
When you do - import subone in subtwo.py, then subone is added to the namespace and subone namespace has attribute a. so subone.a will work.
I would also suggest that you play with dir() to see how namespaces are being added.
In subtwo.py, you can do the following:
print dir()
import subone
print dir()
print subone.a
Similarly, try adding "print dir()" before and after your import statements and the idea should become clear to you.
"import x" adds 'x' to the current modules
namespace while "from x import * " will
add all the module level attributes
directly into current module namespace
So in your above first example of main.py, subone.py and subtwo.py, the namespace in main.py will contain 'subone' and 'subtwo' while subtwo.py will have an empty namespace and can not access subone.a.
[Edit: Some more explanations]
Consider following files:
main.py
print "Before importing subone : ", dir()
import subone
print "After importing subone and before importing subtwo: ", dir()
import subtwo
print "After importing subone and subtwo: ", dir()
subone.py
a = 'abc'
subtwo.py
print dir()
import subone
print "module level print: ", subone.a
print dir()
def printX():
print subone.a
And the output of running main.py:
Before importing subone : ['__builtins__', '__doc__', '__file__', '__name__', '__package__']
After importing subone and before importing subtwo: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'subone']
['__builtins__', '__doc__', '__file__', '__name__', '__package__']
module level print: abc
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'subone']
After importing subone and subtwo: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'subone', 'subtwo']
Some Observations
- You will notice that importing a module subtwo.py, the print statement is executed immediately.
- So when subone and subtwo are imported in main.py, the namespace of main.py is augmented.
- That does not mean that namespace of subtwo will be augmented. so "a" is available only in main.py via subone.a
- When we do import subone in subtwo.py then the namespace of subtwo is augmented with subone and attribute a of module subone is available in subtow.py via subone.a