Python 2.6 之前版本的 def next() ? (而不是 object.next 方法)
Python 2.6+ 和 3.* 有 next(),但 2.6 之前的版本仅提供 object.next 方法。有没有办法在2.6之前获得next()样式;也许是一些“def next():”构造?
Python 2.6+ and 3.* have next(), but pre-2.6 only offers the object.next method. Is there a way to get the next() style in pre-2.6; some "def next():" construction perhaps?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(
throw = object()
也可以,但是这在检查时会生成更好的文档,例如help(next)
。None
不合适,因为您必须以不同的方式对待next(it)
和next(it, None)
。)(
throw = object()
works too, but this generates better docs when inspecting, e.g.help(next)
.None
is not suitable, because you must treatnext(it)
andnext(it, None)
differently.)R. Pate 似乎有一个很好的答案。需要额外补充一点:如果您正在编写在许多不同版本的 Python 上运行的代码,您可以对定义进行条件化:
这样您在任何情况下都定义了
next
,但您使用的是内置实现(如果可用)。我使用
next = next
以便可以将此定义放入模块中,然后在代码的其他位置使用:R. Pate seems to have a good answer. One extra bell to add: if you're writing code to run on many different versions of Python, you can conditionalize the definition:
That way you have
next
defined in any case, but you're using the built in implementation where it's available.I use
next = next
so that I can put this definition in a module, then elsewhere in my code use:更简单的方法:
Ned 关于将其放入
try
块的建议在这里也适用,但如果您打算走这条路,请注意一点:在 Python 3 中,调用next()非迭代器上的
会引发TypeError
,而此版本会引发AttributeError
。编辑:没关系。正如 steveha 指出的,operator.methodcaller() 是在 2.6 中才引入的,这很遗憾。
Simpler method:
Ned's suggestion about putting it in a
try
block works here as well, but if you're going to go that route, one minor note: in Python 3, callingnext()
on a non-iterator raises aTypeError
, whereas this version would raise anAttributeError
instead.Edit: Never mind. As steveha points out,
operator.methodcaller()
was only introduced in 2.6, which is a shame.