✅ 1. Prepare the code
You need the .py file or the text in a .txt file.
# A simple example of reading the code
with open("your_code.py", "r") as f:
lines = f.readlines()
✅ 2. Analyse the code to extract its structure
You can use regular expressions or Python's tokenize module to detect def, if, for, return, etc.
import tokenize
from io import BytesIO
code = ''.join(lines)
tokens = list(tokenize.tokenize(BytesIO(code.encode('utf-8')).readline))
Assign a “weight” or “type” to each line based on its token type:
def,class= main nodeif,else,elif,for,while= conditionreturn,yield= exit#or docstring = comment- others = instructions
✅ 3. Generate shapes or colours from that analysis
You can map each line to a visual object: for example, a circle whose radius depends on the line's length and whose colour depends on the instruction type.
import matplotlib.pyplot as plt
import random
fig, ax = plt.subplots(figsize=(20, 20))
ax.set_facecolor("black")
ax.axis("off")
y = 0
for i, line in enumerate(lines):
length = len(line.strip())
radius = length * 0.1
colour = plt.cm.viridis(random.random())
ax.add_patch(plt.Circle((random.uniform(0, 100), y), radius, color=colour, alpha=0.6))
y += 1.5
plt.savefig("code_poster.png", dpi=300, bbox_inches="tight")
This is a simple example. You can adapt it to use:
- Colours by token type.
- Shapes that connect to one another, such as lines and curves.
- Symmetrical patterns.
✅ 4. Adjust the artistic style
Explore these options:
- Replace
plt.Circlewithplt.Rectangle,plt.Polygon, etc. - Use libraries such as:
turtlefor a more minimal, hand-drawn style.p5, the Python port of p5.js.cairoorsvgwritefor exportable vectors.
- Export to
.svgor.pdffor high-quality printing.