首页 > 解决方案 > 如何检测if语句何时退出

问题描述

因此,在为 python 编写干净的 switch/case 语句之后,我一直在解决这个问题。

我遇到的问题是嵌套上下文泄漏:

value = 10

switch( value ) # sets context result to 10

if case( 10 ):

    subvalue = 20

    switch( subvalue ) # changes context result from 10 to 20

    if case( 5 ):
        pass

    if case( 15, 20 ):
        pass

if case( 20 ): # this shouldn't execute (workaround: place this above case(10))
    pass

如何自动检测 if 语句的退出子句以正确重置上下文而无需手动更改此前端代码?

switch/case 函数的代码目前非常基础:

class Null(object): pass

context = [Null()] # avoids error cases

def switch( test ): context[0] = test

def case( *comparators ): return context[0] in comparators

注意:需要 ast 或 dis/inspect 在执行前动态修改脚本的方法在这里是可行的。

标签: pythonpython-3.x

解决方案


快速解决:

elif case( 20 ): # this shouldn't execute (workaround: place this above case(10))
    pass

另一种可能的解决方案是制作context堆栈:

def switch(test):
    context.append(test)

def case(*args):
    ret = context[-1] in args
    if ret:
        context.pop()
    return ret

如果其中一种情况评估为,然后if case(20)将采取行动。但是,无法检查是否有任何调用被评估为。valuesubvalueTruecaseTrue

您可以使用上下文管理器解决此问题,并且elif

def case(*args):
    ...

class switch:
    def __init__(self, variable):
        self.variable = variable

    def __enter__(self):
        global case
        case = self.case

    def __exit__(self, *args):
        # Don't forget to clean up
        global case
        def case(*args):
            ...

    def case(self, *args):
        return self.variable in args

with switch(6):
    if case(5):
        print('five')
    elif case(6, 7):
        print('six or seven')
    else:
        print('what is this??')

推荐阅读