我很困惑如何安排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