단도직입 파이썬(Python) – 패키지(Package)

패키지(package)는 모듈(module)을 계층적으로 관리할 수 있게 합니다. 우선 calctest_pkg폴더를 생성합니다.(각자 작업환경에 알맞게 지정하면 됩니다. 제 경우 c:/Python_code/calctest_pkg로 진행하게 됩니다.)
새롭게 생성된 calctest_pkg 폴더에 __init__.py를 만들어 둡니다.
(__init__.py 내용은 비워도 상관 없습니다. 폴더에 __init__.py가 있다면 파이썬은 해당 폴더를 패키지로 인식하게 됩니다. 단, python version 3.3 이상에서는 __init__존재여부 상관없이 패키지로 인식할 수 있으나 하위버전 사용자를 위하여 __init__.py 생성을 권장합니다.)

add_test.py
def add (a, b):
return a + b
sub_test.py
def sub (a,b):
return a - b
add_test.py와 sub_test.py를 작성하여 __init__.py 함께 calctest_pkg폴더에 넣고 c:/python_code폴더 에서 main.py를 작성 합니다.

import 또는 from ~ import로 모듈 또는 모듈의 특정 메서드를 호출 할 수 있습니다.
>>> import calctest_pkg.add_test
>>> print (add_test.add(1,2))
3
>>> from calctest_pkg.add_test import add
>>>print(add(1,2))
3
>>> from calctest_pkg import sub_test
>>> print (sub_test.sub(5,2))
3
에러없이 결과를 출력합니다.
C:\Python_code>python c:/Python_code/main.py
Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from calctest_pkg import *
>>> add_test.add(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'add_test' is not defined
>>>
from calctest_pkg import * (모든 모듈을 호출합니다.)
하지만 함수를 실행하면 add_test가 정의 되지 않았다는 에러가 발생하는데 이는 특정 디렉토리의 모든( * ) 모듈을 import할 때 해당 디렉토리의 __init__.py에 __all__변수를 설정하고 import 할 수 있는 모듈을 설정해야 합니다.
__init__.py에 아래와 같이 __all__변수를 정의합니다.
__all__ = [ ‘add_test’, ‘sub_test’ ]
그리고 실행하게 되면 에러 없이 결과를 출력합니다.
C:\Python_code>python
Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from calctest_pkg import *
>>> add_test.add(1,2)
3
>>> sub_test.sub(3,1)
2
함수, 클래스, 모듈 그리고 패키지까지 알아봤습니다. 조금씩 헷갈리지만 직접 손으로 코딩하고 에러도 수없이 경험하며 디버깅(debugging)을 하다 보면 실력이 늘 수 밖에 없습니다. 어떠한 프로그래밍 언어도 눈으로만 보고 머리로만 따라가게 되면 끝까지 도달하기 어렵습니다. 조금이라도 배운 만큼 아는 만큼이라도 직접 코딩하고 결과 확인하고 수정하고 이래도 해보고 저래도 해보고…! 그러다 보면 어슬프게라도 답 나옵디다.^^
Python Package Index site를 링크하오니 원하는 package가 있는지 확인해 보시죠?
PyPI · The Python Package Index
The Python Package Index (PyPI) is a repository of software for the Python programming language.
pypi.org