python - def next() 适用于 Python pre-2.6? (而不是 object.next 方法)

标签 python next

Python 2.6+ 和 3.* 有 next(),但是 pre-2.6 只提供了 object.next 方法。有没有办法在 pre-2.6 中获得 next() 样式;也许是一些“def next():”结构?

最佳答案

class Throw(object): pass
throw = Throw() # easy sentinel hack
def next(iterator, default=throw):
  """next(iterator[, default])

  Return the next item from the iterator. If default is given
  and the iterator is exhausted, it is returned instead of
  raising StopIteration.
  """
  try:
    iternext = iterator.next.__call__
    # this way an AttributeError while executing next() isn't hidden
    # (2.6 does this too)
  except AttributeError:
    raise TypeError("%s object is not an iterator" % type(iterator).__name__)
  try:
    return iternext()
  except StopIteration:
    if default is throw:
      raise
    return default

(throw = object() 也可以工作,但这会在检查时生成更好的文档,例如 help(next)None 不是合适,因为你必须区别对待 next(it)next(it, None)。)

关于python - def next() 适用于 Python pre-2.6? (而不是 object.next 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1716428/

相关文章:

相当于 JQuery .next() 的 JavaScript

javascript - 具有多个链接的 Accordion

c - gdb 中的 "target record-full"使 "n"命令在带有 "Process record does not support instruction 0xc5 at address 0x7ffff7dee6e7"的 printf 上失败?

Python lxml提取span标签的值

Python Markdown : Markdown Inside HTML Blocks

postgresql - 将记录与postgresql中的先前记录进行比较

python - PyTorch DataLoader() 中的 next() 和 iter() 做了什么

python - 如何在 Pyspark 数据帧中使用列表理解变量名称

python - 在 Python 中使用 prints 创建数据框

python - 连续2次403后如何获取IP地址