Auto Class Diagram In Python

Avi Yeger
2 min readAug 22, 2020

--

Auto class diagram in Python

Class diagram according to Wikipedia is a: “structure diagram that describes the structure of a system by showing the system’s classes, their attributes, operations (or methods), and the relationships among objects.”. It is a good and easy way to dive into a new library. Automatically generate class diagram make sure it is up to date.

TL;DR:

  1. Generate class diagram with pyreverse
  2. View it with graph-easy
  3. Automatically generate it with git hooks
  4. View the diffs with graphdiff

Example

An example of the git-graph-diff-tool can be found in the pylspclient repository:

How to

In order to generate class diagram for a Python library, you can use the pyreverse tool that is now part of pylint. In order to install you follow the README.rst or run the following command:

pip install pylint

After installing it, you can use it with the command:

pyreverse -k -o dot /path/to/library

This will generate class diagram for the library and save it to the file ./classes.dot. It will also create a ./pakcages.dot file, but we won’t talk about it here. The .dot format is a description language for graphs. In order to view it you can use the Graphviz package, or the graph-easy package. We’ll use the later because it supports viewing it in the CLI. In order to install it you can:

sudo apt-get install libgraph-easy-perl

You can view the classes.dot with the command:

cat classes.dot | graph-easy --as boxart

In order to auto generate it for every commit, you can use git hooks. Git hooks enable you to perform something before a git action occur. You can use the pre-commit hook to generate the classes.dot file, and then add it, before the commit is performed.

echo '#!/bin/shpyreverse -o dot ./pylspclient -k
git add ./classes.dot
' >> ./git/hooks/pre-commit
chmod +x ./git/hooks/pre-commit

After you add a couple of commits, you can view the diffs with graphdiff. In order to install you can:

pip install graphdiff

After installing it, you can use the git-graph-diff-tool. It enables to view diffs between .dot files in visual way. First, you need to add to .gitattributes file rules to know how to handle .dot files. For example:

echo "*.dot diff=graph_diff" >> .gitattributes

Then, configure the difftool to be the git-graph-diff-tool. For example:

git config diff.graph_diff.command git-graph-diff-tool

Then, you can use git as usual, while adding –ext-diff flag to enable external difftools.

git log -p --ext-diff

You can see a working example in the pylspclient library.

This posts was originally published in my blog.

--

--