Skipping execution of -with- block

前端 未结 7 1976
Happy的楠姐
Happy的楠姐 2020-12-02 17:22

I am defining a context manager class and I would like to be able to skip the block of code without raising an exception if certain conditions are met during instantiation.

7条回答
  •  爱一瞬间的悲伤
    2020-12-02 17:50

    Based on @Peter's answer, here's a version that uses no string manipulations but should work the same way otherwise:

    from contextlib import contextmanager
    
    @contextmanager
    def skippable_context(skip):
        skip_error = ValueError("Skipping Context Exception")
        prev_entered = getattr(skippable_context, "entered", False)
        skippable_context.entered = False
    
        def command():
            skippable_context.entered = True
            if skip:
                raise skip_error
    
        try:
            yield command
        except ValueError as err:
            if err != skip_error:
                raise
        finally:
            assert skippable_context.entered, "Need to call returned command at least once."
            skippable_context.entered = prev_entered
    
    
    print("=== Running with skip disabled ===")
    with skippable_context(skip=False) as command:
        command()
        print("Entering this block")
    print("... Done")
    
    print("=== Running with skip enabled ===")
    with skippable_context(skip=True) as command:
        command()
        raise NotImplementedError("... But this will never be printed")
    print("... Done")
    
    

提交回复
热议问题