Vikas
Vikas

Reputation: 8948

What happens when a module is imported in python

I've following use case:

a.py:

import b
import c

c.fun()

b.py:

def fun():
  print 'b'

c.py:

def fun():
  b.fun()

python a.py doesn't work. It fails with NameError: global name 'b' is not defined.

My understanding of import in python was that a name is added in sys.modules. If that is the case then c.py should also see module b. But apparently that is not the case. So can anyone explain what exactly happens when a module is imported.

Thanks.

Upvotes: 1

Views: 1490

Answers (3)

Neel
Neel

Reputation: 21243

You have to add all modules which you want to use in that script.

Other way to pass that module in function argument and after that you can call that modules method.

The other way is to add it in _ _ builtins _ _ which is better explain in other post

Upvotes: 2

gecco
gecco

Reputation: 18850

The module c.py has to import b in order to get this working... When importing a module then it is added to the globals-dictionary that is available in the current script's scope only (use "globals()" to print its content)

Upvotes: 4

Vaughn Cato
Vaughn Cato

Reputation: 64308

You have added b and c to the a module, but but not to the c module. When you are inside a module, you can only see what has been added to it. b and c are added to sys.modules, but you haven't imported sys, and you aren't using sys.modules['b'].

Upvotes: 1

Related Questions