manually open context manager

后端 未结 2 1001
离开以前
离开以前 2021-01-13 15:00

My question is, how can I execute any context manager without using with?


Python has the idea of context managers,

instead of



        
2条回答
  •  日久生厌
    2021-01-13 15:12

    You can call app.test_request.context('/?name=Peter') to a variable (e.g. ctx), and then call ctx.__enter__() on it to enter the context manager, and ctx.__exit__(None, None, None) to perform the cleanup. Note that you lose the safety guarantees of context managers, unless you put the ctx.__exit__ in a finally clause.

提交回复
热议问题