Basic 'import' problem
Josiah Carlson
jcarlson at nospam.uci.edu
Sun Feb 8 00:35:46 EST 2004
> Thanks for that. It makes sense.
>
> Now, if X.py imports Y.py and Y.py imports X.py, does this present any
> fundamental problems? (e.g. something get initizlized twice...)
No, Python is smart about that. However, realize that if you try to do
anything with X in Y before X is done being imported, then Y will have
issues.
Don't:
#in X.py
from Y import *
#in Y.py
from X import *
The above will result in Y getting a partial namespace update from X,
really only getting everything initialized before the 'from Y import *'
statement in X.py.
Won't work:
#in main.py
import X
#in X.py
import Y
def blah():
pass
#in Y.Py
import X
X.blah()
Will work:
#main.py
import X
import Y
X.runme()
Y.runme()
#in X.py
import Y
def runme():
print "calling Y.runyou"
Y.runyou()
def runyou():
print "called X.runyou"
#in Y.py
import X
def runme():
print "calling X.runyou"
X.runyou()
def runyou():
print "called Y.runyou"
Notice in the last version, we allow the entirety of the function
definitions and namespaces to be completely initialized by the time we
call anything? Yeah, that is another method.
- Josiah
More information about the Python-list
mailing list