假設我們有以下mod.py
:爲什麼模塊不能成爲上下文管理器(對'with'語句)?
def __enter__():
print("__enter__<")
def __exit__(*exc):
print("__exit__< {0}".format(exc))
class cls:
def __enter__(self):
print("cls.__enter__<")
def __exit__(self, *exc):
print("cls.__exit__< {0}".format(exc))
及以下使用它:
import mod
with mod:
pass
我得到一個錯誤:
Traceback (most recent call last):
File "./test.py", line 3, in <module>
with mod:
AttributeError: __exit__
根據文檔的文檔with
語句應執行如下(我相信它在第2步失敗,因此截斷列表):
- The context expression (the expression given in the with_item) is evaluated to obtain a context manager.
- The context manager’s
__exit__()
is loaded for later use.- The context manager’s
__enter__()
method is invoked.- etc...
正如我的理解是沒有理由__exit__
找不到。有什麼我錯過了,使模塊無法作爲上下文管理器工作?
在這一點上,你必須問自己*爲什麼你需要甚至這樣做*? –
@Martijn:用一個自定義類的實例替換一個模塊有時是有用的,因爲它允許做一些常規模塊對象(例如控制屬性訪問)無法做到的事情 - 但是我傾向於同意這樣做,因此模塊可以被用作上下文管理器可能有點兒難。 – martineau
是的,我知道有用例,我不確定這是否是其中之一。 –