清晰明了
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
函数参数
1、位置参数
send(message, recipient) or point(x, y) 符合常理
send(recipient='World', message='Hello') and point(y=2, x=1) 容易误解
2、关键参数
send(message, to, cc=None, bcc=None).
send('Hello', 'World', 'Cthulhu', 'God'), 不好
send('Hello again', 'World', bcc='God', cc='Cthulhu'). 乱序,也不好
send('Hello', 'World', cc='Cthulhu', bcc='God').按顺序,指定,最好
3、任意参数列表
send(message, *args)
send('Hello', 'God', 'Mom', 'Cthulhu') # args=['God', 'Mom', 'Cthulhu']
这样更好些
send(message, recipients)
send('Hello', ['God', 'Mom', 'Cthulhu']).
4、任意参数字典
send(message, **kargs)
同上
参数良好原则:
a、易读:参数不用注释别人都明白
b、易改:修改参数不会影响其他参数
函数返回
def complex_function(a, b, c):
if not a:
return None # Raising an exception might be better
if not b:
return None # Raising an exception might be better
# Some complex code trying to compute x from a, b and c
# Resist temptation to return x if succeeded
if not x:
# Some Plan-B computation of x
return x # One single exit point for the returned value x will help
# when maintaining the code.
真值检验
Bad:
if attr == True:
print 'True!'
if attr == None:
print 'attr is None!'
Good:
# Just check the value
if attr:
print 'attr is truthy!'
# or check for the opposite
if not attr:
print 'attr is falsey!'
# 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']
#《doc》
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
has_key(key)
Test for the presence of key in the dictionary. has_key() is deprecated in favor of key in d.
列表捷径
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]
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)
文件操作
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
用with更好,它会自动关闭文件,甚至是有异常时也会这样。
特长的行
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)