首页 > 解决方案 > 用于处理 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__

标签: pythonwith-statement

解决方案


如果您想要一个什么都不做的上下文管理器,那就是contextlib.nullcontext(),不是None

import contextlib

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

fNone在这种not flag情况下 - 被分配的东西f__enter__' 的返回值,它不必是上下文管理器本身。


推荐阅读