python - 如何检测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 在执行前动态修改脚本的方法在这里是可行的。
解决方案
快速解决:
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)
将采取行动。但是,无法检查是否有任何调用被评估为。value
subvalue
True
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??')
推荐阅读
- c# - 创建 .net core 3.0 类库问题
- java - Is it true to say that every run time binding was a static binding during compilation?
- c++ - C++ 宏解包并加入
- c# - 实体框架执行功能不起作用
- doctrine-orm - 向 Doctrine QueryBuilder 的 where-in-clause 添加条件
- python - 如何保存一个热编码器?
- sql - 具有完整详细信息的 PostgreSQL 错误处理
- git - `.gitmodules` 中的 `[submodule "(heads/master)"]` 是什么?
- react-native - 使用 toast 进行第二次后按后退出应用程序
- logging - 从 Kubernetes 记录到文件