我很困惑如何安排Python上下文管理器可以做的所有事情到适当的位置。放在一起的Python上下文管理器:一个谜题
据我了解,这有可能进入全面建设上下文管理的要素包括:
- 答:东西总是发生
- B:需要对C
- C语言带来的准备:创建并建立在上下文中使用的对象X
- D:在上下文开始之前使用成功建立的X执行一些事情
- E:将X返回到上下文(供使用)
- F:结束语与X时一切正常在上下文
- G的端部:进入上下文
- 小时,然后应对故障的在C和后果B:应对故障的后果上下文
我想我大致得到这些元素在上下文管理器函数中的每个元素的位置,但对于如何将它们排列在类中完全不知所措。
是否有一个上下文管理器函数和类的模板,显示这些元素中的每一个都在函数和(尤其是)类中?我在这里和其他地方查看了很多示例,但没有发现任何全面的示例,并且许多示例使用实际的代码,我无法总是映射到上面的每个构建块。
我认为我基本上明白通过函数来实现,当一个上下文管理器的行为:
from contextlib import contextmanager
@contextmanager
def log_file_open(oec_data, build_description, log_dir):
# A: Something that always happens
try:
# B: Some stuff needed to make a_thing
a_thing = establish_thing_in_a_way_that_might_fail() # C
# D: Some things that happen using a_thing at context start
yield a_thing # E
# F: Wrap up with a_thing when all is well
except:
# G: Deal the consequences of failure in try or...
# H: Deal the consequences of failure in context
finally:
# Could F go here instead?
例如,打开的东西应该在成功打开并写入到一个文件关闭,但应该清理如果有问题,我可以写
from contextlib import contextmanager
@contextmanager
def log_file_open(oec_data, build_description, log_dir):
print('Entering context...')
try:
usable_file_name = get_some_name()
a_thing = open(usable_file_name, mode='w')
a_thing.write('Logging context started.')
yield a_thing
a_thing.write('Logging context ended.')
except:
a_thing.close()
os.remove(a_thing.name)
raise
但我不确定这是对的, nd我很困惑它如何映射到__enter()__
和__exit()__
在类中的使用。是(示意性):
def __init__(self):
# A: Something that always happens
def __enter__(self):
try:
# B: Some stuff needed to make a_thing
a_thing = establish_thing_in_a_way_that_might_fail() # C
# D: Some things that happen using a_thing at context start
except:
# G: Deal the consequences of failure in try
a_thing = some_appropriate_blank_value
finally:
return a_thing # E
def __exit__(self, type, value, traceback):
if type is None:
# F: Wrap up with a_thing when all is well
return True
else:
# H: Deal the consequences of failure in context
return False