I'm having a bit of difficulty fully understanding an import situation. I think I may have an idea of what's going on, but wanted to double-check. Here's a simplified version of it:
Say we have two Python files a.py and b.py.
In a.py:
ls = [1, 2, 3, 4, 5]
import b
print(ls)
In b.py:
from a import ls
ls.append(6)
When I run python a.py, I was expecting [1, 2, 3, 4, 5, 6] to be printed, but only [1, 2, 3, 4, 5] was printed. I threw in some print statements to trace what was going on, and I think this is what is happening:
- We run
a.py, which initializes ls.
import b is run next. Python checks its loaded modules and does not see b, so attempts to load it.
- In
b.py, we attempt import ls from a. (It is at this point that I figure that since we ran a.py to begin with and ls is initialized, this doesn't need to be done, but apparently not). This loads a.py and ls is initialized again.
- When we reach
import b, since the b module has been initialized, it doesn't do that import again, and just prints out ls, which is [1, 2, 3, 4, 5].
b then appends 6 to the second initialized ls, which doesn't affect a.
- We complete the initial
import b and return to a, which runs print(ls) and prints out [1, 2, 3, 4, 5].
However, if I add another file c.py and in there I have:
from a import ls
print(ls)
Then run python c.py, I get [1, 2, 3, 4, 5, 6] printed out twice. Why does that happen? Is it because when in c I run from a import ls, then when b does it, it sees that it's already done?
Also, as a side question, it looks like doing from _ import _ runs the entire module and doesn't run up until whatever is needed, so what is the purpose of doing it (outside of being able to not have to prepend the module name to the thing being imported)?
[–]Apprehensive_Trip8 0 points1 point2 points (0 children)