현상
Django 애플리케이션 업그레이드 또는 실행 중 manage.py makemigrations 명령 실행 시 ImportError가 발생합니다.
에러 traceback은 다음과 같습니다.
File "/home/eduardo/projdevs/upgrade-intra/corporate/models/section.py", line 9, in <module>
from authentication.models import get_sentinel
ImportError: cannot import name 'get_sentinel' from partially initialized module 'authentication.models' (most likely due to a circular import)

원인
이 에러는 모듈 간 **순환 참조(Circular Import)**가 발생했을 때 나타납니다.
파이썬은 모듈을 로드하는 과정에서 해당 코드를 실행하며, 다른 모듈을 import하면 실행이 일시 중단됩니다.
이때 authentication.models가 corporate.models를 import하고, corporate.models가 다시 authentication.models를 필요로 하는 순환 구조가 존재합니다.
구체적인 참조 경로는 다음과 같습니다.
authentication/models.py파일 내from corporate.models import ...구문으로 인해corporate.models가 로드됩니다.corporate/models/section.py파일이corporate.models에 의해 import됩니다.section.py파일 내from authentication.models import get_sentinel구문이 실행되며 순환이 발생합니다.
authentication.models가 완전히 로드되기 전에 section 모듈이 해당 모듈의 내용을 가져오려 하므로, 모듈이 '부분적으로 초기화(partially initialized)'된 상태로 이름(함수)을 찾을 수 없게 됩니다.
해결 방법
순환 import를 해결하려면 모듈 간 import 순서를 재구성하거나, import를 지연(delayed import)해야 합니다. 가장 명확한 방법은 모듈을 계층 구조로 조직하여, 하위 계층의 모듈이 상위 계층의 모듈을 import하지 않도록 하는 것입니다.
- 순환 참조 경로 확인
authentication.models→corporate.models→section→authentication.models로 이어지는 경로를 파악합니다. - 지연 import 적용
순환 참조의 핵심인
section.py에서authentication.models의 import를 함수 내부나 필요 시점에 지연시킵니다.
# 수정 전 (section.py)
from authentication.models import get_sentinel
# 수정 후 (section.py) - 함수 내부에서 import
def some_function():
from authentication.models import get_sentinel
# ...

다른 해결 방법
지연 import 외에도 모듈의 import 순서를 조정하여 순환을 끊는 방법이 있습니다. 모듈을 디렉토리 구조나 논리적 계층에 따라 정리하고, 계층 하위 모듈이 상위를 참조하지 않도록 구조를 개선해야 합니다.
기존 구조
모듈 간 import가 양방향으로 이루어져 순환 참조 발생
제안 구조
모듈을 계층적으로 조직하여 하위 모듈만 상위 모듈을 참조
추가 참고사항
순환 import는 모듈 설계 단계에서 이를 예방하는 것이 가장 좋습니다. 공통으로 사용되는 모델이나 상수를 별도의 모듈로 분리하여 순환을 끊는 전략을 사용할 수 있습니다. 모듈을 조직할 때는 항상 모듈이 다른 모듈보다 먼저 정의되어 있는지, 혹은 계층 구조를 따르는지 확인해야 합니다.
출처
- StackOverflow: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) — 작성자: 3WZ(질문), John Gordon(답변) (CC BY-SA)
- Python 공식 문서: The Python Tutorial — Modules
본문 이미지는 위 출처에서 가져왔습니다.
읽다가 궁금한 코드를 직접 실행해 보세요.
작은 실험이 이해를 도와줄 수 있어요.