0

I have the following situation:

The first file, named a.py contains:

var = 2

The second file, named b.py contains:

def prnt():
  print(var)

The third file, named c.py contains:

from a import *
from b import *

prnt()       # NameError: name 'var' is not defined

and raises the given error. I always thought that the import statement basically "copies" code into the calling namespace, so it should be the same as:

var = 2

def prnt():
  print(var)

prnt()

but apparently this is not the case. What am I missing?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Dingsda
  • 11
  • 3

1 Answers1

1

When you import a module, the code in that module is run by the interpreter (see this for example; add a print statement in there and you'll see it in action). Therefore you can't use variables etc without defining them or importing them.

In b.py do this at the top:

from a import var

Then, unless you need var in c.py, you won't need to import anything from a.py in c.py.

I know this is fake code, but avoid using globals in your functions.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
  • thank you for the hint, but now I'm even more confused about how the interpreter works under the hood (see my edited question) – Dingsda Jul 29 '22 at 11:19
  • You aren't importing the module's code as text into the current program, you're running the module's code in the current runtime. – Matt Hall Jul 29 '22 at 18:02