1

While I know how to work around/with the usual circular imports in Python, I really would like to ensure our project never gets into this problem/smell in the first place. So I am searching for tools/automation, which detects circular imports.

I am aware that some of our dependencies have circular imports - thus it would also need to only detect on our code and ignore dependency code.

My idea is to hook this into CI and preferably Visual Studio Code.

abergmeier
  • 13,224
  • 13
  • 64
  • 120
  • It's just gonna blow up on imports? :P I'm not sure how nefarious such an issue can be because it just explodes as soon as you run the code – roganjosh Apr 03 '21 at 19:56
  • Circular imports can work in Python and must not necessarily blow up. Still - I want a mechanism to prevent them because I think they are a code smell at best. – abergmeier Apr 03 '21 at 19:58
  • You could obviously have weird things if you import into a function scope and there's a conflict there. Otherwise, I'm not sure what you'll get beyond the obvious failure. It's just gonna be an error in a different format? – roganjosh Apr 03 '21 at 19:59
  • mm, I can't off-hand think of how I've had a circular import waiting to blow up. Do you have an example in mind? – roganjosh Apr 03 '21 at 20:01
  • 1
    What about https://github.com/bndr/pycycle? – Daria Pydorenko Apr 03 '21 at 20:02
  • @DariaPydorenko Sounds interesting. Will give it a try. – abergmeier Apr 03 '21 at 20:07
  • I recommend also looking at a linter that enforces layering, e.g. https://import-linter.readthedocs.io/en/stable/contract_types.html#layers. Blocking cycles on its own is problematic because by the time a chain of imports comes back around on itself to form a cycle, it may not be obvious how to fix it. Layer checking helps you avoid cycles before they start. – Samwise Apr 03 '21 at 20:13
  • 5
    Does this answer your question? [Detecting circular imports](https://stackoverflow.com/questions/2406007/detecting-circular-imports) – GTS Apr 03 '21 at 20:21
  • @GTS From the phrasing of the question I am looking for something working to get the job done. The other answers seem more like a start for implementing a tool. So IMO not what I was asking for. – abergmeier Apr 04 '21 at 14:17

0 Answers0