[問題] 如何強制使用 with statement

看板Python作者 (ResolaQQ)時間9年前 (2015/12/21 10:14), 編輯推噓1(102)
留言3則, 1人參與, 最新討論串1/2 (看更多)
直覺的想法是在 __enter__ 的時候加個變數,執行其他函數的時候檢查,像這樣 class Test(object): def __init__(self): self._with_statement = False def __enter__(self): self._with_statement = True def __exit__(self, type, value, traceback): pass def do_something(self): assert(self._with_statement) 如此一來,如果沒用到 with statement,執行任何函數都會出錯 但是這寫法怎麼看怎麼蠢,也有漏寫 assert 的可能 請問有沒有比較好的寫法,既可以做到使用者防呆也能做到開發者防呆? -- 放著養蚊子的部落格 http://resolaqq.blogspot.tw -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.165.73.83 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1450692859.A.86C.html

12/21 22:24, , 1F
我覺得這樣挺好的啊
12/21 22:24, 1F

12/21 22:25, , 2F
另外如果沒有assert也不會出錯的話,又何必非要逼人用wi
12/21 22:25, 2F

12/21 22:25, , 3F
th?
12/21 22:25, 3F
文章代碼(AID): #1MTz3xXi (Python)
文章代碼(AID): #1MTz3xXi (Python)