- 모듈을
import할 때 여러 방법이 있다.
- 나는 보통 리트코드를 주로 이용하고 있는데 리트코드에서 파이썬 표준 라이브러리는
import하지 않아도 된다.
- 그래서
import를 직접 타이핑한 적이 별로 없는데, import도 방법이 여러가지 있고, 권장하는 스타일이 있다.
여러 가지 import 방법
import math
print(math.sqrt(16))
import numpy as np
print(np.array([1, 2, 3]))
from math import sqrt, factorial
print(sqrt(16))
print(factorial(5))
import importlib
module_name = "math"
math_module = importlib.import_module(module_name)
print(math_module.sqrt(16))
PEP 8 모듈 임포트 가이드 라인
import os
import sys
def my_function():
pass
import sys
import os
import os
import sys
import numpy as np
import pandas as pd
import my_module
from math import sqrt, factorial
import numpy as np
import pandas as pd
def dynamic_import(module_name):
import importlib
return importlib.import_module(module_name)
math_module = dynamic_import("math")
print(math_module.sqrt(25))
📊 파이썬 모듈 임포트 방법 비교
| 방법 | 예시 코드 | 장점 | 단점 | 특징 |
|---|
import 모듈명 | import math | 네임스페이스 충돌 없음, 가독성 좋음 | 항상 모듈명.을 붙여야 해서 코드가 길어질 수 있음 | 가장 일반적이고 권장되는 방식 |
import 모듈명 as 별칭 | import numpy as np | 코드가 간결해짐, 긴 모듈명을 줄일 수 있음 | 직관적이지 않은 별칭 사용 시 가독성 저하 | NumPy, Pandas 등에서 자주 사용됨 |
from 모듈명 import 함수 | from math import sqrt | 모듈명을 생략하고 바로 사용 가능 | 같은 이름의 함수가 다른 모듈과 충돌할 위험 | 특정 기능만 사용할 때 유용 |
from 모듈명 import * | from math import * | 모든 기능을 한 번에 가져올 수 있음 | 네임스페이스 오염 위험, 가독성 저하 | PEP 8에서 권장하지 않음 ❌ |
동적 임포트 (importlib) | importlib.import_module("math") | 문자열로 모듈을 로드할 수 있어 유연함 | 속도가 느리고 디버깅 어려움 | 플러그인 시스템, 동적 로딩에 유용 |