Imagine a situation, in which you have two files say p1.py and p2.py.
p1.py:
a=5
p2.py:
from p1 import *
print(a) # NameError: name 'a' is not defined
print(p1.a) # NameError: name 'p1' is not defined
The first print statement is understandable. I am boggling over second print statement.
from p1 import *
should import everything inside p1.py, so why am I not able to access p1.a variable. This is not the end, interesting part starts from here. Now consider the below-given modification:
import p1
print(p1.a) # prints a = 5
So what am I missing here? In this answer from @ThiefMaster he says that
from foo import *
importsa
to the local scope. When assigning a value toa
, it is replaced with the new value - but the originalfoo.a
variable is not touched.So unless you
import foo
and modifyfoo.a
, both calls will return the same value.
So I modified p1.a but why isn't it working?