Denis Dubinin
Denis Dubinin

Reputation: 257

Python import problem

I have some problem, that look like some spaces in my understanding how python does import modules. For example i have module which called somemodule with two submodules a.py and b.py.


content of a.py:

from somemodule.b import b

def a():
    b()
    print "I'am A"

content b.py

from somemodule.a import a

def b():
    a()
    print "I'am B"


Now if i would like to invoke any module i get ImportError:

ImportError: cannot import name b

Whats wrong with me?

Upvotes: 3

Views: 481

Answers (2)

David Heffernan
David Heffernan

Reputation: 613441

You've got a circular reference. You import module a which then imports module b. But module b imports function a from module a. But at the time it tries to do so, a has not been defined. Remember that Python import effectively executes the module.

The solution would appear to be to move the function definitions so that they appear before the imports.

Or, as @lazyr suggests, move the import statements to be inside the functions so that the import happens when the function is called, not at module import time.

Upvotes: 6

immortal
immortal

Reputation: 3188

You have recursive importing here: a imports b which imports a which imports b which .....

In addition, please make sure you have an __init__.py file in the folder somemodule

Upvotes: 3

Related Questions