I cannot modify global variables interactively in Spyder 4.0.0 with Python 3.8, Windows 10. There must have been a recent change because this was possible before.
I have the following example file:
x = 5
def IncreaseX():
global x
x += 1
print(x)
IncreaseX()
print(x)
- When I run it (with F5), I get the desired output:
In [1]: runfile('TestGlobals.py', wdir='D:')
5
6
- However, if I try to run the IncreaseX() function from the embedded Ipython console, it does not change the value of the global variable:
In [2]: x
Out[2]: 6
In [3]: IncreaseX()
In [4]: x
Out[4]: 6
- The same occurs if I select the last 3 rows of my example, and I run them (with F9):
In [5]: print(x)
...: IncreaseX()
...: print(x)
6
6
- The behaviour is different if I select all the rows of my example file and run them (with F9):
In [6]: x = 5
...: def IncreaseX():
...: global x
...: x += 1
...:
...: print(x)
...: IncreaseX()
...: print(x)
5
6
- After I do this, I can modify the value of the global variable. Repeating the exact same code of step 2., I obtain the desired outcome:
In [7]: x
Out[7]: 6
In [8]: IncreaseX()
In [9]: x
Out[9]: 7
Does anyone understand this behaviour? How can I restore the old behaviour (i.e., having step 2. to work directly as step 5.)?
I know that it is generally very bad to use global variables. However, I need to interactively modify some variables while I am controlling an experiment, hence a few correctly working global variables strongly simplify my workflow.
FOUND IT!!
Spyder/Preferences/Run/General settings/Run in console's namespace instead of an empty one
With this option turned on, the old behaviour of globals is restored.