two newbie questions "cyclic class dependencies" and "date from string"

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue May 13 04:17:59 EDT 2003


Daan Hoogland <hoogland at astron.nl> wrote in
news:mailman.1052808978.12235.python-list at python.org: 

> Now I want to have these lines in three files. so adding some
> import statements seemed the obvious. It failed for equally obvious
> reasons: 
> 
> ImportError: cannot import name A                                     
>          
> 
><file name="A.py">
> from B import B;
>  
> class A:
>   def __init__(self):
>     self.b = B();
></file>
> 
><file name="B.py">
> from A import A;
>  

This is one of many reasons why you should avoid using the 'from module 
import name' form of the import statement. If you simply import the module 
then the problem (almost) goes away:

--- A.py ---
import B

class A:
    def __init__(self):
        self.b = B.B()

--- B.py ---
import A

class B:
  def delegate(self, a):
    a = A.A();

--------------
Say you import A first, then the import B starts executing B.py, that calls 
import A which succeeds immediately, even though the class A.A doesn't yet 
exist. class B gets defined and the original import of B can complete 
letting class A get defined.

If you imported B first then the code in A.py gets executed by the import A 
after which the code in B.py can complete. Either way, so long as you don't 
try to use the classes until all the imports have completed it should all 
hang together.

Of course, if you actually try to instantiate class A in A.py it will still 
break if B was imported first.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list