[python] Calculator package

Bik_Kyun·2022년 3월 6일
0
post-thumbnail

1. calculator 패키지 만들기

2. main.py에서 상대경로로 add_and_multiply를 임포트 했을 때 발생하는 에러를 확인하고, 다음의 파이썬 공식 문서를 참고해 main module에서는 패키지의 모듈을 어떻게 임포트 해야하는가?

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 해야한다고 서술해놓았다.
상대 경로는 현재 모듈을 기준점으로 잡기에,

이렇게 절대경로로 수정하면 문제가 해결된다.

3. add_and_multiply.py에서 multiply함수를 절대경로와 상대경로로 각각 임포트 해보고 main 모듈과 차이점을 생각해보고 결과를 출력하라.

1) 상대경로

#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 디렉토리에 위치하기 때문에

이렇게 .을 빼주면 정상작동한다.

2) 절대경로

#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로 부터 경로를 시작해야 한다.

똑같이 .을 빼주면 정상작동한다.

4. __init__

  • __init__.py 파일은 해당 디렉토리가 패키지의 일부임을 알려준다.
  • 이 파일이 없으면 패키지로 인식되지 않는다(python3.3 부터 없어도 된다고 한다.)
  • 패키지가 import될 때 __init__.py의 코드들이 자동으로 실행된다.

__all__

  • *을 이용해서 import하고 싶다면 해당 디렉토리의 __init__.py안의 __all__에 import 가능한 모듈을 정의해주어야 사용 가능하다.
profile
비진

0개의 댓글