PyCon 2016 in Portland, Or
hills next to breadcrumb illustration

Monday 4:15 p.m.–5 p.m.

Playing with Python Bytecode

Scott Sanderson, Joe Jevnik

Audience level:
Experienced
Category:
Python Internals

Description

Ever wondered what Python is actually doing when it executes your code? Want to learn to hand-craft artisanal Python bytecode? In this talk, we explain CPython's internal code representation, and we demonstrate techniques for modifying code objects for fun and profit.

Abstract

In this talk, we explain CPython's internal code representation, demonstrating techniques for modifying code objects. We break down the attributes of Python's `code` type, showing how one might construct a function or module "from scratch" without the help of the compiler. We then introduce techniques for manipulating the bytecode of existing code objects, which allows us express functions that can't be written directly in Python. We discuss some of the challenges that must be addressed to safely alter bytecode, and we conclude by demonstrating some of the toys we've built with `codetransformer`, our bytecode-manipulation library.