[Tutor] module Cyclic references

Martin v. Loewis martin at v.loewis.de
Sun Jan 6 21:31:13 CET 2002


"Andy W" <toodles at yifan.net> writes:

> > This sequence works just fine!
> > >>> import price
> > >>> import movie
> > >>> import cust
> > >>> import test
> 
> Umm this sounds too simple to be true, but is there a typo or something?

No, that is well possible. Consider the modules

#price

from movie import Movie

#movie
import price

class Movie:
  def __init__(self):
    self.price = price.DEFAULT_PRICE

Then, 'import price' will put price into sys.modules, and start
executing price.py. 

That does 'from movie import Movie', so movie is added to sys.modules,
and execution of movie.py starts. That does 'import price', so it gets
the existing module from sys.modules (which is still incomplete). It
continues defining Movie, then movie.py is done.

Next, the "from ..." looks for movie.Movie, finds it, and adds it to
price.__dict__, so 'import price' is also done.

The next 'import movie' is mostly a no-op: movie is retrieved from
sys.modules, and added to __main__.__dict__.

HTH,
Martin




More information about the Python-list mailing list