简体   繁体   中英

Can't change a variable from an imported module

I have a function declared in module1 :

from shared import *
def foo():
  global a
  print('in :',a)
  a=0
  print('out:',a)

And shared module:

a=1

So I'm launching python3 interpreter and:

>>> from module1 import *
>>> a
1
>>> foo()
in : 1
out: 0
>>> a
1

Why a is still 1?

Hrm, I was pretty convinced that there should already be an answer to that question floating around, but I seem unable to find it. Well then, here you go:

from shared import * imports all (exported) fields from the shared module into the current namespace. It does so, by iterating through the fields from the module and assigning the variables into the current namespace with the same names as in the module.

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> from shared import *
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']

Note that our current namespace now contains a variable named a .

While that a has the same value as shared.a (as of the import), there's no further connection between the two. If you re-assign a in your namespace, this has no effect on the imported module.

In fact, if you pull in the name again from the module, you will overwrite your local value:

>>> a = 5
>>> a
5
>>> from shared import a
>>> a
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM