Python을 사용하다 보면 비슷해 보이는 세 종류의 기능을 만나게 된다.
이 세 가지를 구분하면 어떤 기능을 바로 사용할 수 있는지, 무엇을 import해야 하는지, 무엇을 설치해야 하는지 판단하기 쉬워진다.
별도 import 없이 사용할 수 있다.
print("hello")
len([1, 2, 3])
sum([10, 20, 30])
max([3, 8, 2])
min([3, 8, 2])
type()value = 10
print(type(value))
isinstance()value = 10
print(
isinstance(
value,
int,
)
)
abs()print(abs(-10))
round()print(
round(
3.14159,
2,
)
)
sorted()scores = [
80,
95,
70,
]
result = sorted(
scores,
reverse=True,
)
enumerate()users = [
"kim",
"lee",
]
for index, user in enumerate(
users,
start=1,
):
print(
index,
user,
)
zip()names = [
"kim",
"lee",
]
scores = [
90,
85,
]
for name, score in zip(
names,
scores,
):
print(
name,
score,
)
Python 설치 시 함께 제공되지만 보통 import가 필요하다.
대표적인 모듈:
datetimetimemathrandomjsonpathlibshutilstatisticscollectionsitertoolsfunctoolsloggingargparseredatetime날짜와 시간을 다룬다.
from datetime import date
start = date(
2026,
1,
1,
)
end = date(
2026,
10,
1,
)
diff = end - start
print(diff.days)
현재 날짜:
from datetime import datetime
now = datetime.now()
print(
now.strftime(
"%Y-%m-%d %H:%M:%S"
)
)
pathlib파일 경로를 객체 형태로 다룬다.
from pathlib import Path
path = (
Path("data")
/ "users.json"
)
if path.exists():
print(path.name)
shutil파일과 디렉터리의 고수준 작업에 사용한다.
import shutil
shutil.copy(
"source.txt",
"backup.txt",
)
디렉터리를 ZIP으로 만들 수도 있다.
shutil.make_archive(
"backup",
"zip",
"logs",
)
random무작위 값을 만든다.
import random
items = [
"A",
"B",
"C",
]
print(
random.choice(items)
)
리스트 섞기:
random.shuffle(items)
보안 토큰이나 비밀번호처럼 보안이 중요한 난수에는 일반 random 대신 secrets를 사용하는 것이 적절하다.
import secrets
token = secrets.token_hex(
16
)
statisticsimport statistics
scores = [
90,
80,
100,
70,
]
print(
statistics.mean(
scores
)
)
itertools반복 작업을 조합할 때 유용하다.
from itertools import combinations
items = [
"A",
"B",
"C",
]
for pair in combinations(
items,
2,
):
print(pair)
collections카운팅 작업에는 Counter가 편리하다.
from collections import Counter
actions = [
"view",
"view",
"buy",
"view",
"login",
]
counts = Counter(actions)
print(counts)
Python 기본 설치에 포함되지 않아 별도 설치가 필요하다.
예:
python -m pip install requests
사용:
import requests
Python 외부 패키지 대부분은 PyPI에 배포된다.
설치:
python -m pip install PACKAGE_NAME
삭제:
python -m pip uninstall PACKAGE_NAME
특정 버전:
python -m pip install PACKAGE_NAME==1.2.3
업그레이드:
python -m pip install --upgrade PACKAGE_NAME
설치 목록:
python -m pip list
다음부터 확인한다.
python --version
python -m pip --version
가상환경을 사용한다면 현재 활성화된 환경도 확인한다.
Python 실행 환경과 pip 설치 환경이 다르면 패키지를 설치했는데도 ModuleNotFoundError가 발생할 수 있다.
requests로 HTTP 요청하기python -m pip install requests
import requests
response = requests.get(
"https://example.com/api/users",
timeout=10,
)
response.raise_for_status()
data = response.json()
실제 API 호출에서는 timeout과 HTTP 오류 처리를 함께 고려하는 것이 좋다.
테스트나 개발용 가짜 데이터가 필요할 때 사용할 수 있다.
python -m pip install Faker
from faker import Faker
fake = Faker("ko_KR")
for _ in range(3):
print(
fake.name(),
fake.email(),
)
실제 개인정보를 테스트 데이터로 사용하지 않고도 현실적인 데이터를 만들 수 있다는 장점이 있다.
아무 패키지나 설치하기보다 다음을 확인하는 습관이 좋다.
작은 프로젝트에서는 현재 설치 상태를 파일로 남길 수 있다.
python -m pip freeze > requirements.txt
다른 환경에서 설치:
python -m pip install -r requirements.txt
다만 pip freeze는 환경의 모든 패키지를 기록하므로 프로젝트 규모가 커질수록 의존성 관리 도구나 명시적인 프로젝트 설정을 고려할 수 있다.
예를 들어 합계를 직접 반복문으로 계산할 수도 있다.
total = 0
for number in numbers:
total += number
하지만 내장 함수가 더 명확하다.
total = sum(numbers)
기능이 필요할 때 다음 순서로 생각해보면 좋다.
datetime, pathlib, shutil, collections, itertools, logging 등은 실무에서도 활용도가 높다.python -m pip 형태로 관리하면 실행 환경을 명확하게 맞추기 쉽다.requests, 테스트 데이터에는 Faker 같은 외부 패키지를 활용할 수 있다.