• Stars
    star
    305
  • Rank 136,073 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python codes to Flowcharts

PyFlowchart

English | 机翻中文

PyFlowchart is a Python package that lets you:

  • Write flowcharts in Python.
  • Translate Python source code into flowcharts.

PyFlowchart produces flowcharts in the flowchart.js flowchart DSL, a widely used textual representation of flowcharts. You can convert these flowcharts to images using flowchart.js.org, francoislaberge/diagrams, or some markdown editors.

Get PyFlowchart

$ pip install pyflowchart

Quick Start

Want to flowchart your Python code in example.py? Run this:

$ python -m pyflowchart example.py

⚠️ PyFlowchart works with Python 3.7+. To check your Python version, run python --version.

If you have both Python 2 and Python 3 installed, you may need to use python3 instead of python. This is becoming less common as Python 2 is sunsetting.

PyFlowchart will output the generated flowchart.js DSL. You can convert the output code to a rendered diagram by going to http://flowchart.js.org or using editors like Typora.

To specify a function (or a method in a class) to flowchartlize:

  • Use the -f flag to specify the function or method name.
$ python -m pyflowchart example.py -f function_name
# or
$ python -m pyflowchart example.py -f ClassName.method_name

For example, to flowchartlize the add() function in the MyClass class, you would use the following command: python3 -m pyflowchart example.py -f MyClass.add.

🎉 Now you are ready to flowchart your code!

To learn more about how to use PyFlowchart, keep reading this document.

Flowchart in Python

PyFlowchart lets you write flowcharts in Python, which can be automatically translated into the flowchart.js DSL.

The following flowchart.js node types are supported:

  • StartNode
  • OperationNode
  • ConditionNode
  • InputOutputNode
  • SubroutineNode
  • EndNode

To connect nodes, use the connect() method. For ConditionNodes, use the connect_{yes|no} syntax. You can optionally specify the connect_direction as a second parameter.

Get a Flowchart with your start node and call its flowchart() method to generate flowchart.js flowchart DSL:

from pyflowchart import *

st = StartNode('a_pyflow_test')
op = OperationNode('do something')
cond = ConditionNode('Yes or No?')
io = InputOutputNode(InputOutputNode.OUTPUT, 'something...')
sub = SubroutineNode('A Subroutine')
e = EndNode('a_pyflow_test')

st.connect(op)
op.connect(cond)
cond.connect_yes(io)
cond.connect_no(sub)
sub.connect(op, "right")  # sub->op line starts from the right of sub
io.connect(e)
 
fc = Flowchart(st)
print(fc.flowchart())

Output:

st0=>start: start a_pyflow_test
op1=>operation: do something
cond2=>condition: Yes or No?
io3=>inputoutput: output: something...
e5=>end: end a_pyflow_test
sub4=>subroutine: A Subroutine

st0->op1
op1->cond2
cond2->
cond2->
cond2(yes)->io3
io3->e5
cond2(no)->sub4
sub4(right)->op1

Then you can visit http://flowchart.js.org and translate the generated textual representation into SVG flow chart diagrams:

screenshot on flowchart.js page

By the way, many Markdown editors, like Typora, also support this flowchart syntax. For more information, see the Typora documentation on flowcharts. If you prefer the command line, you can use francoislaberge/diagrams.

Set Params to Nodes

Starting with v0.2.0, you can use the Node.set_param(key, value) method to generate flowcharts like this:

element(param1=value1,param2=value2)=>start: Start

