Created
March 3, 2018 23:05
-
-
Save ssanderson/00a7bd52ae7cd34454f06a9701f10d08 to your computer and use it in GitHub Desktop.
Manually assembling a code object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
$ 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