FAQ 1.7.3 : How can I have modules that mutually import each other

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sat Mar 19 15:15:41 EST 2005


MackS wrote:
> Hi
> 
> I'm new to Python, I've read the FAQ but still can't get the following
> simple example working:
> 
> # file main_mod.py:
> 
> global_string = 'abc'
> 
> def main():
> 
>     import auxiliary_mod
>     instance = auxiliary_mod.ClassA()
>     instance.fun()
>     return
> 
> main()
> 
> # file auxiliary_mod.py:
> 
> class ClassA:
> 
>   def fun(self):
> 
>     import main_mod
> 
>     print 'this is ClassA.fun() and global_string is ' +
> main_mod.global_string
> 
>     return
> 
> In words, the problem is: I've a main module which defines a global
> variable and instantiates a class defined in a second module, and a
> method of that class needs to access the global variable defined in the
> main module.

[...]
> How can I get this simple example to work?

You suffer from a circular dependency issue. The general solution in
this case is to factor out code into a third module. In your case,
consider putting global_string or main() in a third module that you can
import from auxiliary_mod.

Reinhold



More information about the Python-list mailing list