package import dangers
davea at ieee.org
Wed Oct 7 08:13:34 CEST 2009
Steven D'Aprano wrote:
> On Tue, 06 Oct 2009 21:44:35 -0400, Dave Angel wrote:
>> I'm surprised to see you missed this. A module doesn't generally import
>> itself, but it's an easy mistake for a circular dependency to develop
>> among modules.
> Circular imports are always a difficulty. That has nothing to do with
> making modules executable as scripts.
I was mainly making the point that while self-importing would be rare,
circular imports probably crop up fairly often. Circular imports are
(nearly always) a design flaw. But until you made me think about it, I
would have said that they are safe in CPython as long as all imports are
at the top of the file. And as long as the script isn't part of the
dependency loop. Thanks for the word "always" above; in trying to
refute it, I thought hard enough to realize you're right. And what's
better, realized it before hitting "SEND."
I would still say that the bugs caused in circular imports are
relatively easy to spot, while the ones caused by importing the script
can be quite painful to discover, if you aren't practiced at looking for
And my practice is to keep the two separate, only using a module as a
script when testing that module. The only time I've run into the
problem of the dual loading of the script was in a simple program I
copy-pasted from the wxPython demo code. That demo had a common module
(shell) which each individual demo imported. But if you ran that common
module as a script, it interactively let you choose which demo to import.
More information about the Python-list