摘要:def process_files(file1, file2, file3): with open(file1, 'r') as f1: with open(file2, 'r') as f2: with open(file3, 'r') as f3: pas
嵌套的 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 ExitStackdef 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 ospassword = os.getenv("MY_SECRET_PASSWORD")不好:
data = {"name": "Alice", "age": 30}city = data["city"] if "city" in data else "Unknown"✅ 好:
city = data.get("city", "Unknown")不好:
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"来源:自由坦荡的湖泊AI一点号
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!