跳转到主要内容

此包定义了装饰器和IPython魔法,用于显示动态调用图。

项目描述

Latest PyPI Version Documentation Status License Supported Python Versions

Callgraph是一个Python包,它定义了一个装饰器和一个Jupyter魔法,用于绘制Python函数调用的动态调用图

它旨在用于课堂教学,但也可能对自学探索有用。

该包定义了一个Jupyter IPython 魔法,即%callgraph,它可以在Jupyter单元中显示调用图。

from functools import lru_cache

@lru_cache()
def lev(a, b):
    if "" in (a, b):
        return len(a) + len(b)

    candidates = []
    if a[0] == b[0]:
        candidates.append(lev(a[1:], b[1:]))
    else:
        candidates.append(lev(a[1:], b[1:]) + 1)
    candidates.append(lev(a, b[1:]) + 1)
    candidates.append(lev(a[1:], b) + 1)
    return min(candidates)

%callgraph -w10 lev("big", "dog"); lev("dig", "dog")

image0

它还提供了一个Python装饰器,即callgraph.decorator,它将函数工具化以收集调用图信息并渲染结果。

Jupyter / IPython 使用

$ pip install callgraph

在Jupyter IPython笔记本中

%load_ext callgraph

def nchoosek(n, k):
    if k == 0:
        return 1
    if n == k:
        return 1
    return nchoosek(n - 1, k - 1) + nchoosek(n - 1, k)

%callgraph nchoosek(4, 2)

作为在每个使用%callgraph的笔记本中包含%load_ext callgraph的替代方案,您可以将扩展添加到您的IPython配置文件中。

您的配置文件可能被称为~/.ipython/profile_default/ipython_config.py。(您可以通过运行ipython profile locate来找到它。)编辑此文件以包含以下行

c.InteractiveShellApp.extensions = ["callgraph.extension"]

(如果您的配置文件已包含一个未取消注释的语句c.InteractiveShellApp.extensions = […],则编辑该行中的扩展列表以包含"callgraph.extension"。)

请参阅扩展示例笔记本以获取更多示例。

装饰器使用

$ pip install callgraph
from functools import lru_cache
import callgraph.decorator as callgraph

@callgraph()
@lru_cache()
def nchoosek(n, k):
    if k == 0:
        return 1
    if n == k:
        return 1
    return nchoosek(n - 1, k - 1) + nchoosek(n - 1, k)

nchoosek(5, 2)

nchoosek.__callgraph__.view()

有关其他文档,请参阅API文档

请参阅装饰器示例笔记本获取更多说明和示例。

开发

安装开发工具,并为本Python环境设置Jupyter内核

$ pip install -r requirements-dev.txt
$ python -m ipykernel install --user

本地安装

flit install --symlink

致谢

Callgraph使用了Python的graphviz包。Python graphviz使用Graphviz包。

许可证

MIT

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码发行版

callgraph-1.0.0.tar.gz (55.6 kB 查看散列值)

上传时间 源代码

构建发行版

callgraph-1.0.0-py3-none-any.whl (15.4 kB 查看散列值)

上传时间 Python 3

支持者