在为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子句以正确地重置上下文,而不需要手动更改前面的代码?
目前,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在执行前动态修改脚本的方法在这里是可行的。
发布于 2019-07-21 23:29:46
快速解决方案:
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然后,如果value的某个案例的计算结果为True,则if case(20)将对subvalue采取行动。但是,无法检查是否有任何case调用的计算结果为True。
您可以使用上下文管理器和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??')https://stackoverflow.com/questions/57134270
复制相似问题