python - try/except 和上下文管理器
问题描述
我正在尝试使我的 try/except 块尽可能小。但是,我不知道如何将其与可能很长的with
块相协调:
try:
with db.connect() as connection:
# many lines interacting with the database
# and more lines
# and yet more lines
except ConnectionError:
有没有办法写 try/except 所以它不是那么长?
我想我可以将大部分代码重新组织成一个单独的函数:
try:
with db.connect() as connection:
do_stuff(connection)
except ConnectionError:
...但似乎应该有一种方法可以在更少的行中做到这一点。
解决方案
您实际上不必将with
语句放在try
语句中, ifdb.connect
是唯一可以引发ConnectionError
. 如果出现连接错误,则没有要关闭的连接。
try:
connection = db.connect()
except ConnectionError:
...
with connection:
...
声明关心的不是对db.connect
自身的调用;这是对andwith
的调用。connection.__enter__
connection.__exit__
根据您对的操作,可能应该保护ConnectionError
该语句以避免尝试使用未定义的名称。with
connection
connection
如果您不喜欢在分配它和with
语句之间做某事的想法,您可以使用 anExitStack
立即进入上下文。例如,
from contextlib import ExitStack
with ExitStack() as es:
try:
connection = es.enter_context(db.connect())
except ConnectionError:
...
# do stuff with the connection
推荐阅读
- git - 更新被拒绝,因为您当前分支的尖端位于其远程分支的后面。在再次推送之前集成远程更改
- python-3.x - 数据帧序列检测:查找连续三行具有负值的组
- session - curator中的连接超时和会话超时有什么区别
- javascript - 使功能在页面加载后运行并在没有 ID 或 Class 的情况下编辑 Label 的 innerHTML
- python - 需要帮助编写余弦相似度的测试用例
- java - 如何查找方法(在我们无权访问源代码的 .class 中)何时被其他类调用
- java - 使用 TimeUnit 在更改 JavaFX 标签文本之间休眠
- javascript - Recharts - 如何不插入值区域图
- r - 在 R 中制作相关值的矩形矩阵,可能使用 corrplot
- javascript - 如何在 index.html 文件中定义变量?(window.parentPage = true;)