티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?

"ImportError: Cannot import name X" 또는 "AttributeError" 를 어떻게 해결하나요?(순환 import로 인해 발생 가능성이 가장 높음)

 문제 내용 

I have some code spread across multiple files that try to import from each other, as follows:

다음과 같이 여러 파일에 걸쳐 서로 가져오기를 시도하는 코드가 있습니다.

 

main.py:

main.py:

 

from entity import Ent

entity.py:

entity.py:

 

from physics import Physics
class Ent:
    ...

physics.py:

physics.py:

 

from entity import Ent
class Physics:
    ...

I then run from main.py and I get the following error:

그런 다음 main.py에서 실행하면 다음 오류가 표시됩니다.

 

Traceback (most recent call last):
File "main.py", line 2, in <module>
    from entity import Ent
File ".../entity.py", line 5, in <module>
    from physics import Physics
File ".../physics.py", line 2, in <module>
    from entity import Ent
ImportError: cannot import name Ent

I'm assume the error is due to importing entity twice - once in main.py and later in physics.py - but how can I work around the problem?

이 오류는 엔티티를 두 번 가져오기 때문인 것 같습니다. 한 번은 main.py에서, 나중에는 physics.py에서 이 문제를 해결하려면 어떻게 해야 합니까?

 


See also What happens when using mutual or circular (cyclic) imports in Python? for a general overview of what is allowed and what causes a problem WRT circular imports. See Why do circular imports seemingly work further up in the call stack but then raise an ImportError further down? for technical details on why and how the problem occurs.

참고 항목Python에서 상호 또는 순환(순환) 가져오기를 사용하면 어떻게 됩니까? 허용되는 항목과 WRT 순환 가져오기 문제의 원인에 대한 일반적인 개요. 순환 가져오기가 콜 스택에서 더 위쪽으로 작동하는 것처럼 보이지만 가져오기 오류가 더 아래쪽으로 발생하는 이유를 참조하십시오. 문제가 발생하는 이유와 방법에 대한 기술 세부 정보를 참조하십시오.

 

 

 

 높은 점수를 받은 Solution 

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

순환 종속 가져오기가 있습니다. physics.py는 클래스 Ent가 정의되기 전에 엔티티에서 가져오고 physics은 이미 초기화 중인 엔티티를 가져오려고 합니다. 엔티티 모듈에서 physics에 대한 종속성을 제거합니다.

 

 

 

 가장 최근 달린 Solution 

In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.

제 경우에는 Jupyter 노트북에서 작업하고 있었는데 작업 파일에 클래스/함수를 정의했을 때 가져오기가 이미 캐시되어 있었기 때문에 이 문제가 발생했습니다.

 

I restarted my Jupyter kernel and the error disappeared.

Jupyter 커널을 다시 시작했는데 오류가 사라졌습니다.

 

 

 

출처 : https://stackoverflow.com/questions/9252543/what-can-i-do-about-importerror-cannot-import-name-x-or-attributeerror

반응형
댓글
공지사항
최근에 올라온 글