python替代goto_python3里用goto

这篇博客介绍了在Python中实现goto功能的方法,主要探讨了两个第三方库:goto和goto-statement。尽管goto对Python3的支持不佳,但goto-statement作为更优的选择,尽管其最新版本1.2尚不支持动态计算标签。作者Sebastian Noack解释了这一限制,并提出了一种可能的解决途径。如果你在实践中找到了更好的解决方案,欢迎分享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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是个不错的选择,如果你有在实践中发现更好的方法,欢迎交流!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值