Python Object Graphs — objgraph 1.7.2 documentation

Python Object Graphs

objgraph is a module that lets you visually explore Python object graphs.

You’ll need graphviz if you want to draw the pretty graphs.

I recommend xdot for interactive use. pip install xdot should suffice; objgraph will automatically look for it in your PATH.

Installation and Documentation

pip install objgraph or download it from PyPI.

Documentation lives at http://mg.pov.lt/objgraph.

Quick start

Try this in a Python shell:

>>> x = []
>>> y = [x, [x], dict(x=x)]
>>> import objgraph
>>> objgraph.show_refs([y], filename='sample-graph.png')
Graph written to ....dot (... nodes)
Image generated as sample-graph.png

(If you’ve installed xdot, omit the filename argument to get the interactive viewer.)

You should see a graph like this:

Backreferences

Now try

>>> objgraph.show_backrefs([x], filename='sample-backref-graph.png')
...
Graph written to ....dot (8 nodes)
Image generated as sample-backref-graph.png

and you’ll see

Memory leak example

The original purpose of objgraph was to help me find memory leaks. The idea was to pick an object in memory that shouldn’t be there and then see what references are keeping it alive.

To get a quick overview of the objects in memory, use the imaginatively-named show_most_common_types():

>>> objgraph.show_most_common_types()
tuple 5224
function 1329
wrapper_descriptor 967
dict 790
builtin_function_or_method 658
method_descriptor 340
weakref 322
list 168
member_descriptor 167
type 163

But that’s looking for a small needle in a large haystack. Can we limit our haystack to objects that were created recently? Perhaps.

Let’s define a function that “leaks” memory

>>> class MyBigFatObject(object):
... pass
...
>>> def computate_something(_cache={}):
... _cache[42] = dict(foo=MyBigFatObject(),
... bar=MyBigFatObject())
... # a very explicit and easy-to-find "leak" but oh well
... x = MyBigFatObject() # this one doesn't leak

We take a snapshot of all the objects counts that are alive before we call our function

>>> objgraph.show_growth(limit=3)
tuple 5228 +5228
function 1330 +1330
wrapper_descriptor 967 +967

and see what changes after we call it

>>> computate_something()
>>> objgraph.show_growth()
MyBigFatObject 2 +2
dict 797 +1

It’s easy to see MyBigFatObject instances that appeared and were not freed. I can pick one of them at random and trace the reference chain back to one of the garbage collector’s roots.

For simplicity’s sake let’s assume all of the roots are modules; if you’ve any examples where that isn’t true, I’d love to hear about them (although see Reference counting bugs).

>>> import inspect, random
>>> objgraph.show_chain(
... objgraph.find_backref_chain(
... random.choice(objgraph.by_type('MyBigFatObject')),
... inspect.ismodule),
... filename='chain.png')
Graph written to ...dot (13 nodes)
Image generated as chain.png

It is perhaps surprising to find linecache at the end of that chain (apparently doctest monkey-patches it), but the important things – computate_something() and its cache dictionary – are in there.

There are other tools, perhaps better suited for memory leak hunting: heapy, Dozer.

Reference counting bugs

Bugs in C-level reference counting may leave objects in memory that do not have any other objects pointing at them. You can find these by calling get_leaking_objects(), but you’ll have to filter out legitimate GC roots from them, and there are a lot of those:

>>> roots = objgraph.get_leaking_objects()
>>> len(roots)
4621
>>> objgraph.show_most_common_types(objects=roots)
...
tuple 4333
dict 171
list 74
instancemethod 4
listiterator 2
MemoryError 1
Sub 1
RuntimeError 1
Param 1
Add 1
>>> objgraph.show_refs(roots[:3], refcounts=True, filename='roots.png')
...
Graph written to ...dot (19 nodes)
Image generated as roots.png

History

I’ve developed a set of functions that eventually became objgraph when I was hunting for memory leaks in a Python program. The whole story – with illustrated examples – is in this series of blog posts:

And here’s the change log

Support and Development

The source code can be found in this Bazaar repository: https://code.launchpad.net/~mgedmin/objgraph/trunk.

To check it out, use bzr branch lp:objgraph.

Report bugs at https://bugs.launchpad.net/objgraph.

For more information, see Hacking on objgraph.

