[Python-ideas] ImportError raised for a circular import

Chris Angelico rosuav at gmail.com
Tue Jun 13 16:43:16 EDT 2017


On Wed, Jun 14, 2017 at 6:35 AM, Barry <barry at barrys-emacs.org> wrote:
> On 13 Jun 2017, at 20:13, Antoine Rozo <antoine.rozo at gmail.com> wrote:
>
> But circular imports are sometimes needed in modules.
> For example when you have two classes in two different modules that
> reference each other in their methods (and because you can't pre-declare
> classes like in C++).
>
>
> Really? It has always been a strong sign of a design bug in all the cases I
> have ever seen.
> The example you suggest always fails when I accidentally write it.
>
> Pylint will certainly shout loud that this case is an error.
>

Depends on your definition of "circular". Consider this:

# __init__.py
from flask import Flask
app = Flask(__name__)
from . import views

# views.py
from . import app
@app.route("/")
def home():
    ...


Technically this is circular. During the loading of __init__, views
will be imported, which then imports something from __init__. But it's
perfectly well-defined (there's no way that views will ever be the
first one imported, per the rules of packages) and it makes good
sense. An error on circular imports, or even a warning, would be very
annoying here.

ChrisA


More information about the Python-ideas mailing list