Python files - import from each other
10,993
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
Related videos on Youtube
Author by
Chris Dutrow
Creator, EnterpriseJazz.com Owner, SharpDetail.com LinkedIn
Updated on June 27, 2022Comments
-
Chris Dutrow almost 2 years
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!
-
Fred Foo about 12 yearsWhile this kind of setup may make intuitive sense to you now, cyclic dependencies are considered bad software engineering practice.
-
Chris Dutrow about 12 years@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.
-
Fred Foo about 12 yearsIt'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.
-