похоже, нашел один способ
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
with My_Context(mode=1):
print 'Executing block of code ...'
написан на 2 питоне, но на 3 должно быть легко переписать.
mode=1 игнорирует выполнение тела with блока.
Кстати, советуют не использовать такое.
UPD:
вариант для python3
import sys
class SkipWithBlock(Exception):
pass
class SkipContextManager:
def __init__(self, skip = True):
self.skip = skip
def __enter__(self):
if self.skip:
sys.settrace(lambda *args, **keys: None)
frame = sys._getframe(1)
frame.f_trace = self.trace
def trace(self, frame, event, arg):
raise SkipWithBlock()
def __exit__(self, type, value, traceback):
if type is None:
return # No exception
if issubclass(type, SkipWithBlock):
return True # Suppress special SkipWithBlock exception
with SkipContextManager():
print('In the with block') # Won't be called
print('Out of the with block')