Exceptions and modules / namespaces question
Samuele Pedroni
pedronis at bluewin.ch
Thu Mar 28 19:06:51 EST 2002
The problem is that "import module1" in
module2 is re-executing your main script
a second time and so creating new
definitions.
The main script, as the "if __name__ ==
'__main__' " idiom hints, appear as loaded (in the module
cache sys.modules)
under such a name, so "import module1"
triggers the loading of module1.py
as distinct (new) module from the main script.
Consider:
#mod.py:
class C: pass
if __name__ == '__main__':
import mod
import sys
print "module __main__: ",sys.modules['__main__']
print "module mod:", mod
print "are the same?",{0: 'n',1: 'y'}[sys.modules['__main__'] is mod.C]
print "class C in main script:",C
print "class C from mod:",mod.C
print "are the same?",{0: 'n',1: 'y'}[C is mod.C]
Output:
$python mod.py
module __main__: <module '__main__' (built-in)>
module mod: <module 'mod' from 'mod.pyc'>
are the same? n
class C in main script: __main__.C
class C from mod: mod.C
are the same? n
regards.
More information about the Python-list
mailing list