当前位置: 首页 > 工具软件 > goto > 使用案例 >

python中goto的用法_python3里用goto

子车飞鹏
2023-12-01

python里用goto也是小Pa最近做的项目里的一个需求。python不像C有自带的goto, 需要用额外的包,目前为止,小pa只看到2个goto的包:

这2个小Pa都下载试用过,goto因为开发的时候比较早,对于python3的支持不太好,不推荐使用,目前推荐使用goto-statement, 这个project的热度比较低,但是Forks/Stars的比率来说还是不错的。小Pa给它也贡献1颗星,第761颗星星就是小Pa点的啦。goto-statement GitHub statistics

不过,用下来基本的功能还是可以的。

当然,美中不足的是,goto-statement的最新的版本1.2还无法支持动态的计算出的label.

goto-statement的贡献作者Sebastian Noack本人也在和issue的提交者沟通时,做了解释:Thatgoto .foois technical parsed as attribute lookup is an implementation detail, and sincegetattr(goto, 'foo')results into different bytecode (it's a function call, not an attribute lookup on the bytecode-level), it is ignored when the@with_gotodecorator rewrites the bytecode. Furthermore, in order to support calculated jump targets, we'd have to keep a mapping of names and their destination, and resolve them at runtime. This is not supported at the moment, and might be impossible with the current approach, also considering that the bytecode to perform the jump (with the current approach) cannot be any larger than the original bytecode it replaces. However, one workaround would be, generating a string of Python code and usingexec(with_goto(compile(...)))after resolving all labels.

总之,目前想要在python3里实现goto, goto-statement是个不错的选择,如果你有在实践中发现更好的方法,欢迎交流!

 类似资料: