C.W.K.
Stream
Lesson 04 of 05 · published

Python 의 Zen — 그리고 진짜 의미

~15 min · zen, pep-20, philosophy, style

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

Zen — 'import this' 로 읽기

PEP 20, Python 의 Zen, Tim Peters 의 Python 디자인 철학 요약하는 19 격언. 어떤 Python 인터프리터에서도 import this 가 출력. 명백한 거 ("Beautiful is better than ugly"), 깊은 거 ("In the face of ambiguity, refuse the temptation to guess"), 실제 API 디자인 결정하는 가이드라인 몇 개.

가장 중요한 4

"한 가지 — 가능하면 한 가지만 — 명확한 방법." API 디자인 시 같은 거 5 가지 방법 제공 저항. 좋은 한 방법 골라. "Explicit 이 implicit 보다." 호출 사이트에 동작 보이게, 마법 회피. "에러는 절대 조용히 통과 X." 예외 삼키지 말고, 전파하거나 의도적으로 처리. "구현 설명 어려우면 나쁜 아이디어." 코드가 뭐 하는지 묘사 못 하면 아마 잘못.

초보가 잘못 읽는 거

"Simple is better than complex" 가 "항상 가장 단순한 거" 의미 X. "단순이 작동할 때 단순" 의미. 다음 줄 — "Complex is better than complicated" — 가 교정 — 복잡성 필요할 때 구조화 (complex) X 엉킴 (complicated). 명확한 구조 가진 복잡 코드가 문제 안 맞는 단순 코드 이김.

안 사라지는 거

"Now is better than never. Although never is often better than *right* now." 수수께끼처럼 읽힘. 의미 — 완벽 기다리지 말고 ship — 근데 후회할 반쯤 빌드한 거 ship X. 양쪽 다 규율.

Pythonic Way: 1 년에 적어도 한 번 Zen 읽어. 격언 짧음, 적용 안 짧음. 시니어 Python 개발자의 API 디자인, 에러 처리, 명명 선택 직관이 이 필터 통과한 코드의 수년 반영.

Code

Zen 직접 읽기·python
import this

# Python 의 Zen, Tim Peters
#
# Beautiful is better than ugly.
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicated.
# Flat is better than nested.
# Sparse is better than dense.
# Readability counts.
# Special cases aren't special enough to break the rules.
# Although practicality beats purity.
# Errors should never pass silently.
# Unless explicitly silenced.
# In the face of ambiguity, refuse the temptation to guess.
# There should be one-- and preferably only one --obvious way to do it.
# Although that way may not be obvious at first unless you're Dutch.
# Now is better than never.
# Although never is often better than *right* now.
# If the implementation is hard to explain, it's a bad idea.
# If the implementation is easy to explain, it may be a good idea.
# Namespaces are one honking great idea -- let's do more of those!
Explicit > implicit — 적용·python
# IMPLICIT — caller 가 어떤 모드인지 알 수 X
result = process_data(items)

# EXPLICIT — 호출 사이트가 선택 보여
result = process_data(items, mode="strict", retry=3)

# IMPLICIT — 마법 인자 변경
def bad(items):
    items.sort()        # caller 의 list 변경! 놀라움.

# EXPLICIT — 정렬된 사본 반환
def good(items):
    return sorted(items)
에러 절대 조용히 통과 X — 적용·python
# 안 좋음 — 조용한 실패
try:
    risky_operation()
except Exception:
    pass            # 버그-숨김 supreme

# 좋음 — 특정 에러 처리 + 로그
try:
    risky_operation()
except ValueError as e:
    logger.warning("value error: %s", e)
    # ... fallback 또는 re-raise

# 좋음 — 의외 에러 전파
try:
    risky_operation()
except ValueError:
    handle_known_case()
# 다른 예외 stack 위로 — 그게 맞음
한 가지 명확한 방법 — 적용·python
# UNPYTHONIC — 같은 거 너무 많은 방법
class MyList:
    def append(self, x): ...
    def add(self, x): ...           # 둘이 같은 거?
    def push(self, x): ...          # 이건?
    def insert_at_end(self, x): ...
    def __iadd__(self, x): ...

# PYTHONIC — 정석 이름 하나 골라
class MyList:
    def append(self, x): ...        # 한 가지 방법

External links

Exercise

Zen 격언 중 가장 actionable 한 셋 골라. 각각 — 의미 *X* 인 거 한 문장 예 (흔한 잘못된 읽기). 그 다음 그걸 어기는 코드와 교정 버전 한 문장 예. 핵심은 Zen 외우기 X — 각 줄이 뭐 피하려는지 내재화.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.