[Tutor] Random Number Question

Peter Otten __peter__ at web.de
Thu Nov 25 22:14:23 CET 2010

Alan Gauld wrote:

>>>> import random
> It tries to import itself, which then tries to import itself,
> which then..... infinite loop time...

I think it's more like

- look up module random in sys.modules
- module random not found in sys.modules; locate the file random.py
- file random.py found, create a new empty module object and put it into
- execute code loaded from random.py, encounter 'import random', look up
  random in sys.modules
- module random found in sys.modules, bind it to the name 'random' in itself
- continue execution of random.py code. This will succeed unless you try to
  access random.some_name for a name not already defined.

In short: you are more likely to get an AttributeError than infinite 

$ cat module.py
print "importing", __name__
import module
print module.yadda
yadda = 42
$ python -c'import module'
importing module
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "module.py", line 3, in <module>
    print module.yadda
AttributeError: 'module' object has no attribute 'yadda'

$ cat module2.py
print "importing", __name__
yadda = 42
import module2
print module2.yadda
$ python -c'import module2'
importing module2

While the latter "works" as in "runs without error" it still isn't a good 

By the way, you can generalise the above to arbitrary circular imports where 
module a imports b which imports c which imports ... which imports z which 
imports a.


More information about the Tutor mailing list