SJ Porter
Jul 27, 2022

--

There is no legitimate reason to place import statements anywhere other than the very top of Python files. Circular dependencies are a de-facto code smell indicating that your code needs refactoring.

Here is a design pattern for working around difficult dependencies:

https://refactoring.guru/design-patterns/mediator

Here is the corresponding Python example:

https://refactoring.guru/design-patterns/mediator/python/example

The only semi-convincing argument I've seen for placing import statements anywhere other than the top of a Python file would be to place an import inside of a function to squeeze out a tiny amount of performance in case some specific function were rarely called, but unless it's absolutely needed I would never recommend it.

--

--

SJ Porter

Data/cloud engineer, musician, and gamer. Editor for Low Code for Advanced Data Science, writer for TDS and The Startup.