3

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?

2

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or move one of the imports into the function definition.
@lazyr yes that's probably better still
3

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

1 Comment

recursive imports are perfectly possible

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.