magika icon indicating copy to clipboard operation
magika copied to clipboard

Circular import: logger ↔ magika

Open DaisukeYoda opened this issue 10 months ago • 5 comments

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.

DaisukeYoda avatar Jan 31 '26 07:01 DaisukeYoda

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?

reyammer avatar Feb 12 '26 14:02 reyammer

You're right. I looked into why this doesn't crash. It relies on two conditions:

  1. Python puts a partially-initialized module in sys.modules, so __init__.py won't re-execute
  2. colors.py has zero imports from magika

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.

DaisukeYoda avatar Feb 13 '26 14:02 DaisukeYoda

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.

reyammer avatar Feb 16 '26 15:02 reyammer

That makes sense. Thanks!

DaisukeYoda avatar Feb 17 '26 16:02 DaisukeYoda

Sounds good, thanks!

reyammer avatar Feb 20 '26 13:02 reyammer