accessing variable of the __main__ module

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 20 10:04:41 EDT 2010


On Sat, 20 Mar 2010 14:32:03 +0100, News123 wrote:

>> You try to import from "__main__", but the other module is called
>> "main". __main__ is a special name, which Python understands as meaning
>> "this module that you are in now". For example:
>
> My choice of names was perhaps not very smart. I could have called
> main.py also mytoplevel.py
[...]
> I think you're wrong, my above code seems to work. __main__  refers not
> to the current module, but to the urrent 'top-level-module'
> so
> from __main__ import A tries to import from the top level module which
> is in my case main.py.

Hmmm... it looks like you are correct and I made a mistake.

This isn't something that the documentation is clear about, but here are 
a set of test files:


$ cat A.py
import __main__
import B
print __main__, B, B.__main__

$ cat B.py
import __main__

$ python A.py
<module '__main__' from 'A.py'> <module 'B' from '/home/steve/python/
B.pyc'> <module '__main__' from 'A.py'>


Here is the documentation:

http://docs.python.org/library/__main__.html

which is pretty sparse.



-- 
Steven



More information about the Python-list mailing list