accessing variable of the __main__ module

Steven D'Aprano steve at
Sat Mar 20 15:04:41 CET 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
> also
> 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

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
import __main__
import B
print __main__, B, B.__main__

$ cat
import __main__

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

Here is the documentation:

which is pretty sparse.


More information about the Python-list mailing list