caught in the import web again

Chris Angelico rosuav at gmail.com
Sun Nov 16 10:20:56 CET 2014


On Sun, Nov 16, 2014 at 7:53 PM, Charles T. Smith
<cts.private.yahoo at gmail.com> wrote:
> Yes, we're talking about recursive imports here.  It's a complex, object-
> oriented system with big classes and little classes that are strongly
> interrelated.  I can get the imports configured properly so everything
> works but if I make a little change to the code, then suddenly all my
> imports are broken and I must painstakingly go through the whole
> structure, reorganizing them.

So reorganize *once*, such that there are no recursive imports.
Reorganize your code so things don't actually import one another.
Remember, you can pass an instance of some class to an instance of
another class that has no knowledge of the first class - like this:

# file1.py

class Foo:
    def some_method(self, some_obj):
        some_obj.some_other_method()

# file2.py

class Bar:
    def some_other_method(self):
        return 42

# main.py

import file1, file2

f=file1.Foo()
b=file2.Bar()
f.some_method(b)


This works just fine, and neither file1 nor file2 needs to import the
other. Recursive imports are almost never necessary.

ChrisA



More information about the Python-list mailing list