Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Spyder not pick up a global variable? [duplicate]

Tags:

python

spyder

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):

enter image description here

like image 704
nerdfever.com Avatar asked Dec 13 '25 02:12

nerdfever.com


1 Answers

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.

like image 148
napuzba Avatar answered Dec 14 '25 15:12

napuzba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!