Can't change variable from 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 the general module:

a=1

      

So, I start the python3 interpreter and:

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

      

Why is a

it still 1?

+3


source to share


1 answer


Herm, I was pretty sure this question should already have an answer, but I can't seem to find it. Ok then you go:

from shared import *

imports all (exported) fields from the module shared

into the current namespace. It does this by iterating over fields from the module and assigning variables to 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 it a

has the same meaning shared.a

as (as in import), there is no additional relationship between the two. If you reassign a

in your namespace, it will not affect the imported module.

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

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

      

+2


source







All Articles