Python 모듈(module)과 패키지(package)Language/Python2023. 10. 25. 15:25
Table of Contents
파이썬 모듈과 패키지란?
파이썬에서 모듈(module)과 패키지(package)는 코드의 재사용성과 유지보수를 높이는 핵심 요소입니다.
- 모듈: 하나의
.py파일로 구성된 코드 단위입니다. 변수, 함수, 클래스 등을 포함할 수 있습니다. - 패키지: 여러 모듈을 계층적으로 구성한 디렉터리로, 패키지의 디렉터리에는
__init__.py파일이 포함됩니다.
모듈의 예
아래는 calculator.py라는 이름의 모듈입니다.
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
패키지의 예
다음은 math_utils라는 이름의 패키지 구조입니다.
math_utils/
__init__.py
operations.py
utils.py
__init__.py파일은 패키지를 초기화하는 역할을 하며, 비어 있어도 무방합니다.
모듈 사용하기 (import와 from ... import)
파이썬에서는 import를 사용하여 모듈이나 패키지를 가져올 수 있습니다.
import를 사용한 모듈 가져오기
모듈 전체를 가져옵니다.
import calculator
result = calculator.add(10, 5)
print(result) # 출력: 15
from ... import를 사용한 모듈 가져오기
특정 함수나 변수를 가져올 수 있습니다.
from calculator import add
result = add(20, 10)
print(result) # 출력: 30
별칭(alias) 사용
가져온 모듈에 별칭을 붙여 사용할 수 있습니다.
import calculator as calc
result = calc.subtract(50, 15)
print(result) # 출력: 35
내장 모듈 활용하기
파이썬에는 다양한 내장 모듈이 있어 추가 설치 없이 바로 사용할 수 있습니다. 몇 가지 주요 모듈을 살펴봅니다.
math 모듈
수학 관련 함수와 상수를 제공합니다.
import math
print(math.sqrt(16)) # 출력: 4.0
print(math.pi) # 출력: 3.141592653589793
random 모듈
난수 생성 기능을 제공합니다.
import random
print(random.randint(1, 100)) # 1과 100 사이의 난수
print(random.choice(['apple', 'banana', 'cherry'])) # 리스트에서 랜덤 선택
os 모듈
운영 체제와 상호작용할 수 있는 기능을 제공합니다.
import os
print(os.name) # 운영 체제 이름
print(os.listdir('.')) # 현재 디렉터리 목록
os.mkdir('new_folder') # 새 디렉터리 생성
패키지 만들기와 사용법
사용자 정의 패키지를 만드는 방법과 사용하는 법을 알아봅니다.
패키지 구조 생성
string_utils라는 패키지를 만든다고 가정합니다.
string_utils/
__init__.py
manipulations.py
validations.py
manipulations.py: 문자열 조작 관련 함수validations.py: 문자열 검증 관련 함수
패키지 내용 작성
manipulations.py:
def to_uppercase(text):
return text.upper()
def reverse_string(text):
return text[::-1]
validations.py:
def is_palindrome(text):
return text == text[::-1]
패키지 사용
패키지를 사용하려면 해당 디렉터리가 PYTHONPATH에 포함되어야 합니다.
from string_utils.manipulations import to_uppercase
from string_utils.validations import is_palindrome
print(to_uppercase("hello")) # 출력: HELLO
print(is_palindrome("racecar")) # 출력: True
__init__.py 활용
__init__.py 파일에서 패키지의 기본 내보내기를 정의할 수 있습니다.
# string_utils/__init__.py
from .manipulations import to_uppercase, reverse_string
from .validations import is_palindrome
이제 패키지를 간단히 가져올 수 있습니다.
from string_utils import to_uppercase, is_palindrome
print(to_uppercase("python")) # 출력: PYTHON
print(is_palindrome("madam")) # 출력: True
결론
파이썬의 모듈과 패키지는 코드의 재사용성과 가독성을 높이는 데 매우 유용합니다. 모듈을 통해 관련 기능을 묶고, 패키지를 사용해 코드를 계층적으로 구성함으로써 효율적이고 유지보수 가능한 코드를 작성할 수 있습니다. 개발 과정에서 모듈과 패키지를 적극적으로 활용해보세요!

'Language > Python' 카테고리의 다른 글
| Python 이터레이터와 제너레이터 (0) | 2023.10.27 |
|---|---|
| Python 예외 처리(Exception, try-except) (0) | 2023.10.26 |
| Python 객체지향 프로그래밍 (OOP) (0) | 2023.10.24 |
| Python 파일 입출력 (파일 열기, 읽기와 쓰기) (0) | 2023.10.24 |
| Python의 리스트 컴프리헨션(List Comprehension) (0) | 2023.10.23 |