Anyone know of a library/script that can scan source directories and detect circular imports?
-
The Python interpreter seems to find all of mine pretty easily, but I'm guessing you are looking for some kind of static analysis tool..... – boatcoder Feb 17 '12 at 21:59
-
Yea, I know some can only be detected at runtime, but I think most of ours could be detected statically. – Nix Feb 17 '12 at 22:02
-
1Possible duplicate of [Detecting circular imports](http://stackoverflow.com/questions/2406007/detecting-circular-imports) – das-g Oct 27 '15 at 14:42
1 Answers
I do not know any tool outright, but there are a couple of ways I can think of right now that will get you this data.
Make the Interpreter Work for You
For every module you have, create a stub module that imports it, and then run this module with
$ python -v stub_module.py
This only works if you do not rely on sys.path hackery and your modules do not have dangerous side effects when imported (both very dubious features FWIW). You will get the transitive import closure, but detecting circular imports with this should be straightforward.
Use logilab.astng
With logilab.astng,it is easy to extract all direct imports of your modules (look for nodes of type logilab.astng.nodes.From
and logilab.astng.nodes.Import
). Once you have the list of direct imports of all modules, create the import graphs and look for cycles.
Again, this only works only if you do not use sys.path hacks.

- 83,780
- 21
- 91
- 98