| name | python-patterns |
| description | 견고하고 효율적이며 유지보수가 쉬운 Python 애플리케이션을 구축하기 위한 Pythonic 관용구, PEP 8 표준, 타입 힌트 및 모범 사례입니다. |
| origin | ECC |
Python 개발 패턴
견고하고 효율적이며 유지보수가 쉬운 애플리케이션을 구축하기 위한 관용적인 Python 패턴 및 모범 사례입니다.
활성화 시점
- 새로운 Python 코드를 작성할 때
- Python 코드를 리뷰할 때
- 기존 Python 코드를 리팩터링할 때
- Python 패키지/모듈을 설계할 때
핵심 원칙
1. 가독성이 중요하다 (Readability Counts)
Python은 가독성을 우선시합니다. 코드는 명확하고 이해하기 쉬워야 합니다.
def get_active_users(users: list[User]) -> list[User]:
"""제공된 목록에서 활성 사용자만 반환합니다."""
return [user for user in users if user.is_active]
def get_active_users(u):
return [x for x in u if x.a]
2. 명시적인 것이 암시적인 것보다 낫다 (Explicit is Better Than Implicit)
마법 같은 처리를 피하고, 코드가 무엇을 하는지 명확하게 하십시오.
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
import some_module
some_module.setup()
3. EAFP - 허락을 구하는 것보다 용서를 구하는 것이 쉽다 (Easier to Ask Forgiveness Than Permission)
Python은 조건을 확인하는 것보다 예외 처리를 선호합니다.
def get_value(dictionary: dict, key: str) -> Any:
try:
return dictionary[key]
except KeyError:
return default_value
def get_value(dictionary: dict, key: str) -> Any:
if key in dictionary:
return dictionary[key]
else:
return default_value
타입 힌트 (Type Hints)
기본 타입 어노테이션
from typing import Optional, List, Dict, Any
def process_user(
user_id: str,
data: Dict[str, Any],
active: bool = True
) -> Optional[User]:
"""사용자를 처리하고 업데이트된 User 또는 None을 반환합니다."""
if not active:
return None
return User(user_id, data)
현대적인 타입 힌트 (Python 3.9+)
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
from typing import List, Dict
def process_items(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
타입 별칭(Type Aliases) 및 TypeVar
from typing import TypeVar, Union
JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]
def parse_json(data: str) -> JSON:
return json.loads(data)
T = TypeVar('T')
def first(items: list[T]) -> T | None:
"""목록의 첫 번째 항목을 반환하거나 목록이 비어 있으면 None을 반환합니다."""
return items[0] if items else None
프로토콜 기반 덕 타이핑 (Protocol-Based Duck Typing)
from typing import Protocol
class Renderable(Protocol):
def render(self) -> str:
"""객체를 문자열로 렌더링합니다."""
def render_all(items: list[Renderable]) -> str:
"""Renderable 프로토콜을 구현하는 모든 항목을 렌더링합니다."""
return "\n".join(item.render() for item in items)
오류 처리 패턴
특정 예외 처리
def load_config(path: str) -> Config:
try:
with open(path) as f:
return Config.from_json(f.read())
except FileNotFoundError as e:
raise ConfigError(f"설정 파일을 찾을 수 없음: {path}") from e
except json.JSONDecodeError as e:
raise ConfigError(f"설정 파일의 JSON이 유효하지 않음: {path}") from e
def load_config(path: str) -> Config:
try:
with open(path) as f:
return Config.from_json(f.read())
except:
return None
예외 체이닝 (Exception Chaining)
def process_data(data: str) -> Result:
try:
parsed = json.loads(data)
except json.JSONDecodeError as e:
raise ValueError(f"데이터 파싱 실패: {data}") from e
커스텀 예외 계층 구조
class AppError(Exception):
"""모든 애플리케이션 오류의 기본 예외."""
pass
class ValidationError(AppError):
"""입력 검증 실패 시 발생."""
pass
class NotFoundError(AppError):
"""요청한 리소스를 찾을 수 없을 때 발생."""
pass
def get_user(user_id: str) -> User:
user = db.find_user(user_id)
if not user:
raise NotFoundError(f"사용자를 찾을 수 없음: {user_id}")
return user
컨텍스트 관리자 (Context Managers)
리소스 관리
def process_file(path: str) -> str:
with open(path, 'r') as f:
return f.read()
def process_file(path: str) -> str:
f = open(path, 'r')
try:
return f.read()
finally:
f.close()
커스텀 컨텍스트 관리자
from contextlib import contextmanager
@contextmanager
def timer(name: str):
"""코드 블록의 실행 시간을 측정하는 컨텍스트 관리자."""
start = time.perf_counter()
yield
elapsed = time.perf_counter() - start
print(f"{name} 소요 시간: {elapsed:.4f}초")
with timer("데이터 처리"):
process_large_dataset()
컨텍스트 관리자 클래스
class DatabaseTransaction:
def __init__(self, connection):
self.connection = connection
def __enter__(self):
self.connection.begin_transaction()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.connection.commit()
else:
self.connection.rollback()
return False
컴프리헨션 및 제너레이터
리스트 컴프리헨션 (List Comprehensions)
names = [user.name for user in users if user.is_active]
names = []
for user in users:
if user.is_active:
names.append(user.name)
result = [x * 2 for x in items if x > 0 if x % 2 == 0]
def filter_and_transform(items: Iterable[int]) -> list[int]:
result = []
for x in items:
if x > 0 and x % 2 == 0:
result.append(x * 2)
return result
제너레이터 표현식 (Generator Expressions)
total = sum(x * x for x in range(1_000_000))
total = sum([x * x for x in range(1_000_000)])
제너레이터 함수
def read_large_file(path: str) -> Iterator[str]:
"""큰 파일을 한 줄씩 읽습니다."""
with open(path) as f:
for line in f:
yield line.strip()
for line in read_large_file("huge.txt"):
process(line)
데이터 클래스 및 Named Tuples
데이터 클래스 (Data Classes)
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class User:
"""__init__, __repr__, __eq__가 자동으로 생성되는 사용자 엔티티."""
id: str
name: str
email: str
created_at: datetime = field(default_factory=datetime.now)
is_active: bool = True
검증 기능이 있는 데이터 클래스
@dataclass
class User:
email: str
age: int
def __post_init__(self):
if "@" not in self.email:
raise ValueError(f"유효하지 않은 이메일: {self.email}")
if self.age < 0 or self.age > 150:
raise ValueError(f"유효하지 않은 나이: {self.age}")
Named Tuples
from typing import NamedTuple
class Point(NamedTuple):
"""불변 2D 좌표."""
x: float
y: float
def distance(self, other: 'Point') -> float:
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
데코레이터 (Decorators)
함수 데코레이터
import functools
import time
def timer(func: Callable) -> Callable:
"""함수 실행 시간을 측정하는 데코레이터."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} 소요 시간: {elapsed:.4f}초")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
매개변수가 있는 데코레이터
def repeat(times: int):
"""함수를 여러 번 반복하는 데코레이터."""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(times=3)
def greet(name: str) -> str:
return f"Hello, {name}!"
동시성 패턴
I/O 바운드 작업을 위한 스레딩 (Threading)
import concurrent.futures
import threading
def fetch_url(url: str) -> str:
"""URL 호출 (I/O 바운드 작업)."""
import urllib.request
with urllib.request.urlopen(url) as response:
return response.read().decode()
def fetch_all_urls(urls: list[str]) -> dict[str, str]:
"""스레드를 사용하여 여러 URL을 동시에 호출합니다."""
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_url = {executor.submit(fetch_url, url): url for url in urls}
results = {}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
results[url] = future.result()
except Exception as e:
results[url] = f"오류: {e}"
return results
CPU 바운드 작업을 위한 멀티프로세싱 (Multiprocessing)
def process_data(data: list[int]) -> int:
"""CPU 집약적인 계산."""
return sum(x ** 2 for x in data)
def process_all(datasets: list[list[int]]) -> list[int]:
"""여러 프로세스를 사용하여 여러 데이터셋을 처리합니다."""
with concurrent.futures.ProcessPoolExecutor() as executor:
results = list(executor.map(process_data, datasets))
return results
동시 I/O를 위한 Async/Await
import asyncio
async def fetch_async(url: str) -> str:
"""비동기적으로 URL을 호출합니다."""
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def fetch_all(urls: list[str]) -> dict[str, str]:
"""여러 URL을 동시에 호출합니다."""
tasks = [fetch_async(url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
return dict(zip(urls, results))
패키지 조직화
표준 프로젝트 레이아웃
myproject/
├── src/
│ └── mypackage/
│ ├── __init__.py
│ ├── main.py
│ ├── api/
│ │ ├── __init__.py
│ │ └── routes.py
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py
│ └── utils/
│ ├── __init__.py
│ └── helpers.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_api.py
│ └── test_models.py
├── pyproject.toml
├── README.md
└── .gitignore
임포트 규칙 (Import Conventions)
import os
import sys
from pathlib import Path
import requests
from fastapi import FastAPI
from mypackage.models import User
from mypackage.utils import format_name
패키지 익스포트를 위한 init.py
"""mypackage - 샘플 Python 패키지."""
__version__ = "1.0.0"
from mypackage.models import User, Post
from mypackage.utils import format_name
__all__ = ["User", "Post", "format_name"]
메모리 및 성능
메모리 효율을 위한 slots 사용
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
class Point:
__slots__ = ['x', 'y']
def __init__(self, x: float, y: float):
self.x = x
self.y = y
대용량 데이터를 위한 제너레이터
def read_lines(path: str) -> list[str]:
with open(path) as f:
return [line.strip() for line in f]
def read_lines(path: str) -> Iterator[str]:
with open(path) as f:
for line in f:
yield line.strip()
루프 내 문자열 결합 피하기
result = ""
for item in items:
result += str(item)
result = "".join(str(item) for item in items)
from io import StringIO
buffer = StringIO()
for item in items:
buffer.write(str(item))
result = buffer.getvalue()
Python 도구 통합
필수 명령어
black .
isort .
ruff check .
pylint mypackage/
mypy .
pytest --cov=mypackage --cov-report=html
bandit -r .
pip-audit
safety check
... (중략) ...
빠른 참조: Python 관용구
| 관용구 | 설명 |
|---|
| EAFP | 허락을 구하는 것보다 용서를 구하는 것이 쉽다 |
| 컨텍스트 관리자 | 리소스 관리를 위해 with 사용 |
| 리스트 컴프리헨션 | 간단한 데이터 변환용 |
| 제너레이터 | 지연 평가 및 대용량 데이터셋용 |
| 타입 힌트 | 함수 시그니처에 어노테이션 추가 |
| 데이터 클래스 | 자동 생성 메서드가 있는 데이터 컨테이너용 |
__slots__ | 메모리 최적화용 |
| f-strings | 문자열 포맷팅 (Python 3.6+) |
pathlib.Path | 경로 작업용 (Python 3.4+) |
enumerate | 루프에서 인덱스-요소 쌍 획득용 |
피해야 할 안티 패턴
def append_to(item, items=[]):
items.append(item)
return items
def append_to(item, items=None):
if items is None:
items = []
items.append(item)
return items
if type(obj) == list:
process(obj)
if isinstance(obj, list):
process(obj)
if value == None:
process()
if value is None:
process()
from os.path import *
from os.path import join, exists
try:
risky_operation()
except:
pass
try:
risky_operation()
except SpecificError as e:
logger.error(f"작업 실패: {e}")
기억하십시오: Python 코드는 읽기 쉽고, 명시적이어야 하며, 최소 놀람의 원칙(Principle of Least Surprise)을 따라야 합니다. 의심스러울 때는 영리함보다 명확함을 우선시하십시오.