Skipping execution of -with- block

前端 未结 7 1966
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 18:13

    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 ... '
    
    0 讨论(0)
提交回复
热议问题