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!
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:
Now, order of execution:
A
A
imports b
, which does not exist, so is executed. B
imports B
, which does not exist (as an import) and is executed. 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. A
completes its run.B
completes its run.That is the order of print statements you are getting. It's important to note execution is completely linear here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With