1

In Python 3.8.10, consider test.py:

A = 3

def foo():
   global A, B
   A = A*10
   B = 5
   print((A,B))

If I import test.py, no problem:

import test
test.foo() => (30, 5)
test.A => 30
test.B => 5

But if I import *, which variables A and B are referred to as global?:

from test import *
A => 3
foo() => (30, 5)  (it read the existing value of A)
A => 3         (apparently a different A was assigned?)
B => undefined (apparently set a different B?)

Now, if I reimport *, the variables become visible:

(continuation of previous commands)
from test import *
A => 30    (not 3??)
B => 5     (?? B isn't even mentioned at the top level of test)

What is going on? Where do variables A and B 'live'?

  • When you do `from test import *` it assigns all the global variables in `test` to *new global variables in the module doing the importing*. Python "global" variables are actually "module-level" global - i.e. not truly global across all namespace. So think of your starred import as `import test; A = test.A, foo = test.foo; del test` – juanpa.arrivillaga Jun 10 '21 at 19:52
  • 1
    Note, starred imports are highly discouraged... but this would also apply to `from test import some_name`. – juanpa.arrivillaga Jun 10 '21 at 19:52
  • The problem is not actually due to imports. ``A = 5``, ``B = A``, ``A = 10``, ``print(B)`` is exactly the same "issue". ``import`` is just a somewhat non-obvious way of doing a name assignment. – MisterMiyagi Jun 10 '21 at 19:59
  • 1
    @MisterMiyagi yes, but I suspect the OP understands that, however, doesn't understand the nature of globals in Python, which don't behave like globals in, say, C – juanpa.arrivillaga Jun 10 '21 at 20:03
  • Thanks for the comments. But I still don't understand where A and B "live" -- what is their fully qualified name? If I do ``from X import *``, the X module is not defined in my REPL environment. So how do I name the global B? And why didn't A=A*10 change the value of A? – Stavros Macrakis Jun 11 '21 at 20:11

0 Answers0