Class diagrams and flowcharts are very useful tools when designing programs. We have many tools to draw these drawings and even use them to generate the most basic framework code. Sometimes we need to reverse the code we have written into class diagrams, flow charts, such as when writing homework and sharing design with others.

There are also many tools for Code transformation diagrams, such as VS Code, IntelliJ IDEA and other common ides that can be installed with plug-ins to do the job. And if you do Microsoft development, Visual Studio’s optional installation of “class Designer” is unbelievably strong, easily beat any other similar tool I’ve seen, in this respect, VS deserves the title of “the universe’s first IDE.”

The code-to-code flow chart, however, has relatively few requirements and fewer tools. Recently, I had a sudden need to turn some Python code into a flow chart. Google turned two pages and GitHub did a search for several projects, and none of the existing implementations worked: Either the techniques are too weird (the ones on the front of “regular expressions” shocked me all afternoon), they don’t work (depending on conditions, such as the macOS-unfriendly PyGame for some projects), or they’re too ugly (messy lines, strange colors, not new ugly, just ugly). When I saw Vatsha/ CODE_to_flowchart of a highly acclaimed project, and so many of the three “merits” mentioned above, I chose flowchart of Python and workflow by myself.

Of course, I’m not saying that other people’s projects are not good, but some of the details are really not good, I think there is room for improvement. But it has to be said that some of the designs are simple and effective, and they are illuminating. Vatsha/ CODE_to_Flowchart and PyGame are creative and visually useful. In fact, I’ve made a lot of references to other big names for my own implementation.

Python code transfer flowchartPyFlowchart

My solution is PyFlowchart; it’s based on well-known flowchart.

(Originally called PyFlow, I uploaded PyPi with the same name 🤦♂️. PyFlowchart

flowchart.js

If you use Typora, you probably know that Flow in Typora can write flowcharts with a simple flowsheet language. According to Typora’s documentation, this function comes from flowflow.js, which is open source.

My solution is to take Python code and put it into this flowchart language, and you can produce flowcharts by using flowchart.js.org, Typora, Francolaberge/Diagrams, and so on.

st=>start: Start
op=>operation: Your Operation
cond=>condition: Yes or No?
e=>end

st->op->cond
cond(yes)->e
cond(no)->op
Copy the code

PyFlowchart

Here is a brief description of how to use PyFlowchart I realized. See the README of the project for more details.

Install PyFlowchart:

$ pip3 install pyflowchart
Copy the code

Write a simple.py file:

def foo(a, b) :
    if a:
        print("a")
    else:
        for i in range(3) :print("b")
    return a + b
Copy the code

Running PyFlowchart.

$ python3 -m pyflowchart simple.py
Copy the code

It outputs flowchart code:

st4439920016=>start: start foo
io4439920208=>inputoutput: input: a, b
cond4439920592=>condition: if a
sub4439974736=>subroutine: print('a')
io4439974672=>inputoutput: output:  (a + b)
e4439974352=>end: end function return
cond4439974224=>operation: print('b') while  i in range(3)

st4439920016->io4439920208
io4439920208->cond4439920592
cond4439920592(yes)->sub4439974736
sub4439974736->io4439974672
io4439974672->e4439974352
cond4439920592(no)->cond4439974224
cond4439974224->io4439974672
Copy the code

Go to flowchart.js.org and paste the code generated above into the text box. The flowchart will be generated automatically on the right:

Of course, you can also put this code directly into Typora’s Flow code block, which will also generate the flow chart automatically. If you prefer to use the command line, you can also use francoislaberge/diagrams to generate flow charts.

If the flowchart is not satisfactory (for example, lines overlap) or you like to specify a flowchart, it is easy to manually modify flowchart by referring to flowchart.js.org.

Realize the principle of

st=>start: start PyFlowchart
in=>inputoutput: input python source code
sub1=>subroutine: code to ast
sub2=>subroutine: ast to node graph
sub3=>subroutine: node graph to flowchart
out=>inputoutput: output flowchart
e=>end: end

st->in->sub1(right)->sub2(right)->sub3->out->e
Copy the code

PyFlowchart uses Python’s Built-in AST package to transform code into a flowchart (AST). Then, the AST is transformed into a flowchart of its own definition, and each Node represents a flowchart of each member. Walk through the diagram to get the flow chart.

For the AST package, check out this article: AST Modules: Modifying Python code in Python, which is very old, but very easy to understand. In summary, using the AST package, we can turn a piece of Python code into a data structure:

>>> import ast
>>> expr = "" ".def add(a, b):
.    return a + b
."" "
>>> expr_ast = ast.parse(expr)
>>> expr_ast
<_ast.Module object at 0x10c773e10>
>>> ast.dump(expr_ast)
# P.S. manually formatted here
Module(body=[FunctionDef(name='add',
  args=arguments(
    args=[
      arg(arg='a', annotation=None),
      arg(arg='b', annotation=None)],
    vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]),
  body=[Return(value=BinOp(
    left=Name(id='a', ctx=Load()),
    op=Add(),
    right=Name(id='b', ctx=Load())))],
  decorator_list=[],
  returns=None)])
Copy the code

After learning this, the next step is to translate the expr_ast (_ast.module object) into a flow chart. We do this in an object-oriented way:

Node is the most basic class, representing a Node in the flowchart from which everything else is inherited. A Node has attributes such as Node type, name, and content. The fc_definition() and fc_Connection () methods provided by a Node can turn each Node into a flowchart string. The other __visited and _traverse() are used to traverse the map. In relation to node types in Flowchart, we have realized various subcategories of node: StartNode, EndNode and OperationNode……

NodesGroup is a special Node; it does not appear in the flowchart that is produced, but it can contain a flowchart of some other nodes. This design is inspired by Android’s View and ViewGroup. With the NodesGroup, if statements and for/while loops, it’s easy to handle cases with nested bodies.

AstNode represents a Node obtained from an AST object. To construct an AstNode, you translate an AST object into a Node (or NodesGroup). Subclasses correspond to the various AST objects (and thus Python statements) : If, Loop, Return…….

Flowchart stands for a Flowchart. Flowchart is a bunch of interconnected nodes; so Flowchart is a subclass of No flow group. In its from_code() method, it implements the work of using the AST package to parse Python code and get the AST object. In the Flowchart () method, the diagram is traversed, and all nodes are workflow diagram and summarized into a flowchart diagram.

In fact, this thing is very simple, more specific implementation to see the source code is very well understood, do not repeat here. To summarize:

  • Code to AST is realized by using AST Flowchart;
  • AstNode and its subclasses implement the AST to node graph.
  • Node and its subclasses realize Node graph and flowchart.

Finally, attach the project address again with a class diagram of the full implementation:

  • Github.com/cdfmlr/pyfl…

by('CDFMLR'.'2020.10.24')
# 🎉
Copy the code

Update 2021.07.22: It has been a long time since this paper was first released, and PyFlowchart has been repaired and improved greatly. Check out The README on GitHub for a more detailed description of PyFlowchart.

At the same time, WE hope that everyone can participate in PyFlowchart development and welcome any workflow related issues and PR; especially, we hope that there are leaders who can solve TODO’s work.