我应该如何处理 python 上下文管理器中的 None ?

发布于 2025-01-16 13:49:15 字数 689 浏览 3 评论 0原文

在 Python 中,以下模式很常见。

thing = x and load_thing(x)

它通过您的代码传播 None (如果 xNone 那么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哽咽笑 2025-01-23 13:49:15

将测试放入包装器上下文管理器中。

@contextlib.contextmanager
def default_manager(cm, x):
    if x is None
        yield x
    else:
        yield cm(x)


with default_manager(load_thing, x) as y:
    f(y)

您也可以考虑使用 contextlib.nullcontext 代替。

with (load_thing if x is not None else nullcontext)(x) as y:
    f(y)

Put the test in your wrapper context manager.

@contextlib.contextmanager
def default_manager(cm, x):
    if x is None
        yield x
    else:
        yield cm(x)


with default_manager(load_thing, x) as y:
    f(y)

You might also consider using contextlib.nullcontext instead.

with (load_thing if x is not None else nullcontext)(x) as y:
    f(y)
吃素的狼 2025-01-23 13:49:15

不要让 None 到达您的上下文管理器。

# ...
if x is None:
    return None  # or raise SomeException, depends on context
# ...
with my_context(x) as c:  # Here we do have something to play with
    # ...

Don't let the None ever reach your context manager.

# ...
if x is None:
    return None  # or raise SomeException, depends on context
# ...
with my_context(x) as c:  # Here we do have something to play with
    # ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文