python - 用于处理 None 和 with 语句的 Pythonic 方法
问题描述
我想调用一个函数并传递一个File
-like 对象或None
. 但是,使用File
-like 对象,我想用with
语句正确处理它的资源分配。AttributeError
但是,如果我的with
表达式计算结果为,Python 将引发异常 ( ) None
。我想我可以写完整的try
/except
块手写,但是处理这种情况的简洁的 Pythonic 方式存在吗?
def call_method(o1, o2, f_in):
if f_in:
pass # Do something optional if we have the f_in value
# ...
with (open(path, 'rb') if flag else None) as f_in:
call_method(opt1, opt2, f_in)
# Throws an AttributeError, since None does not have __exit__
解决方案
如果您想要一个什么都不做的上下文管理器,那就是contextlib.nullcontext()
,不是None
:
import contextlib
with (open(whatever) if flag else contextlib.nullcontext()) as f:
do_whatever()
f
将None
在这种not flag
情况下 - 被分配的东西f
是__enter__
' 的返回值,它不必是上下文管理器本身。
推荐阅读
- javascript - 无法在 JavaScript fetch() 中将请求正文发送到 API 端点
- elasticsearch - Kibana:如何仅显示搜索词周围的有限行/单词,而不是完整文档?
- excel - vba 代码运行时出现“excel 已停止工作”
- string - 如何在未转义的空白处拆分字符串?
- android - 如何修复运行 ionic cordova build android 时未找到 AAPT 错误前台活动?
- python-3.x - 这个矩阵乘法背后的逻辑是什么?
- c# - 字段中的 QueryExpression 不应为空且具有特定值
- java - 当我尝试运行新的示例应用程序时,无法打开 xmltree 错误
- angular - Getting some error in while setting up Angular using cmd
- python - Django如何选择forms.Form