如何在 Jupyter 笔记本中转到函数的定义?

Gul*_*zar 9 python jupyter-notebook

我如何去 Jupyter 中的函数定义?

我想要像 Visual Studio 的 f12,或 eclipse 和 PyCharm 的 ctrl+click 之类的东西。

我很难相信这不存在,但找不到它

Kam*_*ski 8

我不知道这种功能适用于所有内核。

如果您使用的是 Python 内核并安装了 ipython,则可以使用检查功能:

  • %pdoc <object>:打印(如果太长,则通过寻呼机运行)对象的文档字符串。如果给定的对象是一个类,它将打印类和构造函数文档字符串。
  • %pdef <object>:打印任何可调用对象的调用签名。如果对象是类,则打印构造函数信息。
  • %psource <object>:打印(如果太长,则通过寻呼机运行)对象的源代码。
  • %pfile <object>:显示通过分页器定义对象的整个源文件,在对象定义开始的行打开它。
  • %who/%whos:这些函数提供有关您以交互方式定义的标识符的信息(不是您在配置文件中加载或定义的内容)。%who 只打印一个标识符列表,%whos 打印一个表格,其中包含有关每个标识符的一些基本详细信息。

键入??wordword??提供对完整信息的访问权限,包括可能的源代码。长字符串不会被剪断。

使用示例

In [4]: pd.DataFrame?

In [5]: pd.DataFrame??

In [6]: %pdef pd.Dataframe
Object `pd.Dataframe` not found.

In [7]: %pdef pd.DataFrame
Class constructor information:
 pd.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

In [8]: %pdoc pd.DataFrame

In [9]: %pfile pd.DataFrame
Run Code Online (Sandbox Code Playgroud)

资源

动态对象信息


kra*_*ski 6

如果您可以升级到 JupyterLab,则可以使用以下命令安装jupyterlab-go-to-definition扩展:

jupyter labextension install @krassowski/jupyterlab_go_to_definition
Run Code Online (Sandbox Code Playgroud)

它支持 R 和 Python,并允许使用 alt 单击跳转到定义(其中 alt 可以更改为设置中的另一个键修饰符)。有关更多使用详细信息,请参阅链接的 GitHub 存储库(上图)。

在技​​术方面,有两种方法可以获取笔记本中定义的位置:静态分析和内核中的检查。如果您还不能升级到 JupyterLab,您可以尝试为 jupyter-notebook 重新实现其中任何一个。

  • 内核检查似乎更容易实现,因为它们不依赖于所使用的代码编辑器,而是必须为每种语言单独编写。是 Python 的示例
  • static analysis can be done via external tool but those will be problematic due to the nature of the notebook (being composed of multiple cells, unlike normal source code files); the approach used in the extension above is to analyze the tokens of CodeMirror editor, iterating over cells, starting from the cell with the symbol usage (where the user alt-clicked on a variable). Here is an example of implementation for such iteration.

Disclaimer: I am the author of this extension.

Edit: For an implementation which allows the same for any language (provided that you install a language server for this language), see: jupyterlab-lsp (with many other features too!). The difference is that it only uses static analysis for now (the kernel-based position retrieval is not implemented just yet).