python3 使用 goto 跳转执行指定代码行
1. 缘起
在实际开发中遇到这样一个问题:
以下是伪代码
if embedding.model is not exist:
calculate embedding ## moudel_1
save embedding.model
else :
embedding = load embedding.model
try:
use embedding
except KeyError:
calculate embedding ##这里与moudel_1一致。
发现except 中需要粘贴之前写过的calculate embedding
简单概括就是:
somecode_1
try:
somecode_2
except:
somecode_3
somecode_1 ## 重新执行
2. 使用goto
(1)安装goto
pip install goto-statement
(2)使用goto完成一个小例子
官方文档见:https://pypi.org/project/goto-statement/
定义函数
from goto import with_goto
@with_goto #必须有
def test(list_):
tmp_list = list_
label.begin #标识跳转并开始执行的地方
result = []
try:
for i, j in enumerate(list_):
tmp = 1 / j
result.append(tmp)
last_right_i = i
except ZeroDivisionError:
del tmp_list[last_right_i + 1]
goto.begin #在有跳转标识的地方开始执行
return result
运行
a = test([1, 3, 4, 0, 6])
print(a)
结果
[1.0, 0.3333333333333333, 0.25, 0.16666666666666666]
注意:如果你在ide山运行label 和 goto 下有红色波浪线提示错误。不用理会直接执行即可