Python: Visualise your class hierarchy in UML

Sometimes it's handy to graph out the way your classes are arranged, either for training purposes or simply to help you plan your next move.

There's always the option of doing it manually, or you can use some handy tools to do so.

To get the ball rolling, grab pylint and graphviz

sudo apt-get install graphviz libgraphviz-dev python-dev
pip install pylint pygraphviz

If you don't have python-dev installed, you'll run into the error below:

pygraphviz/graphviz_wrap.c:124:20: fatal error: Python.h: No such file or directory
#include <Python.h>

Now back in your project folder, type:

pyreverse -my -A -o png -p test **/classes.py

Replace "classes.py" with "**.py" if you want all python files.

Another example is if you wanted to graph all the form classes:

pyreverse -my -A -o png -p test **/forms.py

Once it's done, you'll now have classes_test.png and packages_test.png in the folder. The packages image allows you to determine if your code modules are properly decoupled. The classes files shows you how twisted your class inheritance may be.

classes_test

Django models

For Django specific projects, you can install a module called "django_extensions". It also uses graphviz to generate some cool charts but is very Django friendly so you don't have to manually remove Meta classes from your models.

The syntax for graphing models is:

python manage.py graph_models -g -e -l dot -o my_project.png module_a module_b module_c
  • -g groups the models into their respective apps for easier viewing
  • -e shows the inheritance arrows
  • -l uses the "dot" rendering layout by GraphViz (possible values are: twopi, gvcolor, wc, ccomps, tred, sccmap, fdp, circo, neato, acyclic, nop, gvpr, dot, sfdp. I found dot to be the only legible one, and most of them didn't work for me)
  • "-o my_project.png" is the output file
  • module_x includes all the modules which you want to draw

directory_listing

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog