How to Generate UML Diagrams from Python Source Code?

Your code moves faster than the digrams you created for the documentation. How about a Python tool that you can add to your CI/CD pipeline that generates UML diagram for each version of your code

In spite of designing and thinking through the class structure before coding, developers might have to restructure and refactor the code during implementation. It is also a good idea to generate UML diagrams from code and see if it matches the actual design.

I've explored a variety of code diagram generators, and the one that stood out for me was a Pyreverse example

Pyreverse is a set of utilities to reverse engineering Python code. It uses a representation of a Python project in a class hierarchy which can be used to extract any information (such as generating UML diagrams or unit tests, such as pyargo and py2tests).

The package is now a part of pylint so to install it. You need pylint installed in your python environment.

pip install pylint

Generating UML Diagrams

  1. Let's choose a project; feel free to choose any python project. I'm using Python requests library's source code

git clone <python requests>

2. Create a python virtualenv with pylint installed. Activate the environment.

pip install pylint

3. Use pyreverse command to create the UML diagram image

pyreverse -o png <path_to_src>

The generated image looks something like this. (Click to open)

Last updated