Circular import errors

Tags: django

In rare cases, you can import a file that imports the file you’re importing from. This might sound a bit recursive, and it is. In Python it is called a circular import error.

The best way to recognize a circular import that goes wrong is to look at your results. You will get an ImportError message from Django, like cannot import some_view from your_project.views. When you look in your_project/ you see that some_view really exists in that very same file. Huh? That wasn’t expected.

This huh??? is exactly what a circular import looks like. Something that exists (you checked it five times at least) doesn’t seem to exist. A computer doesn’t lie, but you start to wonder.

The problem is, Python cannot complete the import, so it complains about the point where it goes wrong, even though the actual error is the circular import loop as a whole.

The solution is to break the loop somewhere. Perhaps the thing you want to import is best placed somewhere else? Most often, a circular import error indicates an organization problem in your code. logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):