Skip to content

Instantly share code, notes, and snippets.

@mrocklin
Created August 12, 2012 14:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrocklin/3332164 to your computer and use it in GitHub Desktop.
Save mrocklin/3332164 to your computer and use it in GitHub Desktop.
A small program to look through a Python source directory, pull out the class hierarchy, and generate a .dot file. It also produces a .pdf file using the dot program.
#!/usr/bin/python
import re
import networkx as nx
import os
prog = re.compile("class (?P<subclass>\w+)\((?P<superclasses>[\s\w,]+)\):")
def grep_stream(location):
return os.popen(
'find %s -name "*.py" | xargs grep -h "^class \w*\([\w\s][\s\w,]*\)"'%location)
def nx_from_stream(f):
assert isinstance(f, file)
G = nx.DiGraph()
for line in f:
match = prog.match(line)
if not match:
continue
subclass = match.groupdict()['subclass']
for superclass in match.groupdict()['superclasses'].split(','):
G.add_edge(superclass.strip(), subclass)
return G
if __name__ == "__main__":
from sys import argv, exit
if len(argv) == 3:
location, name = argv[1:]
else:
print "Usage:\n%s sympy/core/ core\nevince core.pdf"%argv[0]
exit()
stream = grep_stream(location)
G = nx_from_stream(stream)
Gpd = nx.to_pydot(G)
Gpd.set_rankdir("LR")
Gpd.set_overlap("false")
Gpd.write("%s.dot"%name)
os.system("dot -Tpdf %s.dot -o %s.pdf"%(name, name))
@mrocklin
Copy link
Author

To produce a dot file this requires:

  • Standard Unix utilities find, xargs, grep
  • python libraries networkx, pydot

To produce a pdf this requires

  • dot (the graphvis executable)

@mrocklin
Copy link
Author

Here are some examples of the sympy code repository

@mrocklin
Copy link
Author

Here are some examples of the sympy code repository

(the previous link was relative)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment