본문 바로가기
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

PEP 20의 Zen은 Tim Peters가 정리한 19개 격언이고 import this로 읽을 수 있어. 예쁜 문구를 외우기보다 API·오류·이름을 고를 때 던질 질문으로 써.

명시적인 것이 암시적인 것보다 낫다는 말은 호출부에서 중요한 동작을 보이라는 뜻이고, 오류를 조용히 넘기지 말라는 말은 전파하거나 의도적으로 처리하라는 뜻이야. 가능한 한 한 가지 분명한 방법을 두고, 구현을 설명하기 어렵다면 설계를 다시 의심해.

단순함이 복잡함보다 낫다는 말은 필요한 복잡성까지 지우라는 뜻이 아니야. 필요한 복잡성은 구조화하되 뒤엉키게 만들지 말라는 뜻이야. 지금 하는 것이 영원히 미루는 것보다 낫지만 성급히 내놓느니 하지 않는 편이 나을 때도 있어. 격언끼리의 긴장이 판단을 만들어.

Code

import this로 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!
명시적인 API로 바꾸기·python
# IMPLICIT — caller 가 어떤 모드인지 알 수 없음
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)
오류를 의도적으로 처리하기·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에서 실제 결정에 쓸 격언 세 개를 골라. 각각 흔한 오독 한 문장, 그 격언을 어긴 코드 한 예, 고친 버전 한 예를 적어 어떤 문제를 피하려는 말인지 설명해.

Progress

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

댓글 0

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

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