Can someone explain this #Python import behavior
-
@treyhunner Tagging you on this since it might qualify as a #Pythonoddity
@bmispelon This is absolutely a Python oddity. I guessed incorrectly. I understand why I guessed incorrectly now that I look back at the code... I'm not sure any Python oddity has stress testeded my mental model of Python's import system as much as this one.
-
Can someone explain this #Python import behavior?
I'm in a directory with 3 files:a.py contains `A = 1; from b import *`
b.py contains `from a import *; A += 1`
c.py contains `from a import A; print(A)`Can you guess and explain what happens when you run `python c.py`?
$ echo 'A = 1; print("A1"); from b import A; print("A2")' > a.py
$ echo 'print("B1"); from a import A; print("B2"); A += 1' > b.py
$ python -c 'from a import A; print(A)'
A1
B1
B2
A2
2I added several prints so that it's possible to tell what order code is executed, and changed
import *toimport Abecause I think it improves clarity without changing the behavior.- The main program runs
- It encounters an import of
aso it starts executing the content ofa.pyin a newly createdamodule - It sets
A.a=1via the assignment statement ina.py - It encounters an import of
bso it starts executing the content ofb.pyin a newly createdbmodule - It sets
b.A=1byfrom...import - It adds 1 to
b.Aso thatb.Ais now equal to 2 - Execution reaches the end of
b.pyso it returns toa.py a.pysetsa.Ato 2 byfrom...import- Execution reaches the end of
a.pyso it returns to the main program. - The main program sets
__main__.Ato 2 byfrom ...import - The value of
Ais printed (2)
-
Can someone explain this #Python import behavior?
I'm in a directory with 3 files:a.py contains `A = 1; from b import *`
b.py contains `from a import *; A += 1`
c.py contains `from a import A; print(A)`Can you guess and explain what happens when you run `python c.py`?
@bmispelon My reasoning was the last option, 2, and then I saw what @pawamoy wrote, which makes perfect sense to me
-
R ActivityRelay shared this topic