Skip to content

Instantly share code, notes, and snippets.

@ssanderson
Created March 3, 2018 23:05
Show Gist options
  • Save ssanderson/00a7bd52ae7cd34454f06a9701f10d08 to your computer and use it in GitHub Desktop.
Save ssanderson/00a7bd52ae7cd34454f06a9701f10d08 to your computer and use it in GitHub Desktop.
Manually assembling a code object
"""
$ python example.py
1 + 1 is 2
"""
from types import FunctionType
from codetransformer import Code
import codetransformer.instructions as instrs
def make_func():
"""Make a function equivalent to::
def addone(x):
return x + 1
"""
instructions = [
instrs.LOAD_FAST('x'),
instrs.LOAD_CONST(1),
instrs.BINARY_ADD(),
instrs.RETURN_VALUE(),
]
code = Code(instructions, argnames=('x',), name='addone')
return FunctionType(code.to_pycode(), globals={})
addone = make_func()
print("1 + 1 is", addone(1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment