Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand import in python? [duplicate]

Tags:

python

import

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!

like image 820
buttonreht Avatar asked Nov 07 '22 19:11

buttonreht


1 Answers

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.

like image 75
kabanus Avatar answered Nov 14 '22 21:11

kabanus