Python Import Dependency
<p>I know this question has been asked many times, but even after I tried many SO suggestions, I still cannot get it right. So, posting here for your help.</p>

<p>I'm building a simple web server with Flask-Restful and Flask-SqlAlchemy. Basically, I think I'm getting an error because of a circular import. My <strong>Widget</strong> class is dependent on <strong>Visualization</strong> class and vice versa...</p>

<p>The error message:</p>

<pre><code>Traceback (most recent call last):
  File "server.py", line 1, in &lt;module&gt;
    from app.resources.dashboard import Dashboards, Dashboard
  File "app/__init__.py", line 14, in &lt;module&gt;
    from models import *
  File "app/models/__init__.py", line 1, in &lt;module&gt;
    import visualization.Visualization as VisualizationModel
  File "app/models/visualization.py", line 3, in &lt;module&gt;
    from app.models import WidgetModel
ImportError: cannot import name WidgetModel
</code></pre>

<p>Directory structure:</p>

<pre><code>âââ app
âÂ Â  âââ app/__init__.py
âÂ Â  âââ app/models
âÂ Â  âÂ Â  âââ app/models/__init__.py
âÂ Â  âÂ Â  âââ app/models/dashboard.py
âÂ Â  âÂ Â  âââ app/models/visualization.py
âÂ Â  âÂ Â  âââ app/models/widget.py
âÂ Â  âââ app/resources
âÂ Â      âââ app/resources/__init__.py
âÂ Â      âââ app/resources/dashboard.py
âÂ Â      âââ app/resources/visualization.py
âÂ Â      âââ app/resources/widget.py
âââ server.py
</code></pre>

<p>app/models/__init__.py:</p>

<pre><code>from visualization import Visualization as VisualizationModel
from widget import Widget as WidgetModel
from dashboard import Dashboard as DashboardModel
</code></pre>

<p>app/models/visualization.py</p>

<pre><code>from sqlalchemy import types
from app import db
from app.models import WidgetModel


class Visualization(db.Model):
    __tablename__ = 'visualizations'
    ...
    widget = db.relationship(WidgetModel, cascade="all, delete-orphan", backref="visualizations")
</code></pre>

<p>app/models/widget.py</p>

<pre><code>from app import db
from app.models import VisualizationModel


class Widget(db.Model):
    __tablename__ = 'widgets'
    ...
    visualization = db.relationship(VisualizationModel, backref="widgets")
</code></pre>

<p>I tried changing my import to <code>from app import models</code>, and then use <code>models.WidgetModel</code> / <code>models.VisualizationModel</code>. However, still getting an ImportError.</p>

<p>Error message:</p>

<pre><code>Traceback (most recent call last):
  File "server.py", line 1, in &lt;module&gt;
    from app.resources.dashboard import Dashboards, Dashboard
  File "app/__init__.py", line 14, in &lt;module&gt;
    from models import *
  File "app/models/__init__.py", line 1, in &lt;module&gt;
    from visualization import Visualization as VisualizationModel
  File "app/models/visualization.py", line 3, in &lt;module&gt;
    from app import models
ImportError: cannot import name models
</code></pre>

<p>I'm very new to Python. I would be grateful if you can help me out. Thanks for you help in advance!</p>

<hr>

<p><strong>Update</strong> </p>

<p>The intention of defining bi-directional relationship is that I want to attach the <strong>Visualization</strong> object in the fields of <strong>Widget</strong> object upon a return of GET request on a widget record.</p>

<p>In the app/resources/widget.py I have:</p>

<pre><code>...
from flask_restful import fields, Resource, marshal_with, abort
from app.models import WidgetModel
import visualization as visualizationResource


widget_fields = {
    'id': fields.String,
    ...
    'dashboard_id': fields.String,
    'visualization_id': fields.String,
    'visualization': fields.Nested(visualizationResource.visualization_fields)
}

class Widgets(Resource):

    @marshal_with(widget_fields)
    def get(self):
        return WidgetModel.query.all()
</code></pre>

<p>I also want to have the <code>cascade delete</code> feature because if a <strong>widget</strong> cannot exist without a <strong>visualization</strong>.</p>

<p>Change your import to look like this:</p>

<pre><code>from app import models
</code></pre>

<p>And then use <code>models.WidgetModel</code> / <code>models.VisualizationModel</code> instead.</p>

<p>The problem is that you're creating a circular import dependency where both files require the other file to already have been processed before they can be processed. By moving to importing the entire <code>models</code> namespace rather than trying to import a specific model name at import time, you avoid making the import dependent on a fully processed file. That way, both files can be fully processed before either tries to invoke an object created by the other.</p>

<p>It may still not work in this case however because you're trying to immediately use the import in part of the class definition, which is evaluated at processing time.</p>

<hr>

<p>It looks like you're trying to define bi-directional relationships - the <code>backref</code> parameter is intended to do this automatically without you having to specify the relationship on both models. (<code>backref</code> tells sqlalchemy what field to add to the <em>other</em> model to point back to the original models that link to it). So you may not need to be doing both of these imports in the first place.</p>

<p>For instance, the fact that <code>Visualization.widget</code> is defined with <code>backref="visualizations"</code> means that <code>Widget.visualizations</code> will <em>already exist</em> - you don't need to explicitly create it.</p>

<p>If what you specifically need is many:many relationships, then chances are what you actually want to do is <a href="http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many" rel="nofollow">define an association table for the many-to-many relationship</a>.</p>

python flask-sqlalchemy flask-restful