Pythonic Code

range 대신 enumerate

# ❌ Unpythonic
animals = ['cat', 'dog', 'moose']
for i in range(len(animals)):
    print(i, animals[i])

# ✅ Pythonic
for i, animal in enumerate(animals):
    print(i, animal)

# 인덱스 필요 없으면 직접 순회
for animal in animals:
    print(animal)

open/close 대신 with

# ❌ Unpythonic
fileObj = open('spam.txt', 'w')
fileObj.write('Hello')
fileObj.close()

# ✅ Pythonic
with open('spam.txt', 'w') as fileObj:
    fileObj.write('Hello')

None 비교는 is 사용

# ❌ Unpythonic
if spam == None:
    pass

# ✅ Pythonic
if spam is None:
    pass

Boolean 직접 비교 금지

# ❌ Unpythonic
if is_valid == True:
    pass

# ✅ Pythonic
if is_valid:
    pass

if not is_valid:
    pass

원시 문자열 (Raw String)

# ❌ Unpythonic - 백슬래시 이스케이프
path = 'C:\\Users\\Al\\Desktop'

# ✅ Pythonic - r 접두사
path = r'C:\Users\Al\Desktop'

F-문자열 포매팅

name, age = 'Alice', 25

# ❌ Unpythonic
msg = "Hello, " + name + ". Age: " + str(age)

# ✅ Pythonic
msg = f"Hello, {name}. Age: {age}"

# 표현식도 가능
width, length = 10, 12
f"Area: {width * length}"  # "Area: 120"

딕셔너리 get()과 setdefault()

# ❌ Unpythonic
if 'key' in d:
    value = d['key']
else:
    value = 'default'

# ✅ Pythonic
value = d.get('key', 'default')

# 기본값 설정하면서 가져오기
value = d.setdefault('key', 'default')

switch문 대신 딕셔너리

# ❌ Unpythonic
if season == 'Winter':
    holiday = "New Year's Day"
elif season == 'Spring':
    holiday = 'May Day'
elif season == 'Summer':
    holiday = 'Juneteenth'
else:
    holiday = 'Personal day off'

# ✅ Pythonic
holiday = {
    'Winter': "New Year's Day",
    'Spring': 'May Day',
    'Summer': 'Juneteenth',
    'Fall': 'Halloween'
}.get(season, 'Personal day off')

체이닝 비교 연산자

# ❌ Unpythonic
if 42 < spam and spam < 99:
    pass

# ✅ Pythonic
if 42 < spam < 99:
    pass

# 할당 체이닝
spam = eggs = bacon = 'value'

# 비교 체이닝
spam == eggs == bacon == 'value'  # True

여러 값 중 하나인지 확인

# ❌ Unpythonic
if spam == 'cat' or spam == 'dog' or spam == 'moose':
    pass

# ✅ Pythonic
if spam in ('cat', 'dog', 'moose'):
    pass

map/filter 대신 리스트 컴프리헨션

numbers = [8, 16, 18, 19, 12, 1, 6, 7]

# ❌ Unpythonic - map
list(map(lambda n: str(n), numbers))

# ✅ Pythonic
[str(n) for n in numbers]

# ❌ Unpythonic - filter
list(filter(lambda n: n % 2 == 0, numbers))

# ✅ Pythonic
[n for n in numbers if n % 2 == 0]

3항 연산자 주의

# ✅ Pythonic - 간단한 경우만
message = 'Access granted' if condition else 'Access denied'

# ❌ Unpythonic - 중첩 금지
age_range = 'child' if age < 13 else 'teen' if age < 18 else 'adult'

# ✅ 복잡하면 if-elif-else 사용
if age < 13:
    age_range = 'child'
elif age < 18:
    age_range = 'teen'
else:
    age_range = 'adult'