Python next()function

iterator, next()function
我想知道python的built-in function next()的实现源码, 以及用vscode如何查询其实现源码。

next()是python的内置函数,不同的python实现源码也不一样,可以看看官方的实现cpython的源码,底层是用C实现的。next函数的实现源码在这个源文件中https://github.com/python/cpython/blob/main/Python/bltinmodule.c

C函数builtin_next

img

将C函数builtin_next映射为python内置函数next,后面的next_doc是对next的注释,也是在这个文件中定义的

img

next函数的注释next_doc,在IDE(VSCode、PyCharm等)中对next按Ctrl+鼠标点击跳转后显示的next函数的文档字符串就是从这里来的

img

img

装一个Pylance插件。

  1. 如果是windows系统,按住Ctrl键 + 鼠标点击待查看的方法或者类名

  2. 如果是mac系统,按住Command键 + 鼠标点击待查看的方法或者类名

需要安装Pylance插件,然后就可以像pycharm那样,按着ctrl+鼠标点击代码中药查看的位置,就可以看到了。



def next(iterator, default=None): # real signature unknown; restored from __doc__
    """
    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.
    """
    pass

函数必须接收一个可迭代对象参数,每次调用的时候,返回可迭代对象的下一个元素。如果所有元素均已经返回过,则抛出StopIteration 异常。
next()函数不断调用并返回下一个值