Reputation: 6140
I'm getting used to Python's packaging mechanisms, and working to understand how to avoid circular imports. It seems difficult to develop a class based model with relationships between the classes without falling afoul of the circular dependency issue.
I'm interested in the case where there are many classes and relationships, but boiling it down to a simple form:
If I have two classes A and B with a many-to-many relationship between them, and methods A.getRelatedBs() and B.getRelatedAs(), what is the best way to package the code into modules and packages?
The solution of putting them in once module may work for this simple case, but doesn't work at scale, when there will be many more classes and relations.
What's the best practice here?
Upvotes: 1
Views: 289
Reputation: 1371
The only time I've run into falling afoul of the circular dependency issue was in a similar project with many smallish modules that all worked together. The answer was to not import any names from the imported modules into the current module namespace, but to use fully qualified references to the other modules.
So, instead of:
from foo import Foo,Foobar
from bar import Bar,Barbaz
class Zuul(Foo):
def do_something(self):
self.bar = Bar()
self.baz = Barbaz()
Do this instead:
import foo
import bar
class Zuul(foo.Foo):
def do_something(self):
self.bar = bar.Bar()
self.baz = bar.Barbaz()
Python tries to get around the circular import problem by only importing each module once. But, if you assign names from those imported modules into your module, then it has to try to obey an order, which it can't for circular imports. Using the fully-qualified names seems to sidestep the issue. It's more typing, but much safer.
Upvotes: 1