Python Object Graphs — objgraph 1.7.2 documentation的更多相关文章

  1. Odoo8查询产品时提示"maximum recursion depth exceeded while calling a Python object"

    今天在生产系统中查询产品时,莫名提示错误:maximum recursion depth exceeded while calling a Python object,根据错误日志提示,发现在查询产品 ...

  2. scrapy RuntimeError: maximum recursion depth exceeded while calling a Python object 超出python最大递归数异常

    2019-10-21 19:01:00 [scrapy.core.engine] INFO: Spider opened2019-10-21 19:01:00 [scrapy.extensions.l ...

  3. pickle — Python object serialization

    pickle - Python object serialization  消息队列

  4. Python Object Oriented

    1. Creating class class className: 'Optional class documentation string' class_suite The class has a ...

  5. python object对象

    动态语言的对象属性 既然都是动态语言,自然python和熟知的JavaScript很像,建一个空对象用来存放所有的数据,看看js: var data = {}; data.name = 'CooMar ...

  6. [Python] Object spread operator in Python

    In JS, we have object spread opreator: const x = { a: '1', b: '2' } const y = { c: '3', d: '4' } con ...

  7. Commons JXPath - Modifying Object Graphs

    JXPath 除了可以 XPath 语法访问 JavaBeans.DOM/JDOM,也可以对其属性赋值. 以下面的 JavaBeans 为例. package com.huey.jxpath; imp ...

  8. python object takes no parameters

    class Song(object): def __init__(self,lyrics): self.lyrics = lyrics def sing_me_a_song(self): for li ...

  9. python object类

    这个应为写得,写得蛮啰嗦的,建议耐心的人看看:http://www.cafepy.com/article/python_types_and_objects/python_types_and_objec ...

随机推荐

  1. android sdk国内快速更新下载

    Android SDK在线更新镜像服务器 http://www.androiddevtools.cn/ 目前正在使用的是:包含详细的配图流程 http://android-mirror.bugly.q ...

  2. Android TextView(同时显示图片+文字)

    见上图:需要图片和文字 在一起 之前的做法是用两个控件组成 <LinearLayout> <ImageView /> <TextView /> </Linea ...

  3. Windows Phone 8初学者开发—第22部分:用演示图板创建卷盘的动画

    原文 Windows Phone 8初学者开发—第22部分:用演示图板创建卷盘的动画 第22部分: 用演示图板创建卷盘的动画 原文地址:http://channel9.msdn.com/Series/ ...

  4. Swift - 纯代码实现页面segue跳转,以及参数传递

    下面通过一个例子说明如何在代码中进行segue页面的切换,以及参数的传递.   样例功能如下: 1,主界面中是一个列表(这个列表是在代码中实现) 2,点击列表项时,界面会切换到详情页面,同时传递改列表 ...

  5. android软键盘的管理和属性的设置

    android:windowSoftInputMode activity主窗口与软键盘的交互模式,可以用来避免输入法面板遮挡问题,Android1.5后的一个新特性. 这个属性能影响两件事情: [一] ...

  6. 基于visual Studio2013解决C语言竞赛题之1039移动

          题目 解决代码及点评 /* 39. 有n个整数,编程序将前面的各个数依次向后移动k个位置, 最后k个数移到最前边的k个位置(见下图,其中n=8,k=3). */ # ...

  7. memset,memcpy,memmove,strcpy,strcat,strcmp的实现(其实很简单,每个程序都只有几行代码)

    面试中的几个小问题 1.对stl中list封装(参考1): 2.对重要C函数实现(参考2): //memset void *memset(void *buffer, int c, int count) ...

  8. Last_IO_Errno: 1236 Last_IO_Error: Got fatal error 1236 from master when reading data from binary lo

    mysql> show slave status\G *************************** 1. row ***************************         ...

  9. MFC为应用程序添加托盘(右键托盘,弹出菜单)

    源代码:http://download.csdn.net/detail/nuptboyzhb/4137784 1.       导入一个托盘图标的资源(.ico)格式:资源ID为IDI_ICON1 2 ...

  10. 按钮的图标 Button icons-JQUERY MOBILE 1.0正式版中文手册

    按钮的图标 Button icons-JQUERY MOBILE 1.0正式版中文手册 data-icon属性可以被用来创建如下所示的图标 左箭头data-icon="arrow-l&quo ...