파이썬 모듈 임포트 실전 가이드: 예제로 배우는 모듈 시스템
파이썬 모듈이란 무엇인가?
모듈은 변수, 함수, 클래스를 포함할 수 있는 단일 파이썬 파일입니다. 파일명을 guru99.py로 지으면 모듈은 guru99로 접근합니다. 모듈을 사용하면 큰 프로그램을 논리적 조각으로 나누어 코드를 체계적이고 재사용 가능하게 유지할 수 있습니다.
왜 모듈을 임포트하는가?
다른 파일에 정의된 코드를 사용하려면 반드시 임포트해야 합니다. 임포트를 통해 모듈의 함수, 클래스, 변수에 접근할 수 있으며, 이는 JavaScript, Java, Ruby 같은 언어의 import 키워드와 유사합니다.
모듈 생성과 임포트
간단한 예제로 살펴보겠습니다.
폴더 구조:
modtest/
test.py
display.py
1. test.py 생성:
def display_message():
return 'Welcome to Guru99 Tutorials!'
2. display.py 생성 후 test 임포트:
import test
print(test.display_message())
display.py 실행 시 출력:
Welcome to Guru99 Tutorials!
모듈에서 클래스 임포트
Car.py에 자동차 클래스가 정의되어 있다고 가정:
class Car:
brand_name = 'BMW'
model = 'Z4'
manu_year = '2020'
def __init__(self, brand_name, model, manu_year):
self.brand_name = brand_name
self.model = model
self.manu_year = manu_year
def car_details(self):
print('Car brand is', self.brand_name)
print('Car model is', self.model)
print('Car manufacture year is', self.manu_year)
def get_car_brand(self):
print('Car brand is', self.brand_name)
def get_car_model(self):
print('Car model is', self.model)
display.py에서 사용:
import Car
car_det = Car.Car('BMW', 'Z5', 2020)
print(car_det.brand_name)
car_det.car_details()
car_det.get_car_brand()
car_det.get_car_model()
출력:
BMW
Car brand is BMW
Car model is Z5
Car manufacture year is 2020
Car brand is BMW
Car model is Z5
from으로 특정 항목 임포트
몇몇 함수나 변수만 필요할 때 직접 임포트:
from test import display_message
print(display_message())
임포트하지 않은 이름을 사용하면 NameError 발생:
from test import display_message
print(display_message1())
모듈 전체 임포트
import test로 전체 모듈 임포트 후 모듈 접두사 사용, 또는 from test import *로 현재 네임스페이스에 모든 이름 임포트. 후자는 편리하지만 네임스페이스 오염 우려.
dir() 이해하기
내장 dir() 함수는 모듈에 정의된 속성을 포함해 객체의 모든 속성을 나열합니다:
import Car
print(dir(Car))
표준 라이브러리에도 적용:
import json
print(dir(json))
패키지 작업
패키지는 __init__.py 파일과 하나 이상의 모듈을 포함하는 디렉터리입니다. 예:
디렉터리 구조:
mypackage/
__init__.py
module1.py
module2.py
module3.py
module1.py 내용:
def mod1_func1():
print('Welcome to Module1 function1')
def mod1_func2():
print('Welcome to Module1 function2')
# …
별칭으로 임포트:
import mypackage.module1 as mod1
mod1.mod1_func1()
mod1.mod1_func2()
파이썬 모듈 검색 경로
파이썬이 임포트를 해결할 때 확인 순서:
- 현재 작업 디렉터리
- 내장 모듈
sys.path에 나열된 디렉터리
확인 방법:
import sys
print(sys.path)
모듈 별칭 사용
긴 모듈 이름을 줄여 가독성 향상:
import test as t
print(t.display_message())
print(t.my_name)
절대 임포트 vs 상대 임포트
멀티 모듈 프로젝트에서 모듈을 전체 경로(절대)로 참조하거나 현재 파일 기준 상대 경로(상대)로 참조할 수 있습니다.
절대 임포트 예제
from package1.module1 import myfunc1
# 또는
import package1.module1
package1.module1.myfunc1()
상대 임포트 예제
from .module1 import myfunc1
# 또는
from .subpkg.module3 import myfunc3
절대 임포트는 프로젝트 이동 시 더 명확하고 덜 오류 발생하지만 장황해질 수 있습니다. 상대 임포트는 코드를 간결하게 하지만 대규모 프로젝트에서 추적이 어려울 수 있습니다.
핵심 요약
- 모듈로 파이썬 코드를 별도 파일로 분리
import 또는 from … import …로 모듈 내용 접근
- 별칭(
as)으로 긴 모듈 이름 단순화
- 패키지는 디렉터리로 모듈 구성,
__init__.py로 표시
sys.path 이해로 임포트 에러 해결
- 명확성 위해 절대 임포트, 간결성 위해 상대 임포트 선택