Created
October 14, 2023 03:37
-
-
Save maple3142/a561154aeedefdc602373c81d49bda2e to your computer and use it in GitHub Desktop.
Python 3.11 bytecode assemble
This file contains hidden or 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
from types import FunctionType, CodeType | |
import dis | |
def assemble(ops): | |
cache = bytes([dis.opmap["CACHE"], 0]) | |
ret = b"" | |
for op, arg in ops: | |
opc = dis.opmap[op] | |
ret += bytes([opc, arg]) | |
ret += cache * dis._inline_cache_entries[opc] | |
return ret | |
co_code = assemble( | |
[ | |
("RESUME", 0), | |
("LOAD_FAST", 0), | |
("LOAD_ATTR", 0), | |
("RETURN_VALUE", 0), | |
] | |
) | |
def f(): | |
pass | |
def getattr(x, y): | |
co = f.__code__.replace( | |
co_code=co_code, | |
co_consts=(None,), | |
co_names=(y,), | |
co_varnames=("obj",), | |
co_nlocals=1, | |
co_argcount=1, | |
co_flags=3, | |
co_stacksize=1, | |
co_freevars=(), | |
) | |
return FunctionType(co, {})(x) | |
print(getattr(1, "to_bytes")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment