Newbie - circular import problem

Peter Otten __peter__ at web.de
Tue Feb 24 05:57:10 EST 2004


sw wrote:

> Can you give me some pointers on resolving this circular inclusion? I've
> got two classes, in two files:
> 
> --a.py--
> import b
> class ClassA:
>     def __init__(self):
>         print 'ClassA'
> 
> --b.py--
> import a

Your problem has nothing to do with circular references. Just change the
following to 

class ClassB(a.ClassA):

> class ClassB(ClassA):
>     def __init__(self):
>         print 'ClassB'
>  
> If I try to access ClassB (for example, by firing up python and importing
> b), I get the error:
> 
>   File "b.py", line 2, in ?
>     class ClassB(ClassA):
>     NameError: name 'ClassA' is not defined
> 
> Could someone explain what is going wrong here? I'm still getting up to
> speed with python, but, to me, this looks like the import of b is occuring
> before ClassA has been defined. Is that right? How can I correct this,
> apart from amalgamating the two into a single file?
> 
> Many thanks for any guidance.

Circular imports are often an indication of a design error. However, most of
the time python has no problem with two modules importing each other - as
long as you put references to the "other" module into function or method
bodies, i. e. into code that is not executed during import.

Peter





More information about the Python-list mailing list