Catching exception in context manager __enter__()

后端 未结 7 1687
栀梦
栀梦 2020-12-08 01:00

Is it possible to ensure the __exit__() method is called even if there is an exception in __enter__()?

>>> class TstCont         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 01:59

    I suggest you follow RAII (resource acquisition is initialization) and use the constructor of your context to do the potentially failing allocation. Then your __enter__ can simply return self which should never ever raise an exception. If your constructor fails, the exception may be thrown before even entering the with context.

    class Foo:
        def __init__(self):
            print("init")
            raise Exception("booh")
    
        def __enter__(self):
            print("enter")
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("exit")
            return False
    
    
    with Foo() as f:
        print("within with")
    

    Output:

    init
    Traceback (most recent call last):
      File "", line 1, in 
      ...
        raise Exception("booh")
    Exception: booh
    

提交回复
热议问题