본문 바로가기
Python

ImportError: attempted relative import with no known parent package

by 붕어사랑 티스토리 2023. 12. 14.
반응형

파이썬 할 때 마다 매번 마주치는 에러.

 

 

1. 원인

 

파이썬은 상대경로로 임포트 할 때 __name__을 기준으로 상대경로를 파악한다고 한다.

허나 어떤 파이썬 파일을 직접 실행시키면 __name__이 __main__으로 설정된다.

이때 상대경로 임포트는 항상 실패한다고 한다.

 

https://stackoverflow.com/questions/16981921/relative-imports-in-python-3

 

Relative imports in Python 3

I want to import a function from another file in the same directory. Usually, one of the following works: from .mymodule import myfunction from mymodule import myfunction ...but the other one giv...

stackoverflow.com

 

 

... relative imports rely on __name__ to determine the current module's position in the package hierarchy. In a main module, the value of __name__ is always '__main__', so explicit relative imports will always fail (as they only work for a module inside a package)

 

 

2. 해결방법

 

메인 모듈이 아닌곳에서 상대경로를 이용하거나, 절대경로를 사용해주어야 한다.

 

아무튼 머리가 아픈문제이고 다들 잘 이해도 못하니 그냥 돌아만 가면 신경쓰지 않아도 될 것 같다.

반응형

'Python' 카테고리의 다른 글

파이썬에서 fft를 출력할때 고려해야할 사항  (0) 2024.05.16

댓글