(See also adrai/flowchart.js#node-specific-specifiers-by-type)

There is also a shortcut to set the align-next=no parameter for ConditionNodes:

cond = ConditionNode("a cond node")
cond.no_align_next()
# or do this at __init__:
cond = ConditionNode("a cond node", align_next=False)

This usually works with a connect_direction customization:

cond.connect_yes(op, "right")

The generated flowchart will look like:

cond(align-next=no)=>condition: Yes or No?
...
cond(yes,right)->op

Python to Flowchart

PyFlowchart can also translate your Python code into flowcharts.

For example, let's say you have a Python file called simple.py with the following code:

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

To generate a flowchart from this code, you can run the following command in the terminal:

$ python -m pyflowchart simple.py

# output flowchart code.

Or, in Python:

>>> from pyflowchart import Flowchart
>>> with open('simple.py') as f:
...     code = f.read()
... 
>>> fc = Flowchart.from_code(code)
>>> print(fc.flowchart())

# output flowchart code.

simple.py to flowchart

Advanced Usages

As mentioned above, we use Flowchart.from_code to translate Python codes into Flowcharts. The from_code is defined as:

Flowchart.from_code(code, field="", inner=True, simplify=True, conds_align=False)
  • code: The Python code to be converted into a flowchart.
  • field: The name of a field in the code to be converted into a flowchart. If this parameter is not specified, the entire code will be converted.
  • inner: If True, the body of the field will be parsed as a nested flowchart. If False, the body of the field will be parsed as a single node.
  • simplify: If True, simple If and Loop statements will be simplified. For example, an If statement with a single expression will be converted into a single node.
  • conds_align: If True, consecutive If statements will be aligned in the flowchart.

PyFlowchart CLI is a 1:1 interface for this function:

python -m pyflowchart [-f FIELD] [-i] [--no-simplify] [--conds-align] code_file
  • -f FIELD: The name of the field to be converted into a flowchart.
  • -i: If specified, the body of the field will be parsed as a nested flowchart.
  • --no-simplify: If specified, the If and Loop statements will not be simplified.
  • --conds-align: If specified, consecutive If statements will be aligned in the flowchart.

field

the field is the path to a field (i.e. a function) you want to draw a flowchart.

# example.py
print("start")

def foo():
    foo = "foo"

class Bar():
    def buzz(self, f):
        def g(self):
            print("g")
            f(self)
        return g(self)

Bar().buzz(foo)
print("end")

For example.py above, available paths are:

- "" (means the whole code)
- "foo"
- "Bar.buzz"
- "Bar.buzz.g"

To generate a flowchart of Bar.buzz.g

# Python
from pyflowchart import Flowchart
with open('example.py') as f:
	code = f.read()
fc = Flowchart.from_code(code, field='Bar.buzz.g', inner=False)
print(fc.flowchart())

Or:

# CLI
python -m pyflowchart example.py -f Bar.buzz.g

Output result:

specify a field

inner

The inner parameter controls how the parser behaves. If inner=True, the parser will look into the field and parse its body. If inner=False, the parser will take the field as a single node.

pyflowchart_inner

In CLI, the -i argument sets inner=True. The absence of -i argument implies inner=False.

🔧 For developers: Techly, inner=True means parsing field.body, while inner=False parses [field].

simplify

The simplify parameter controls whether to simplify If and Loop statements. When simplify=True, an If or Loop statements with one-line-body will be simplified into a single node.

For example, the following code:

# example_simplify.py
a = 1
if a == 1:
    print(a)
while a < 4:
    a = a + 1

Would be converted into the following flowchart when simplify=True :

flowchart = Flowchart.from_code(example_simplify_py, field="", inner=True)
print(flowchart.flowchart())
# SH $ python -m pyflowchart example_simplify.py 

simplify result

And with simplify=False:

flowchart = Flowchart.from_code(example_simplify_py, field="", inner=True, simplify=False)
print(flowchart.flowchart())
# SH $ python -m pyflowchart --no-simplify example_simplify.py 

no simplify result

conds-align (Beta)

The conds-align parameter controls whether consecutive If statements are aligned in the flowchart. When conds-align=True, consecutive If statements are aligned in the flowchart.

# example-conds-align.py
if cond1:
	op1
if cond2:
	op2
if cond3:
	op3
op_end

conds-align-result

Note: This feature is still in beta and may not work perfectly in all cases.

Beautify Flowcharts

The flowcharts generated by PyFlowchart may not always be perfect. In these cases, you can modify the generated flowchart code yourself or consider making your Python source code more clear. Clear and beautiful Python source code will result in more beautiful flowcharts generated by PyFlowchart.

TODOs

  • Directly generate flowchart SVG/HTML:
$ pyflowchart example.py -o flowchart.svg

Depends on node.js and flowchart.js.

  • PyFlowchart GUI

A GUI for PyFlowchart would be amazing. You could paste your Python code into it, and the flowchart DSL would be generated in real time, with the flowchart displayed alongside it. You could clearly see how the two are related.

  • The Chinese README your buddies waiting for! 希望有同学帮助贡献个中文 README 呀。
  • Tests automation.

Unfortunately, I am too busy (pronounced as [ˈlеizi]——lazy) to code these ideas myself. Please submit an issue to push me on. Or, PR to make it by yourself. I cannot wait to appreciate your great contribution!

References

License

Copyright 2020-2023 CDFMLR. All rights reserved.

Licensed under the MIT License.

More Repositories

1

muvtuber

Makes your AI vtuber
HTML
397
star
2

crud

A package helps writing CRUD servers. All you need is this package and models.
Go
61
star
3

murecom-verse-1

An emotion based music recommendation system
Jupyter Notebook
43
star
4

murecom-intro

A music recommendation system
Jupyter Notebook
29
star
5

IntegerProgExperiment

线性规划课程实验——整数规划问题的求解方法
Python
13
star
6

Deep-Learning-with-Python-Notebooks

Jupyter notebooks for the book "Deep Learning with Python"
Jupyter Notebook
9
star
7

sham

A simulated machine for OS learning.
Go
6
star
8

NumericalAnalysis

数值分析实验
Jupyter Notebook
6
star
9

clownote

clownote -- CDFMLR's notes
Stylus
5
star
10

live2dview

Vue
4
star
11

TransportationProblem

求解产销平衡的运输问题
Python
4
star
12

coursesical

iCalendar课程表
Python
3
star
13

live2ddriver

Go
3
star
14

SimplexLinprog

单纯形算法实现
Python
2
star
15

muvtuberdriver

Go
2
star
16

tools

My tools
Python
2
star
17

CoursesNotifier

微信公众号上课时间提醒系统。
Go
2
star
18

Alarm-WindowsForms

A alarm clock app based on WindowsForms.
C#
1
star
19

t5_chatbot

Chinese T5 Pegasus Chatbot for muvtuber
Python
1
star
20

Graph_Python

数据结构「图」的 Python 实现。
Python
1
star
21

audioview

audioview
TypeScript
1
star
22

smelt

filter & share markdown documents
Rust
1
star
23

emotext

Python
1
star
24

examresult

考试出成绩提醒系统
Go
1
star
25

personum

a android app for counting the number of people in a photo
Java
1
star
26

sshman

A more real world example for [crud](https://github.com/cdfmlr/crud)
Go
1
star
27

hind

yet another naive container runtime
Go
1
star
28

chatgpt_chatbot

Python
1
star
29

MyClock

A simple alarm clock implemented via Xamarin in C#
C#
1
star