Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检测if语句何时退出_Python_Python 3.x - Fatal编程技术网

Python 如何检测if语句何时退出

Python 如何检测if语句何时退出,python,python-3.x,Python,Python 3.x,在为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

在为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语句的exit子句以正确重置上下文,而无需手动更改此正向代码

开关/外壳功能的代码目前非常基本:

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在执行前动态修改脚本的方法。

快速修复:

elif case( 20 ): # this shouldn't execute (workaround: place this above case(10))
    pass
另一种可能的解决方案是将
上下文
作为堆栈:

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

def case(*args):
    ret = context[-1] in args
    if ret:
        context.pop()
    return ret
然后,
if case(20)
将作用于
,如果
子值
的一个案例评估为
。但是,无法检查是否有任何
案例
调用的计算结果为

您可以使用上下文管理器和
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??')

你能发布
案例
开关
的代码吗?目前,它基本上只是设置了一个相对的上下文变量,但好吧,给我一点时间。这是一个很难解决的问题。。。不确定python中是否内置了类似的内容,if块甚至不是它自己的作用域,if块内部声明的变量在外部仍然有效。。。在其他语言中,我会说“have switch是一个宏,它创建一个本地对象,并且通过析构函数调用得到if子句的结尾”,但这不适用于python……如果处理上下文,可能需要一个上下文管理器(一个实现
\uuuuuuuuuuuuuuuuuuuuuuuuu
\uuuuuuuuuuu
方法的类)。然后您可以将上下文存储在此类中并对其进行操作。@ForceBru问题在于需要使用开关(…):这看起来与其他人所期望的完全不同。虽然可以使用ast动态执行,但在上下文中插入case仍然非常困难。我知道我遗漏了一些非常简单的东西,我怎么可能遗漏case函数中的if语句,谢谢:)