python - 跳过 -with- block 的执行

标签 python with-statement skip

我正在定义一个上下文管理器类,如果在实例化过程中满足某些条件,我希望能够跳过代码块而不引发异常。例如,

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...'

最佳答案

根据PEP-343 , with 语句翻译自:

with EXPR as VAR:
    BLOCK

到:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

如您所见,从调用上下文管理器的 __enter__() 方法可以跳过正文(“BLOCK ") 的 with 语句。

人们已经在诸如 withhacks 之类的项目中完成了特定于 Python 实现的事情,例如在 __enter__() 内部操作调用堆栈。 .我记得 Alex Martelli 在一两年前在 stackoverflow 上发布了一个非常有趣的 with-hack(不记得足够多的帖子来搜索和找到它)。

但是对您的问题/问题的简单回答是,您不能做您所要求的事情,跳过 with 语句的主体,而不诉诸所谓的“深度魔法”(这不一定在 python 实现之间可移植) )。使用深奥的魔法,你也许可以做到,但我建议只做一些练习,看看它是如何完成的,而不是在“生产代码”中。

关于python - 跳过 -with- block 的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12594148/

相关文章:

python - 使用 pip 安装 Mayavi - 没有名为 vtk 的模块

python - 有效求和一维 NumPy 数组的外积

python - 通过 api 从树莓派 (DHT22) 收集温度在第二次尝试时失败

python - 在 with 语句外使用 python 变量

c# - Linq + SQLite + Take()==问题

python - Django Form 如果只有一个选项可用,则自动选择第一个选项

python - 我可以从 python 上下文管理器中检索 __exit__ 的返回值吗?

python - 使用Python的 'with open()'写日志,如何将异常写入日志?

python - 以倒计时间隔跳过Python中的迭代

python - 如何通过将某些元素保留在末尾来对Python列表进行排序