Code Style
◉ 암묵적 코드
Bad
def make_complex(*args):
x, y = args
return dict(**locals())
Good
def make_complex(x, y):
return {'x': x, 'y': y}
◉ 한 라인에 한 문장
Bad
print('one'); print('two')
if x == 1: print 'one'
if <complex comparison> and <other complex comparison>:
# do something
Good
print('one')
print('two')
if x == 1:
print('one')
cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
# do something
Conventions
◉ 상수일 경우 확인
Bad
if attr == True:
print('True!')
if attr == None:
print('attr is None!')
Good
# Just check the value
if attr:
print('attr is true!')
# or check for the opposite
if not attr:
print('attr is false!')
# or, since None is considered false, explicitly check for it
if attr is None:
print('attr is None!')
◉ 사전 요소 접근
Bad
d = {'hello': 'world'}
if d.has_key('hello'):
print(d['hello']) # prints 'world'
else:
print('default_value')
Good
d = {'hello': 'world'}
print(d.get('hello', 'default_value')) # prints 'world'
print(d.get('thingy', 'default_value')) # prints 'default_value'
# Or:
if 'hello' in d:
print(d['hello'])
◉ 리스트 짧게 쓰기
리스트 함축은 강력하다. 이를 잘 활용하면 리스트를 짧게 쓸 수 있다.
Bad
# Filter elements greater than 4
a = [3, 4, 5]
b = []
for i in a:
if i > 4:
b.append(i)
Good
a = [3, 4, 5]
b = [i for i in a if i > 4]
# Or:
b = filter(lambda x: x > 4, a)
Bad
# Add three to all list members.
a = [3, 4, 5]
for i in range(len(a)):
a[i] += 3
Good
a = [3, 4, 5]
a = [i + 3 for i in a]
# Or:
a = map(lambda i: i + 3, a)
# enumerate()를 사용하면 list의 인덱스를 알려준다.
a = [3, 4, 5]
for i, item in enumerate(a):
print i, item
# prints
# 0 3
# 1 4
# 2 5
◉ 파일로부터 읽기
Bad
f = open('file.txt')
a = f.read()
print(a)
f.close()
Good
with open('file.txt') as f:
for line in f:
print line
◉ 라인 이어쓰기
Bad
my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
when I had put out my candle, my eyes would close so quickly that I had not even \
time to say “I’m going to sleep.”"""
from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
yet_another_nice_function
Good
my_very_big_string = (
"For a long time I used to go to bed early. Sometimes, "
"when I had put out my candle, my eyes would close so quickly "
"that I had not even time to say “I’m going to sleep.”"
)
from some.deep.module.inside.a.module import (
a_nice_function, another_nice_function, yet_another_nice_function)