with 语句 - Python 2.5 的向后移植
我想在一些生产代码中使用 Python 2.5 中的 with
语句。它被向后移植,我应该期待任何问题(例如其他机器上的可用性/兼容性/等)吗?
此代码
from __future__ import with_statement
与 Python 2.6 兼容吗?
I'd like to use with
statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)?
Is this code
from __future__ import with_statement
compatible with Python 2.6?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,该语句在 Python 2.6 中是无操作的,因此您可以自由地使用它在 2.5 代码中使
with
成为关键字,而不会影响代码在 2.6 中的操作。这其实就是Python“从未来导入”的总体设计意图!Yes, that statement is a no-operation in Python 2.6, so you can freely use it to make
with
a keyword in your 2.5 code as well, without affecting your code's operation in 2.6. This is in fact the general design intention of "importing from the future" in Python!您可以在 Python 2.6 和 3.0/1 中毫无问题地调用它(那里是无操作的)。
You can call this in Python 2.6 and 3.0/1 without problems (it's a no-op there).
with_statement 没有向后移植,而是在 Python 2.5 中实现。添加新的关键字或语法可能会破坏现有的应用程序。对于 Python,他们决定处理这个问题的方式是允许人们尽早选择使用这些功能,这样你就可以慢慢地过渡你的代码。
来自 http://python.org/doc/2.5.2/ref/future .html
实际上,您可以检查 futures 以获取有关何时首次支持、何时不再需要导入等信息。
我个人已经在 Python 2.5 中大量使用 with_statement 一年多了,并且没有遇到任何问题。我还使用 Python 2.6 透明地运行该代码。他们在语言中清理了一些奇怪的极端情况,主要与干净、正确地压缩嵌套语句有关。
with_statement wasn't back ported but implemented in Python 2.5. Adding new keywords or syntax can break existing applications. With Python the way they decided to handle this is allow people to opt-in to those features early so you can slowly transition your code over.
From http://python.org/doc/2.5.2/ref/future.html
You can actually inspect futures to get information on when first supported, when the import isn't needed anymore, etc.
I personally have been heavily using the with_statement in Python 2.5 for well over a year and have not had issues. I also transparently run that code with Python 2.6. There are some weird corner cases they have worked at cleaning up in the language, mostly related to cleanly and correctly compacting nested with statements.