Dingsda
Dingsda

Reputation: 11

How to import dependent code from two modules?

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?

Upvotes: 0

Views: 46

Answers (1)

Matt Hall
Matt Hall

Reputation: 8142

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.

Upvotes: 1

Related Questions