这个包定义了装饰器和 IPython 魔术来显示动态调用图。
项目描述
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")
它还提供了一个 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 调用图的替代方法,您可以将扩展添加到 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包。
执照
麻省理工学院
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。
源分布
callgraph-1.0.0.tar.gz
(55.6 kB
查看哈希)
内置分布
callgraph-1.0.0-py3-none-any.whl
(15.4 kB
查看哈希)