Beyond the Code: Manipulating Bytecode and Building Community
Explore Python bytecode's evolution, its impact on tools like pytype through PEP 709, and the vital role of OSS collaboration in shaping Python's future.
not specific to any source language and target machine. Lexer / Parser Compiler Python AST Bytecode 19 Ease the effort to implement things based on AST like transpiler.
about Python. 2. Performance: Deep check ∝ Performance cost (Skipped check for optimization's example.) Why is Bytecode-based type checker not popular?
• GraalPython - Python language for the JVM built on GraalVM ◦ Github issue: Support for Python 3.12? ▪ Unresolved as of 2025/Apr ◦ Bytecode in graalpython/lib-python/3/opcode.py • PyPy - JIT compiler ◦ Release tagged with supported Python versions: https://github.com/pypy/pypy/tags ▪ CPython 3.11 as of 2025/Apr ◦ Bytecode in rpython/tool/stdlib_opcode.py ◦ Bytecode in rpython/rlib/rsre/rsre_constants.py • … and more 72 Other Python implementations and specialized tools
knowledge. 2) Bytecode change can cause unexpected impacts on CPython itself and other projects. #2: Manipulate Python bytecode is expensive. 1) Developers passion on CPython itself. 2) Hard to keep updated with the newest CPython. 3) Hard to connect to a business value directly.
< 3.13. co_code, co_varnames, co_consts = func.__code__.co_code, func.__code__.co_varnames, func.__code__.co_consts ret, value_stack, varname_to_value = None, [], {} i = 0 while i < len(co_code): opcode, oparg = dis.opname[co_code[i]], co_code[i+1] # print(i, opcode, oparg) match (opcode): case 'CACHE' | 'RESUME': pass case 'LOAD_CONST': value_stack.append(co_consts[oparg]) case 'LOAD_FAST': value_stack.append(varname_to_value[co_varnames[oparg]]) case 'STORE_FAST': varname_to_value[co_varnames[oparg]] = value_stack.pop() case 'RETURN_VALUE': ret = value_stack.pop() case 'BINARY_OP': left, right = value_stack.pop(), value_stack.pop() # Skip mapping BINARY_OP to + (requires a hardcoded map w/ oparg). value_stack.append(left + right) i += 2 return ret 84 Create your own bytecode runner (virtual machine)? >>> import dis >>> def f(): y = 2; x = 1; return x + y >>> print(my_byterun(f)) >>> 3 Code in CPython 3.11.11
''' global_var = 1 def outer_f(): outer_var = 2 def inner_f(): global global_var nonlocal outer_var local_var = 3 ''' CFG Control flow graph (of AST nodes) AST node (each node has their own symtable entry) Compiler unit Created for the first node of a new CFG Compiler Global state of compilation (symtable) Code object Bytecode Python code Code in CPython 3.13.2
import Optional def f(x: Optional[str]): if x is not None: g(x) def g(x: str): pass from random import randint def f(x: int): pass y = 42 if randint(1, 2) else "foo" f(y) def f(x: int): pass y = 42 if True else "foo" f(y)