main.py:
import subone
import subtwo
subone.py:
a = 'abc'
subtwo.py:
print subone.a
Running python main.py
throws a NameError: name 'subone' is not defined
. I expected it to print 'abc'.
Refactoring it to use from
import
and classes doesn't help:
main.py:
from subone import * # Only using from X import * for example purposes.
from subtwo import *
print 'from main.py:', a.out
subone.py:
class A:
out = 'def'
a = A()
subtwo.py:
# This throws NameError: name 'a' is not defined
print a.out
# This throws NameError: name 'A' is not defined
b = A()
print b.out
BUT it will print 'from main.py: def'. (It works when using import
too.)
Why does it work this way? It seems like once subone
is imported, it should be available to subtwo
.
Is it because it's bad programming to have imported modules depend on each other without going through their 'parent' module? Is there another, standard way to do this?
Update:
I now understand that the first example will not work because the line print subone.a
doesn't recognize the name subone
, it not being in subtwo
's namespace (even though it's in main.py
's), and it is being called from within the module subtwo
. This can be fixed by using import subone
at the top of subtwo.py
-- it will not re-load the module but will add it to subtwo
's namespace so subtwo
can use it.
But what about this:
main.py:
from subone import Nugget
from subtwo import Wrap
wrap = Wrap()
print wrap.nugget.gold
subone.py:
class Nugget:
gold = 'def'
subtwo.py:
class Wrap:
nugget = Nugget()
I would think that since Wrap
and Nugget
are both loaded directly into main
's namespace, that they would use main
's namespace and be able to reference each other, but it throws a NameError: name 'Nugget' is not defined
. IS IT because Wrap
is evaluated/checked from within subtwo
's namespace BEFORE being loaded into main
's namespace?