我应该如何处理 python 上下文管理器中的 None ?
在 Python 中,以下模式很常见。
thing = x and load_thing(x)
它通过您的代码传播 None
(如果 x
是 None
那么 thing
也是如此)。这很有用,因为稍后在代码中您可以检查 thing
是否为 None 并具有不同的逻辑。
我不确定如何在上下文管理器中很好地发挥作用:以下代码不起作用(因为如果 x 为 None,则 with None as y
无效(因为 None 没有 __enter__
)
with x and load_thing(x) as y:
f(y)
我想出的最好的办法就是这个,但我认为阅读我的代码的人可能会咒骂我(没有乐趣乐趣我告诉你,没有乐趣)。
@contextlib.contextmanager
def const_manager(x):
yield x
with (const_manager(x) if x is None else load_thing(x)) as y:
f(y)
除了层层函数之外,还有更Pythonic的选择吗?定义和调用。
In Python, the following pattern is quite common.
thing = x and load_thing(x)
which propagates None
through your code (if x
is None
then so is thing
). This is useful because later in your code you can check if thing
is None and have different logic.
I'm not sure how to man this play well with context managers: the following code does not work (because if x is None, with None as y
is not valid (because None does not have __enter__
)
with x and load_thing(x) as y:
f(y)
The best thing I've come up with is this, but I think the people reading my code might curse me (no sense of fun I tell you, no sense of fun).
@contextlib.contextmanager
def const_manager(x):
yield x
with (const_manager(x) if x is None else load_thing(x)) as y:
f(y)
Is there a more pythonic alternative? Besides layers and layers of function definitions and calls.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将测试放入包装器上下文管理器中。
您也可以考虑使用
contextlib.nullcontext
代替。Put the test in your wrapper context manager.
You might also consider using
contextlib.nullcontext
instead.不要让
None
到达您的上下文管理器。Don't let the
None
ever reach your context manager.