gpt4 book ai didi

处理 None 和 with Statement 的 Pythonic 方法

转载 作者:行者123 更新时间:2023-12-04 15:29:42 25 4
gpt4 key购买 nike

我想调用一个函数并传递一个类似File 的对象或None。但是,使用类似 File 的对象,我想使用 with 语句正确处理它的资源分配。但是,如果我的 with 表达式的计算结果为 None,Python 将引发异常 (AttributeError)。我想我可以手写完整的 try/except block ,但是是否存在一种简洁的 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() ,而不是:

import contextlib

with (open(whatever) if flag else contextlib.nullcontext()) as f:
do_whatever()

fnot flag 情况下将是 None - 分配给 f 的东西是 __enter__ 的返回值,不必是上下文管理器本身。

关于处理 None 和 with Statement 的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61492099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com