How to avoid mutual imports

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Fri Apr 12 19:40:01 EDT 2002


Tom Good <Tom_Good1 at excite.com> wrote:
>huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) wrote in message news:<slrnabeai4.lrg.huaiyu at gauss.almadan.ibm.com>...
>> I need advice on how to handle the following situation:
>> 
>> utils1.py:
>>     a
>> 	b
>>     c
>>     if __name__ == '__main__':
>> 	   from interface import data_initialization  # circular
>[snip]
>
>From your description I'm not sure what the problem is.  That import
>is not  actually circular because when utils1.py is imported from
>another module, ( _name__ == '__main__' )  will be false, so the
>import statement after it will not be executed.
>
>Am I missing something?

No, I was missing something.  I over-simplified the problem.  In fact there
are other things that depend on this and they were not in the __main__
condition originally.

But in any case, all the circular imports are now removed by either putting
them into function definitions or under the __main__ condition.  I had the
habit of putting all imports at the beginning of a module so they are
obvious.  Now they are generally either at the beginning of the module or
the beginning of __main__, or occasionally in some functions.

Huaiyu



More information about the Python-list mailing list