PEP 08 states:
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.<
Just to complete Moe's answer and the original question:
When we have to deal with circular dependences we can do some "tricks". Assuming we're working with modules a.py
and b.py
that contain x()
and b y()
, respectively. Then:
from imports
at the bottom of the module.from imports
inside the function or method that is actually requiring the import (this isn't always possible, as you may use it from several places).from imports
to be an import that looks like: import a
So, to conclude. If you aren't dealing with circular dependencies and doing some kind of trick to avoid them, then it's better to put all your imports at the top because of the reasons already explained in other answers to this question. And please, when doing this "tricks" include a comment, it's always welcome! :)