Circular import: logger ↔ magika
Summary
I was analyzing the codebase with pyscn before forking, and found a circular import dependency. This might break depending on import order, so wanted to flag it.
$ uvx pyscn check --select deps .
magika/logger.py:1:1: circular dependency detected: magika.logger -> magika.magika
Cycle
logger.py (from magika import colors)
→ __init__.py (from magika.magika import Magika)
→ magika.py (from magika.logger import get_logger)
→ (cycle)
Suggested Fix
In logger.py, change:
# Before
from magika import colors
# After
from magika.colors import GREEN, RED, YELLOW, RESET
This avoids going through __init__.py.
Happy to submit a PR if needed.
Thanks! interesting. I agree there seems to be a cycle, but not sure why it's not causing problems.
My understanding is that this works, but it could crash depending on specific import order. But so far I couldn't make it to crash this.
BTW wouldn't from magika.colors import GREEN, RED, YELLOW, RESET also go through __init__.py?
You're right. I looked into why this doesn't crash. It relies on two conditions:
- Python puts a partially-initialized module in
sys.modules, so__init__.pywon't re-execute colors.pyhas zero imports frommagika
The root cause is that __init__.py eagerly imports Magika (which pulls in numpy, onnxruntime, etc.), so any intra-package import triggers the full dependency chain. I think PEP 562 __getattr__ in __init__.py would fix this with a single-file change while preserving the public API.
Dirtying up __init__.py with __getattr__ doesn't seem worth it for this. The reason is that 1) this sort of cycle does not appear to be an actual problem, 2) the magika module doesn't have anything that one would like to import without using the actual Magika class... so the fact that all the dependencies get loaded at the first from magika import X, whatever X may be, doesn't look too problematic.
Please let me know if you think I'm missing something -- if not, I'd keep things as is and close this one.
Thanks again for reporting.
That makes sense. Thanks!
Sounds good, thanks!