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

Carl Banks pavlovevidence at gmail.com
Mon Sep 6 05:15:20 CEST 2010


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.


> But to my way of thinking, the answer should be to avoid ever having
> circular imports.  This is just the most blatant of the problems that
> circular imports can cause.
>
> I don't know of any cases where circular dependencies are really
> necessary, but if one decides to use them, then two things should be done:

I don't think they're ever necessary but sometimes it's convenient.
This could be one of those cases.  One of the less misguided reasons
to invoke a module as a script is to run tests on the module.  When
you do that you might need to call an outside module to set up a test
environment, and that module might happen to import the calling
module.  You could refactor the test to avoid the circular import, but
that kind of defeats the convenience of stowing the test in the
module.


> 1) do almost nothing in top-level code in any module involved in such
> circular dependency.  Top-level should have all of the imports, and none
> of the executable code.
> 2) do not ever involve the startup script in the loop.  If necessary,
> make it two lines, importing,then calling the real mainline.

All good advice for that situation. I would add that if you define a
base class in one module and subclass in another, you want to keep
those modules out of cycles.  The problem with circular imports is
that you don't usually know what order the modules will be imported,
but you need to be sure the base class is defined when you subclass.
(I learned that lesson the hard way, and I had to hack up an import
hook to enforce that imports occurred in the correct order.)


Carl Banks



More information about the Python-list mailing list