Code speaks better:
import numpy as np
a = np.ones(shape=(4, 2))
def func():
for i in a:
print(i)
Run:
In[3]: func()
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
In[4]: a = np.zeros(shape=(4, 2))
In[5]: func()
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
Notice that I changed (a). But, when I run the function again, no changes!!
Details: latest version of Pycharm. Configs > Execution: Run with Python console.
I don't use Pycharm. But I think I know why.
When you Run with Python console, it should have from your-source-file import *
in background.
When you rebind a
to new object in console, the func will still use the a
in your-source-file, not the a
in console.
You can have a try by explicitly from your-source-file import *
and take the rest of actions to verify it. I have checked it on my computer by myself.
If you want understand why, you can read 4. Execution model: resolution-of-names — Python 3.7.3 documentation, and make sure you understand this:
When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.
My try in ipython:
In [2]: from test import *
In [3]: func()
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
In [4]: a = np.zeros(shape=(4, 2))
In [5]: func()
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
In [6]: def func():
...: for i in a:
...: print(i)
...:
In [7]: func()
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
and
In [1]: from auto_audit_backend.test_np import *
In [2]: func()
[1. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
In [3]: a[0][0] = 666
In [4]: func()
[666. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
In [5]: a = np.zeros(shape=(4, 2))
In [6]: func()
[666. 1.]
[1. 1.]
[1. 1.]
[1. 1.]
with your code in test.py file.