Apparent "double imports"

HoneyMonster someone at someplace.invalid
Thu Feb 9 16:57:09 EST 2012


On Thu, 09 Feb 2012 15:05:52 -0500, Dave Angel wrote:

> On 02/09/2012 02:40 PM, HoneyMonster wrote:
>> On Thu, 09 Feb 2012 12:02:03 -0700, Ian Kelly wrote:
>>
>>> On Thu, Feb 9, 2012 at 11:53 AM, HoneyMonster
>>> <someone at someplace.invalid>  wrote:
>>>> One issue I have run into, which may or may not be a problem: I am
>>>> finding that modules in the in-house "library" package sometimes have
>>>> to import modules like sys and os, which are also imported by the
>>>> "calling"
>>>> module. Is this a problem or an overhead, or does it just result in
>>>> two names for the same object?
>>> Two names for the same object.  When a module is imported, the module
>>> object is stored in the sys.modules dict.  Further imports of the same
>>> module just return the same module object from sys.modules.
>> Excellent! It seems it is not a problem at all, then. Thank you.
> Just to add a little subtlety, there is a problem with mutually
> recursive imports.  If module aaa imports module bbb, and modole bbb
> imports aaa, there can be some problems.  Most can be avoided by putting
> the imports right at the beginning of each file, so no work has been
> done before doing the imports.  Then by the time some code tries to use
> them, they're all resolved.  One exception is if you try to import the
> file that is your script file.  This one is made into a module by the
> special name of __main__, and if you import it using the original name,
> you'll have two copies around.  That can lead to some very interesting
> anomalies.
> 
> Better is to make sure no loops exist in the importing tree, which is a
> desirable structuring goal anyway.  When two modules need each other,
> try to either move the common stuff to a 3rd module they each import, or
> do something with callbacks or other mechanism that reflects what's
> really going on.
> 
> Of cours that last paragraph is strictly my own opinion.

Thanks, Dave. I'm sure I won't have a problem with circular imports. The 
structure I have in mind is:

A package (say ihlib) consisting of in-house "library" routines for local 
use. The directory above ihlib will be added to PYTHONPATH, so that 
imports can find ihlib.

"Top level" modules will import ihlib.blah as necessary in order to avoid 
code duplication amongst them.



More information about the Python-list mailing list