-1

I was reading loading of modules from here.

There are two files in one of my directory mod_a.py and mod_b.py.

mod_a.py contains the following

print 'at top of mod_a'
import mod_b
print 'mod_a: defining x'
x = 5

while mod_b.py contains

print 'at top of mod_b'
import mod_a
print 'mod_b: defining y'
y = mod_a.x

on executing mod_a.py file I got the following output:

at top of mod_a
at top of mod_b
at top of mod_a
mod_a: defining x
mod_b: defining y
mod_a: defining x

However, while executing mod_b.py I got the following output:

at top of mod_b
at top of mod_a
at top of mod_b
mod_b: defining y
Traceback (most recent call last):
  File "D:\Python\Workspace\Problems-2\mod_b.py", line 2, in <module>
    import mod_a
  File "D:\Python\Workspace\Problems-2\mod_a.py", line 2, in <module>
    import mod_b
  File "D:\Python\Workspace\Problems-2\mod_b.py", line 4, in <module>
    y = mod_a.x
AttributeError: 'module' object has no attribute 'x'

Can anybody please explain this?

Soumendra
  • 1,518
  • 3
  • 27
  • 54

1 Answers1

1

The code fails at this one line

import mod_a

Because it will run though mod_a.py, which imports mod_b.py, where mod_a.x has not yet been defined.

For clarity, see this "trace" of mod_b

print 'at top of mod_b'
import mod_a # Importing a... 

    print 'at top of mod_a'
    import mod_b # Importing b...

        print 'at top of mod_b'
        import mod_a # ... will happen, but... 
        print 'mod_b: defining y'
        y = mod_a.x                 # error

    print 'mod_a: defining x'
    x = 5

print 'mod_b: defining y'
y = mod_a.x

Compared to mod_a

print 'at top of mod_a'
import mod_b # Importing b...

    print 'at top of mod_b'
    import mod_a # Importing a...

        print 'at top of mod_a'
        import mod_b # Recurses...
        print 'mod_a: defining x'
        x = 5                      # definition

    print 'mod_b: defining y'
    y = mod_a.x                    # it's defined... no error

print 'mod_a: defining x'
x = 5
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245