manually open context manager

后端 未结 2 982
离开以前
离开以前 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:27

    You can still use with syntax in the interactive console, however a context is based on 2 magic methods __enter__ and __exit__, so you can just use them:

    class MyCtx(object):
      def __init__(self, f):
        self.f = f
    
      def __enter__(self):
        print("Enter")
        return self.f
    
      def __exit__(*args, **kwargs):
        print("Exit")
    
    def foo():
      print("Hello")
    

    usually you do:

    with MyCtx(foo) as f:
      f()
    

    Same as:

    ctx = MyCtx(foo)
    f = ctx.__enter__()
    f() 
    ctx.__exit__()
    

    Here you have the live example

    Remember that contexts __exit__ method are used for managing errors within the context, so most of them have a signature of __exit__(exception_type, exception_value, traceback), if you dont need to handle it for the tests, just give it some None values:

    __exit__(None, None, None)
    

提交回复
热议问题