17

I would like for two of my python files to import some methods from each other. This seems to be giving me import errors.

Example:

file_A.py:

from file_B import do_B_stuff

file_B.py:

from file_A import do_A_stuff

The reason I am trying to do this is because I would like to organize my project in the way it intuitively makes sense to me as opposed to organizing it with respect to what makes sense to the compiler.

Is there a way to do this?

Thanks!

Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
  • 3
    While this kind of setup may make intuitive sense to you now, cyclic dependencies are considered bad software engineering practice. – Fred Foo Mar 09 '12 at 23:47
  • 2
    @larsmans - Yeah, I know. I'm not sure I agree though. I think this is left over from the days of C++ where you had to be closer to the compiler. I think now it would be better if things are easier on the programmer so that we can get more done with our time instead of having to worry about things like cyclic dependencies. I remember having to worry about memory leaks. Now I hardly ever even hear the term mentioned. There may be other good arguments against cyclic dependencies that I haven't heard of though. – Chris Dutrow Mar 09 '12 at 23:50
  • 3
    It's a matter of coupling and re-usability. Mutually dependent modules (a) are always strongly coupled, which can be bad or just unavoidable, and (b) cannot be reused without each other, so they could just as well be a single module. – Fred Foo Mar 10 '12 at 00:45
  • @larsmans - Yeah, thats actually a really good point. More code re-use means I get more done in less time. I actually moved some of my code around in response to your point. – Chris Dutrow Mar 10 '12 at 03:28

1 Answers1

35

Don't use the names within the other module directly.

file_A.py

import file_B

def something():
    file_B.do_B_stuff

file_B.py

import file_A

def something():
    file_A.do_A_stuff
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358