梳理总结Python开发中需要摒弃的18个坏习惯
本文梳理了Python开发中常见的18个不良编码习惯,涵盖字符串拼接、异常处理、文件操作、函数参数、推导式使用、类型检查、循环方式、日志记录及子进程调用等方面。通过对比错误代码与推荐写法,帮助开发者提升代码质量、执行效率及安全性,养成规范的Python编程风格。
接下来,我们将直接进入主题,开始学习。
1、字符串拼接应使用 + 号
不推荐的写法:
def manual_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,其执行效率更高:
def manual_str_formatting(name, subscribers):
# better
if subscribers > 100000:
print(f"Wow {name}! you have {subscribers} subscribers!")
else:
print(f"Lol {name} that's not many subs")
2、使用 finaly 而非上下文管理器
不推荐的写法:
def finally_instead_of_context_manager(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.sendall(b'Hello, world')
finally:
s.close()
推荐使用上下文管理器,即使发生异常也能确保 socket 被正确关闭:
def finally_instead_of_context_manager(host, port):
# close even if exception
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(b'Hello, world')
3、手动关闭文件
不推荐的写法:
def manually_calling_close_on_a_file(filename):
f = open(filename, "w")
f.write("hello!\n")
f.close()
推荐使用上下文管理器,即使发生异常也能自动关闭文件。凡是涉及上下文管理器的场景,都应优先采用此方式:
def manually_calling_close_on_a_file(filename):
with open(filename) as f:
f.write("hello!\n")
# close automatic, even if exception
4、except 后未指定异常类型
不推荐的写法:
def bare_except():
while True:
try:
s = input("Input a number: ")
x = int(s)
break
except: # oops! can't CTRL-C to exit
print("Not a number, try again")
这样会捕获所有异常,导致按下 CTRL-C 时程序无法终止。推荐的写法是:
def bare_except():
while True:
try:
s = input("Input a number: ")
x = int(s)
break
except Exception: # 比这更好的是用 ValueError
print("Not a number, try again")
5、函数参数使用可变对象
如果函数参数使用可变对象,后续调用可能会产生非预期结果。不推荐的写法:
def mutable_default_arguments():
def append(n, l=[]):
l.append(n)
return l
l1 = append(0) # [0]
l2 = append(1) # [0, 1]
推荐的写法:
def mutable_default_arguments():
def append(n, l=None):
if l is None:
l = []
l.append(n)
return l
l1 = append(0) # [0]
l2 = append(1) # [1]
6、从不使用推导式
不推荐的写法:
squares = {}
for i in range(10):
squares[i] = i * i
推荐的写法:
odd_squares = {i: i * i for i in range(10)}
7、过度使用推导式
推导式虽然便捷,但不应以牺牲代码可读性为代价。不推荐的写法:
c = [
sum(a[n * i + k] * b[n * k + j] for k in range(n))
for i in range(n)
for j in range(n)
]
推荐的写法:
c = []
for i in range(n):
for j in range(n):
ij_entry = sum(a[n * i + k] * b[n * k + j] for k in range(n))
c.append(ij_entry)
8、使用 == 检查类型是否一致
不推荐的写法:
def checking_type_equality():
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
if type(p) == tuple:
print("it's a tuple")
else:
print("it's not a tuple")
推荐的写法:
def checking_type_equality():
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
# probably meant to check if is instance of tuple
if isinstance(p, tuple):
print("it's a tuple")
else:
print("it's not a tuple")
9、使用 == 判断单例
不推荐的写法:
def equality_for_singletons(x):
if x == None:
pass
if x == True:
pass
if x == False:
pass
推荐的写法:
def equality_for_singletons(x):
# better
if x is None:
pass
if x is True:
pass
if x is False:
pass
10、判断变量使用 bool(x)
不推荐的写法:
def checking_bool_or_len(x):
if bool(x):
pass
if len(x) != 0:
pass
推荐的写法:
def checking_bool_or_len(x):
# usually equivalent to
if x:
pass
11、使用类 C 风格的 for 循环
不推荐的写法:
def range_len_pattern():
a = [1, 2, 3]
for i in range(len(a)):
v = a[i]
...
b = [4, 5, 6]
for i in range(len(b)):
av = a[i]
bv = b[i]
...
推荐的写法:
def range_len_pattern():
a = [1, 2, 3]
# instead
for v in a:
...
# or if you wanted the index
for i, v in enumerate(a):
...
# instead use zip
for av, bv in zip(a, b):
...
12、不使用 dict.items
不推荐的写法:
def not_using_dict_items():
d = {"a": 1, "b": 2, "c": 3}
for key in d:
val = d[key]
...
推荐的写法:
def not_using_dict_items():
d = {"a": 1, "b": 2, "c": 3}
for key, val in d.items():
...
13、解包元组使用索引
不推荐的写法:
mytuple = 1, 2
x = mytuple[0]
y = mytuple[1]
推荐的写法:
mytuple = 1, 2
x, y = mytuple
14、使用 time.time() 统计耗时
不推荐的写法:
def timing_with_time():
start = time.time()
time.sleep(1)
end = time.time()
print(end - start)
推荐使用 time.perf_counter(),精度更高:
def timing_with_time():
# more accurate
start = time.perf_counter()
time.sleep(1)
end = time.perf_counter()
print(end - start)
15、记录日志使用 print 而非 logging
不推荐的写法:
def print_vs_logging():
print("debug info")
print("just some info")
print("bad error")
推荐的写法:
def print_vs_logging():
# versus
# in main
level = logging.DEBUG
fmt = '[%(levelname)s] %(asctime)s - %(message)s'
logging.basicConfig(level=level, format=fmt)
# wherever
logging.debug("debug info")
logging.info("just some info")
logging.error("uh oh :(")
16、调用外部命令时使用 shell=True
不推荐的写法:
subprocess.run(["ls -l"], capture_output=True, shell=True)
如果 shell=True,则将 ls -l 传递给 /bin/sh (shell) 而非 Unix 上的 ls 程序,这会导致 subprocess 产生一个中间 shell 进程。换句话说,使用中间 shell 意味着在命令运行前,命令字符串中的变量、glob 模式及其他特殊 shell 功能都会被预处理。例如,$HOME 会在执行 echo 命令之前被处理。
推荐的写法是拒绝从 shell 执行:
subprocess.run(["ls", "-l"], capture_output=True)
17、从不尝试使用 numpy
不推荐的写法:
def not_using_numpy_pandas():
x = list(range(100))
y = list(range(100))
s = [a + b for a, b in zip(x, y)]
推荐的写法:
import numpy as np
def not_using_numpy_pandas():
# 性能更快
x = np.arange(100)
y = np.arange(100)
s = x + y
18、喜欢 import *
不推荐的写法:
from itertools import *
count()
这样会导致无法确定脚本中究竟有多少变量。推荐的写法:
from mypackage.nearby_module import awesome_function
def main():
awesome_function()
if __name__ == '__main__':
main()
至此,关于梳理总结Python开发中需要摒弃的18个坏习惯的文章介绍完毕。如需了解更多Python相关内容,请搜索本站历史文章或继续浏览后续文章。希望大家今后多多支持本站!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













