使用ExitStack()来管理多个上下文
嵌套的 with 语句可能会变得混乱。使用 ExitStack() 来保持整洁。
不好:
def process_files(file1, file2, file3):
with open(file1, 'r') as f1:
with open(file2, 'r') as f2:
with open(file3, 'r') as f3:
pass
好:
from contextlib import ExitStack
def process_files(file1, file2, file3):
with ExitStack() as stack:
f1 = stack.enter_context(open(file1, 'r'))
f2 = stack.enter_context(open(file2, 'r'))
f3 = stack.enter_context(open(file3, 'r'))
pass
保持命名约定一致
不好:
def myFunction(num):
MyVar = num / 3.5
return MyVar
好:
def my_function(num):
my_var = num / 3.5
return my_va
避免硬编码敏感信息
不要直接将 API 密钥或密码存储在代码中!
坏:
password = "iLOVEcats356@33"
好:
import os
password = os.getenv("MY_SECRET_PASSWORD")
使用get()来避免字典中的键错误
不好:
data = {"name": "Alice", "age": 30}
city = data["city"] if "city" in data else "Unknown"
好:
city = data.get("city", "Unknown")
利用match进行简洁的条件语句
不好:
def describe_type(obj):
if isinstance(obj, str):
return "It's a string"
elif isinstance(obj, int):
return "It's an integer"
elif isinstance(obj, list):
return "It's a list"
else:
return "It's something else"
好:
def describe_type(obj):
match obj:
case str():
return "It's a string"
case int():
return "It's an integer"
case list():
return "It's a list"
case _:
return "It's something else"