Welcome, guest | Sign In | My Account | Store | Cart

The following snippet will dump the module dependencies in a format that can be interpreted by the dot program distributed along with graphviz. You can use it like below to see the dependency graph for the asynchat module for example. (the program is saved as grapher.py)

python grapher.py asynchat | dot -Tpng | display

A screenshot is available here http://twitpic.com/1lqnmh

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sys
import types

visited = set()

def tree(parent, mod, indent = 0):
    print '"%s" -> "%s" ; '%(parent, mod.__name__)
    if mod in visited:
        return
    visited.add(mod)
    for i in dir(mod):
        obj = getattr(mod, i)
        if isinstance(obj, types.ModuleType):
            tree(mod.__name__, obj, indent + 1)

if __name__ == "__main__":
    class Foo: pass
    Foo.__name__ = "Top"
    mod = __import__(sys.argv[1])
    print "Digraph F {"
    tree(Foo, mod)
    print "}"

This kind of thing is useful if you're digging into a large project. You can run this on some top level module and figure out which component in most heavily used and start from there.

That's really just a justification. I did this because I had some free time and it looked like fun.

1 comment

Kent Johnson 13 years, 11 months ago  # | flag

This will not find dependencies from code such as

from foo import bar

because the name "foo" will not be in the module namespace.