This is probably something obvious, but I'm confused.
I have a Python script test.py:
def t():
print(a)
a = 1
t()
When I run it, it prints 1, as expected:
runfile('C:/Users/Dave/data/Code/Python/lib/test.py', wdir='C:/Users/Dave/data/Code/Python/lib')
1
But when I then interactively type "a = 999" and run t() again, I expect it to print 999. But it prints 1. Why?
runfile('C:/Users/Dave/data/Code/Python/lib/test.py', wdir='C:/Users/Dave/data/Code/Python/lib')
1
a = 999
t()
1
FWIW, I'm running iPython inside Spyder.
Am I correct to think this is strange and not what I should expect?
Screenshot (added):

They are not the same variables:
def t():
print(id(a))
a = 1
t()
>>> runfile('C:/Users/Dave/data/Code/Python/lib/test.py', wdir='C:/Users/Dave/data/Code/Python/lib')
xx
>>> a = 999
>>> print(id(a))
yy
>>> t()
xx
This is the default behavior of runfile. It run the code in different namespaces.
def runfile(filename=None, args=None, wdir=None, namespace=None, post_mortem=False, current_namespace=False):
Change the current_namespace to True if you want to run it in the current namespace.
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