5

I have a.py and b.py in the same directory. In a.py the code is

A = 'a1'

from b import B

print(B)

In b.py the code is

B = 'b1'

from a import A

print(A)

Now run a.py, the result is

b1
a1
b1

I don't understand. Will somebody explain it? Thanks!

Nishant
  • 20,354
  • 18
  • 69
  • 101
buttonreht
  • 51
  • 4

1 Answers1

1

This question seems to focus on order of execution. This is combined with a cyclic import.

The cyclic rules are stated in the linked answer, which I disagree is a duplicate:

  1. If a module has not been imported yet, execute it.
  2. Otherwise, just return it, regardless of whether its original import completed.

Now, order of execution:

  1. Run A
  2. A imports b, which does not exist, so is executed.
  3. B imports B, which does not exist (as an import) and is executed.
  4. A new A runs. This time when B is imported though, it already exists and returned. Luckily we already declared b1. Things would have gotten weird if we changed it after the import statement for example. Things would have broken if we declared it first after the import.
  5. A completes its run.
  6. B completes its run.
  7. The initial a completes its run.

That is the order of print statements you are getting. It's important to note execution is completely linear here.

kabanus
  • 24,623
  • 6
  • 41
  • 74
  • So, there is no single solution to this problem? I guess every language will get into this problem. Just curious :-) – Nishant Mar 29 '19 at 04:56
  • 1
    @Nishant Well, if you do no nothing you get stuck i an import loop, so as a language designer you either break the loop somehow, or disallow it completely. From a completely theoretical standpoint, it may be "right" to just let this run forever. – kabanus Mar 29 '19 at 04:58