Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #49860

Re: Coping with cyclic imports

From Dave Angel <davea@davea.name>
Subject Re: Coping with cyclic imports
Date 2013-07-04 09:33 -0400
References <87bq4knmax.fsf@physik.rwth-aachen.de> <bc7429c5-7771-4529-9554-f494f393cbb6@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.4228.1372944826.3114.python-list@python.org> (permalink)

Show all headers | View raw


On 07/04/2013 08:48 AM, kanchan.n.mahajan@gmail.com wrote:
> On Tuesday, April 8, 2008 10:06:46 PM UTC+2, Torsten Bronger wrote:
>> Hallöchen!
>>
>> I have a rather fat module that represents a document parser --
>> inline elements, block elements, and the like.  Now I want to split
>> it into many modules to make everything more manageable.
>>
>> But at the moment I don't see how to avoid cyclic imports:  A
>> document element A, which is represented my module parser.A, may
>> contain the element B, as defined in parser.B.  And vice versa.  So
>> both modules must import each other, as far as I can see.
>>
>> I know that cyclic imports work in Python under certain
>> circumstances.  Can anyone refer me to a page which explains *when*
>> this works?  Because at least once, the imported module was not
>> "finished" and thus largely unusual.
>>
>> Thank you!
>>
>> Tschö,
>> Torsten.
>>
>
>
> If you do "import foo" inside bar and "import bar" inside foo, it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.
>
> The problem is when instead you do "from foo import abc" and "from bar import xyz". Because now each module requires the other module to already be compiled (so that the name we are importing exists) before it can be compiled.
>
> from
> http://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python
>

That's a nice looking oversimplification.  But it's not true if 
top-level code in the second module to be imported tries to use symbols 
defined in the first module.  And it's definitely bad practice, with 
weird bugs if either one of these files is the main script being loaded.


-- 
DaveA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Coping with cyclic imports kanchan.n.mahajan@gmail.com - 2013-07-04 05:48 -0700
  Re: Coping with cyclic imports Dave Angel <davea@davea.name> - 2013-07-04 09:33 -0400
  Re: Coping with cyclic imports Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-07-04 16:03 +0100
    Re: Coping with cyclic imports kanchan.n.mahajan@gmail.com - 2013-07-04 08:11 -0700
      Re: Coping with cyclic imports Dave Angel <davea@davea.name> - 2013-07-04 18:12 -0400

csiph-web