from .calculator.add_and_multiply import add_and_multiply if __name__ == '__main__': print(add_and_multiply(1,2))
https://docs.python.org/3/tutorial/modules.html#intra-package-references
Note that relative imports are based on the name of the current module. Since the name of the main module is always
"__main__"
, modules intended for use as the main module of a Python application must always use absolute imports.
python 공식 문서에서 main 모듈일 경우 절대경로로 import 해야한다고 서술해놓았다.
상대 경로는 현재 모듈을 기준점으로 잡기에,
이렇게 절대경로로 수정하면 문제가 해결된다.
#relative import from .multiplication import multiply def add_and_multiply(a,b): return multiply(a,b) + (a+b)
multiplication.py와 add_and_multiply.py는 같은 calculator 디렉토리에 위치하기 때문에
이렇게 .
을 빼주면 정상작동한다.
#absolute import from calculator.multiplication import multiply def add_and_multiply(a,b): return multiply(a,b) + (a+b)
똑같은 문제이다.
current directory라고 하는 현재의 프로젝트 디렉토리는 default로 sys.path에 포함되게 된다.
그러므로 절대 경로는 current directory로 부터 경로를 시작해야 한다.
똑같이 .
을 빼주면 정상작동한다.
__init__
__init__.py
파일은 해당 디렉토리가 패키지의 일부임을 알려준다.이 파일이 없으면 패키지로 인식되지 않는다(python3.3 부터 없어도 된다고 한다.)- 패키지가 import될 때
__init__.py
의 코드들이 자동으로 실행된다.
__all__
*
을 이용해서 import하고 싶다면 해당 디렉토리의__init__.py
안의__all__
에 import 가능한 모듈을 정의해주어야 사용 가능하다.