1. 合并嵌套的 if 条件
合并之前:
if a:
if b:
return c
合并后:
if a and b:
return c
2. 将重复的代码移到条件语句之外
if sold > DISCOUNT_AMOUNT:
total = sold * DISCOUNT_PRICE
label = f'Total: {total}'
else:
total = sold * PRICE
label = f'Total: {total}'
if sold > DISCOUNT_AMOUNT:
total = sold * DISCOUNT_PRICE
else:
total = sold * PRICE
label = f'Total: {total}'
3. 将内部循环中的yield替换为yield from
yield from使程序运行效率提高约 15%。
重构前:
def get_content(entry):
for block in entry.get_blocks():
yield block
重构后:
def get_content(entry):
yield from entry.get_blocks()
4. 使用 any() 而不是用于循环
常见的模式是,我们需要查找是否集合中的一个或多个项符合某些条件。这可以通过 for 循环完成,例如:
found = False
for thing in things:
if thing == other_thing:
found = True
break
更简洁的方法,是使用 Python 的 any() 和 all()内置函数,来清楚地显示代码的意图:
found = any(thing == other_thing for thing in things)
5. 用[]替换list()
创建列表的最简洁和 Pythonic 的方法是使用 []以获取更好的性能:
x = list() # 不建议使用
x = [] # 建议使用
x = ['first', 'second'] # 建议使用
同样的原因和性能表现,使用{}替代dict()。
6. 将重复执行的语句移出for/while循环
重构前:
for building in buildings:
city = 'London'
addresses.append(building.street_address, city)
重构后:
city = 'London'
for building in buildings:
addresses.append(building.street_address, city)
参考链接:
https://sourcery.ai/blog/explaining-refactorings-1/