module Cyclic references

Martin v. Loewis martin at v.loewis.de
Sun Jan 6 15:25:57 EST 2002


Karthik Gurumurthy <karthikg at aztec.soft.net> writes:

> test.py -- > from movie import Movie, Rental 
> movie.py --> has 2 classes Movie , Rental 
> 		#needs price and hence does 
> 		import price
> price.py --> needs Movie 
> 		#does
> 		from movie import Movie, Rental
> cust.py  --> has one class Customer
> 
> so this is the sequence.
> 
> test-->loads movie --> load price which in turn needs movie.
> 
> Can someone tell me what's wrong here??

Your code is wrong. When "import move" is executed the first time, a
new module is added to sys.modules, and this module is subsequently
filled. This process will eventually provide movie.Movie, but before
it does so, it performs "import price", which starts off with
"from movie import Movie, Rental". Since there is already a module
in sys.module["movie"], Python looks into that module, and finds
that there is nothing name Movie in there.

The solution is to delay some of the imports. E.g. if movie.py uses
price only inside functions, like

def something():
  price.compute_something()

then you can delay import of price until you actually need it:

def something()
  import price
  price.compute_something()

Then, importing move will not import price. Only calling
movie.something() will do so; when the call is executed, movie.Movie
will have been defined, so price can import it.

HTH,
Martin



More information about the Python-list mailing list