Class changes in circular imports when __name__ == '__main__'

Carl Banks pavlovevidence at gmail.com
Tue Sep 7 07:08:22 CEST 2010


On Sep 6, 4:44 pm, Dave Angel <da... at ieee.org> wrote:
> On 2:59 PM, Carl Banks wrote:> On Sep 5, 5:07 pm, Dave Angel<da... at ieee.org>  wrote:
> >> On 2:59 PM, Carl Banks wrote:
> >>> All of this gets a lot more complicated when packages are involved.
> >> Perhaps a better answer would be to import __main__ from the second module.
> > Then what if the module is imported from a different script?  It'll
> > try to import __main__ but get a different script than expected.
>
> Then the module needs to adjust its expectations.

No, it shouldn't.  It shouldn't have any expectations at all, because
importing __main__ and expecting to get a particular module is a
foolish thing to do.  There are a bunch of reasons why __main__ might
not be the original script.  Example: running the profiler on it.


> The point is it
> should never try to import the script by name.

Importing __main__ directly is worse than the problem it's trying to
solve.

And "never" is too strong a word.  I already in this thread gave a
solution whereby the script can be imported by name safely, by
renaming itself and assigning itself an item in sys.modules.  When you
do that, you can import the main script by name.


Carl Banks



More information about the Python-list mailing list