网站首页 > 技术文章 正文
使用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"
猜你喜欢
- 2025-05-30 跟我一起玩儿转Python之机器学习线性回归实践
- 2025-05-30 小白学习《python编程从入门到实践》,需要注意的点
- 2025-05-30 Python匿名函数详解:从概念到实践
- 2025-05-30 零基础:用 Unsloth 在 Colab 上光速微调 Llama 3.2 模型|小白也能看懂
- 2025-05-30 用Docker打包Python应用的关键要点与实践
- 2025-05-30 Python + Flask 项目开发实践系列《一》
- 2025-05-30 利用Python实现Kaggle经典案例之泰坦尼克号乘客生存预测
- 2025-05-30 Python资料全家桶—网络爬虫入门到实践,共计4.2G
- 2025-05-30 Python文件读写最佳实践:关键操作的异常处理
- 2025-05-30 python文件读写操作最佳实践——处理大文件时使用迭代或内存映射
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 252℃Python实现字符串小写转大写并写入文件
- 108℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)