gpt4 book ai didi

python - 在另一个上下文管理器中处理上下文管理器的实例

转载 作者:太空狗 更新时间:2023-10-29 17:07:40 26 4
gpt4 key购买 nike

如何在 Python 中处理在另一个上下文管理器中创建的上下文管理器?

示例:假设您有充当​​上下文管理器的 A 类和也充当上下文管理器的 B 类。但是 B 类的实例必须实例化并使用 A 类的实例。我已经阅读了 PEP 343,这是我想到的解决方案:

class A(object):
def __enter__(self):
# Acquire some resources here
return self

def __exit__(seplf, exception_type, exception, traceback):
# Release the resources and clean up
pass


class B(object):
def __init__(self):
self.a = A()

def __enter__(self):
# Acquire some resources, but also need to "start" our instance of A
self.a.__enter__()
return self

def __exit__(self, exception_type, exception, traceback):
# Release the resources, and make our instance of A clean up as well
self.a.__exit__(exception_type, exception, traceback)

这是正确的做法吗?还是我错过了一些陷阱?

最佳答案

如果您可以使用 @contextlib.contextmanager 装饰器,您的生活会变得更加轻松:

import contextlib

@contextlib.contextmanager
def internal_cm():
try:
print "Entering internal_cm"
yield None
print "Exiting cleanly from internal_cm"
finally:
print "Finally internal_cm"


@contextlib.contextmanager
def external_cm():
with internal_cm() as c:
try:
print "In external_cm_f", c
yield [c]
print "Exiting cleanly from external_cm_f", c
finally:
print "Finally external_cm_f", c


if "__main__" == __name__:
with external_cm():
print "Location A"
print
with external_cm():
print "Location B"
raise Exception("Some exception occurs!!")

关于python - 在另一个上下文管理器中处理上下文管理器的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24637199/

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