defmanual_str_formatting(name, subscribers):
if subscribers > 100000:
print("Wow " + name + "! you have " + str(subscribers) + " subscribers!")
else:
print("Lol " + name + " that's not many subs")
好的做法:
使用 f-string(格式化字符串字面量),它更高效且语法清晰。
defmanual_str_formatting(name, subscribers):
# betterif subscribers > 100000:
print(f"Wow {name}! you have {subscribers} subscribers!")
else:
print(f"Lol {name} that's not many subs")
deffinally_instead_of_context_manager(host, port):
# close even if exceptionwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(b'Hello, world')
3. 尝试手动关闭文件
坏的做法:
显式调用 close() 容易遗漏,特别是在复杂逻辑分支中。
defmanually_calling_close_on_a_file(filename):
f = open(filename, "w")
f.write("hello!\n")
f.close()
好的做法:
始终优先使用上下文管理器,确保文件自动关闭。
defmanually_calling_close_on_a_file(filename):
withopen(filename) as f:
f.write("hello!\n")
# close automatic, even if exception
defmutable_default_arguments():
defappend(n, l=None):
if l isNone:
l = []
l.append(n)
return l
l1 = append(0) # [0]
l2 = append(1) # [1]
6. 从不用推导式
坏的做法:
使用循环构建字典或列表,代码冗长。
squares = {}
for i inrange(10):
squares[i] = i * i
好的做法:
使用字典推导式,简洁高效。
odd_squares = {i: i * i for i inrange(10)}
7. 推导式用的上瘾
坏的做法:
过度嵌套的推导式会牺牲可读性,难以维护。
c = [
sum(a[n * i + k] * b[n * k + j] for k inrange(n))
for i inrange(n)
for j inrange(n)
]
好的做法:
对于复杂逻辑,使用普通循环结构。
c = []
for i inrange(n):
for j inrange(n):
ij_entry = sum(a[n * i + k] * b[n * k + j] for k inrange(n))
c.append(ij_entry)
8. 检查类型是否一致用 ==
坏的做法:
使用 type() == 进行类型检查不支持继承关系,且不够 Pythonic。
defchecking_type_equality():
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
iftype(p) == tuple:
print("it's a tuple")
else:
print("it's not a tuple")
好的做法:
使用 isinstance(),它能正确处理继承和多态。
defchecking_type_equality():
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
# probably meant to check if is instance of tupleifisinstance(p, tuple):
print("it's a tuple")
else:
print("it's not a tuple")
9. 用 == 判断是否单例
坏的做法:
使用 == 比较单例对象(如 None, True, False)是不安全的。
defequality_for_singletons(x):
if x == None:
passif x == True:
passif x == False:
pass
好的做法:
使用 is 运算符进行身份比较。
defequality_for_singletons(x):
# betterif x isNone:
passif x isTrue:
passif x isFalse:
pass
defchecking_bool_or_len(x):
# usually equivalent toif x:
pass
11. 使用类 C 风格的 for 循环
坏的做法:
使用 range(len()) 遍历列表索引,不如直接迭代元素直观。
defrange_len_pattern():
a = [1, 2, 3]
for i inrange(len(a)):
v = a[i]
...
b = [4, 5, 6]
for i inrange(len(b)):
av = a[i]
bv = b[i]
...
好的做法:
直接迭代元素,或使用 enumerate 获取索引,使用 zip 并行迭代。
defrange_len_pattern():
a = [1, 2, 3]
# insteadfor v in a:
...
# or if you wanted the indexfor i, v inenumerate(a):
...
# instead use zipfor av, bv inzip(a, b):
...
12. 不实用 dict.items
坏的做法:
通过键访问值需要两次查找,效率较低。
defnot_using_dict_items():
d = {"a": 1, "b": 2, "c": 3}
for key in d:
val = d[key]
...
好的做法:
使用 .items() 直接解包键值对。
defnot_using_dict_items():
d = {"a": 1, "b": 2, "c": 3}
for key, val in d.items():
...