Created
June 7, 2025 04:44
-
-
Save battleguard/cbd22e033c2884922a83a96146c4ca68 to your computer and use it in GitHub Desktop.
bytes code add_42 python 3.12
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
| import types | |
| import dis | |
| import inspect | |
| bin_op: dict[str,int] = {v[1]: i for i, v in enumerate(dis._nb_ops)} | |
| def op(code_name: str, arg: int = 0) -> (int, int): | |
| return dis.opmap[code_name], arg | |
| code_ints = [ | |
| *op("RESUME"), | |
| *op("LOAD_FAST", arg=0), | |
| *op("LOAD_CONST", arg=1), | |
| *op("BINARY_OP", arg=bin_op['+']), | |
| *op("CACHE"), | |
| *op("RETURN_VALUE"), | |
| ] | |
| code_manual = types.CodeType( | |
| 1, # n | |
| 0, | |
| 0, | |
| 1, # n | |
| 2, # n,42 | |
| inspect.CO_OPTIMIZED | inspect.CO_NEWLOCALS, | |
| bytes(code_ints), | |
| (None, 42), | |
| tuple(), | |
| ('n',), | |
| '<manual>', | |
| 'manual_gen_add_42', | |
| 'manual_gen_add_42', | |
| 1, | |
| bytes(), | |
| bytes(), | |
| tuple(), | |
| tuple(), | |
| ) | |
| func = types.FunctionType(code_manual, globals(), "manual_gen_add_42") | |
| print(func(5)) | |
| dis.dis(func, show_caches=True) | |
| def add_42(v): | |
| return v + 42 | |
| print(add_42(5)) | |
| dis.dis(add_42, show_caches=True) |
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
| 47 | |
| 0 RESUME 0 | |
| 2 LOAD_FAST 0 (n) | |
| 4 LOAD_CONST 1 (42) | |
| 6 BINARY_OP 0 (+) | |
| 8 CACHE 0 (counter: 0) | |
| 10 RETURN_VALUE | |
| 47 | |
| 44 0 RESUME 0 | |
| 45 2 LOAD_FAST 0 (v) | |
| 4 LOAD_CONST 1 (42) | |
| 6 BINARY_OP 0 (+) | |
| 8 CACHE 0 (counter: 0) | |
| 10 RETURN_VALUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment