Python Type Hints - How to Fix Circular Imports2021-05-13
Circular imports are always annoying when they arise in Python, and type hints make them more common.
Thankfully, there’s a trick to add circular imports for type hints without causing
Take these two files:
So far, so good.
We can run
models.py with no issues:
We run into a circular import if we add type hints in both files though.
models.py is not a problem as the only type to annotate is
BookController, which is already imported:
But when adding the type hint for
BookController.__init__(), we need to import
We’ve now added a circular import, as
controllers, which imports
Python now raises an
ImportError when we run the code:
So, how can we fix this?
The answer is to use the special
This is hardcoded to
False, but set to
True by type checkers like Mypy.
We can use it to make the
Now the code can run as before, and mypy can still check our types.
Note that we had to change the
Book type hint into a string.
This isn’t necessary if we add
from __future__ import annotations at the top of the file, which makes all annotations strings by default (see PEP 563).
__future__.annotations will become the default in Python 3.11).
May your runtime import graph remain a DAG,
🎉 My book Speed Up Your Django Tests is now up to date for Django 3.2. 🎉
Buy now on Gumroad
One summary email a week, no spam, I pinky promise.
Tags: mypy, python
© 2021 All rights reserved.