Build a Simple Stack-Based Virtual Machine in Python – Step-by-Step Guide
Learn how to create a simple stack‑based virtual machine in Python, covering its core components—code, stack, and address—along with essential methods like push, pop, dispatch, and run, plus an interactive REPL, complete with example code and execution output.
We implement a simple stack‑based virtual machine in Python, which operates similarly to a CPU by fetching and executing instructions.
Virtual machines are generally classified into two types: stack‑based (e.g., CPython, JVM) and register‑based (e.g., Lua). Our toy VM follows the stack‑based approach.
The VM has three essential attributes: code (the list of instructions to execute), stack (temporary storage for values), and addr (the current instruction address).
class Machine:
def __init__(self, code):
self.code = code
self.stack = list()
self.addr = 0To reduce boilerplate, we add a few helper methods:
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop()
@property
def top(self):
return self.stack[-1]The dispatch method determines whether the current item from code is an opcode or data and calls the appropriate handler.
def dispatch(self, opcode):
dispatch_map = {
"%": self.mod,
"*": self.mul,
"+": self.plus,
"-": self.minus,
"/": self.div,
"==": self.eq,
"cast_int": self.cast_int,
"cast_str": self.cast_str,
"drop": self.drop,
"dup": self.dup,
"exit": self.exit,
"if": self.if_stmt,
"jmp": self.jmp,
"over": self.over,
"print": self.print,
"println": self.println,
"read": self.read,
"stack": self.dump_stack,
"swap": self.swap,
}
if opcode in dispatch_map:
dispatch_map[opcode]()
elif isinstance(opcode, int):
self.push(opcode)
elif isinstance(opcode, str) and opcode[0] == opcode[-1] == '"':
self.push(opcode[1:-1])Example implementations of two operations:
def plus(self):
v2 = self.pop()
v1 = self.pop()
self.push(v1 + v2)
def jmp(self):
addr = self.pop()
if 0 <= addr < len(self.code):
self.addr = addr
else:
raise RuntimeError("addr must be integer")The run method repeatedly fetches the next opcode and dispatches it until the program ends.
def run(self):
while self.addr < len(self.code):
opcode = self.code[self.addr]
self.addr += 1
self.dispatch(opcode)Example usage (note that string literals must be quoted):
>> from vm import Machine
>>> Machine([521, 1314, "+", 6, "*", "println"]).run()
11010An optional interactive REPL can be added:
def repl(prompt="VM>> "):
welcome()
while True:
try:
text = read(prompt)
code = list(tokenize(text))
code = constants_fold(code)
Machine(code).run()
except (RuntimeError, IndexError):
stdout.write("Expression invalid
")
except KeyboardInterrupt:
stdout.write("Use exit to quit
")Utility functions for parsing input:
def parse_word(word):
try:
return int(word)
except ValueError:
try:
return float(word)
except ValueError:
return word
def tokenize(text):
for word in text.split():
yield parse_word(word)Resulting interactive interface screenshot:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
