gpt4 book ai didi

python - 是否可以在 python 中使用可选的 with/as 语句?

转载 作者:太空狗 更新时间:2023-10-29 17:41:34 24 4
gpt4 key购买 nike

取而代之的是:

FILE = open(f)
do_something(FILE)
FILE.close()

最好用这个:

with open(f) as FILE:
do_something(FILE)

如果我有这样的事情怎么办?

if f is not None:
FILE = open(f)
else:
FILE = None
do_something(FILE)
if FILE is not None:
FILE.close()

do_something 也有一个“if FILE is None”子句,并且在那种情况下仍然做一些有用的事情 - 我不想如果 FILE 是 None 就跳过 do_something。

有没有一种合理的方法可以将其转换为 with/as 形式?或者我只是想以错误的方式解决可选文件问题?

最佳答案

如果你只是这样写:

if f is not None:
with open(f) as FILE:
do_something(FILE)
else:
do_something(f)

(file 是内置 btw)

更新

这是一种使用不会崩溃的可选 None 来执行即时上下文的时髦方法:

from contextlib import contextmanager

none_context = contextmanager(lambda: iter([None]))()
# <contextlib.GeneratorContextManager at 0x1021a0110>

with (open(f) if f is not None else none_context) as FILE:
do_something(FILE)

它创建一个返回 None 值的上下文。 with 将生成 FILE 作为文件对象,或者生成 None 类型。但是 None 类型将有一个适当的 __exit__

更新

如果您使用的是 Python 3.7 或更高版本,那么您可以以更简单的方式声明空上下文管理器以用于替代目的:

import contextlib
none_context = contextlib.nullcontext()

您可以在这里阅读更多相关信息:

https://docs.python.org/3.7/library/contextlib.html#contextlib.nullcontext

关于python - 是否可以在 python 中使用可选的 with/as 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168208/

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