Search code examples
pythonwith-statementskip

Skipping execution of -with- block


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. For example,

class My_Context(object):
    def __init__(self,mode=0):
        """
        if mode = 0, proceed as normal
        if mode = 1, do not execute block
        """
        self.mode=mode
    def __enter__(self):
        if self.mode==1:
            print 'Exiting...'
            CODE TO EXIT PREMATURELY
    def __exit__(self, type, value, traceback):
        print 'Exiting...'

with My_Context(mode=1):
    print 'Executing block of codes...'

Solution

  • If you want an ad-hoc solution that uses the ideas from withhacks (specifically from AnonymousBlocksInPython), this will work:

    import sys
    import inspect
    
    class My_Context(object):
        def __init__(self,mode=0):
            """
            if mode = 0, proceed as normal
            if mode = 1, do not execute block
            """
            self.mode=mode
        def __enter__(self):
            if self.mode==1:
                print 'Met block-skipping criterion ...'
                # Do some magic
                sys.settrace(lambda *args, **keys: None)
                frame = inspect.currentframe(1)
                frame.f_trace = self.trace
        def trace(self, frame, event, arg):
            raise
        def __exit__(self, type, value, traceback):
            print 'Exiting context ...'
            return True
    

    Compare the following:

    with My_Context(mode=1):
        print 'Executing block of code ...'
    

    with

    with My_Context(mode=0):
        print 'Executing block of code ... '