0

I have a problem with using python module inside another one. The use case is as follows:

Consider the following scenario. The error was commented accordingly.

In file A.py:

import B ... ... 

In file B.py:

import C import A c_func = C.func1() # works perfectly a_func = A.func2() # Error: 'module' object has no attribute 'func2' ... ... 

In file C.py:

... ... 

Any ideas? Thanks in advance.

1
  • 1
    show us the code for A.py which defines func2... Commented Jan 23, 2014 at 1:24

1 Answer 1

6

This is a circular import. In general, they don't work.

See How can I have modules that mutually import each other? in the FAQ for an explanation, and some different ways to solve it. There's also a Circular Imports section on Fredrik Lundh's effbot site. But briefly:

  • A starts executing.
  • A reaches the import B.
  • B starts executing.
  • B reaches the import A. Since A already exists, this does nothing. Whatever code in A wasn't run yet—like the definition for A.func2—still hasn't run.
  • B tries to use A.func2, which hasn't been defined yet, so you get an error.

(Even more briefly, but less accurately: B depends on A, which depends on B, which means B can't run until B runs. This may help you get an intuitive understanding of the problem, which may help you understand the more complete/accurate explanation above.)

What you probably want to do is move the code in A that B needs into a separate module, which both A and B can import, which won't need to import either A or B. That's not the only possible solution (see the FAQ entry for two other ideas), but when it's possible to do this cleanly, it's hard to beat it. (Without actual code, it's hard to give a more specific answer than that.)

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

2 Comments

But it can work so long as the function is called after the import finishes, right?
@mhlester: Yes. One of the possible solutions suggested in the FAQ is to move all of B's top-level code into a function, and have A call that function only after it's defined whatever that function needs. And another possible solution is to move the import B farther down in A until after func2 has been defined.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.