Summary
This example is just a proof-of-concept that shows how to create an import hook that mutates a bytecode object.
Confused math¶
This demonstrates what happens if we swap the meaning of
the BINARY_ADD and BINARY_MULTIPLY bytecodes.
> python -m ideas -a confused_math_bc
Ideas Console version 0.0.34. [Python version: 3.10.2]
>>> x = 3
>>> y = 7
>>> x + y
21
>>> x * y
10
>>> # Python does simple mathematical operations *before*
>>> # generating bytecode
>>> z = 3 + 4
>>> z
7
Yes, it is a silly example. However, I cannot come up with anything possibly useful to demonstrate the value of changing bytecode. Feel free to submit a better example.
API for confused_math_bc¶
confused_math_bc.py¶
Import hook that performs bytecode changes, swapping BINARY_ADD and BINARY_MULTIPLY.
Note: If code contains something like a + b, or a * b, where a and b are integer literals (e.g. 2 + 4), the operations are done prior to the creation of a code object and thus are not captured by this transformation.
- ideas.included.confused_math_bc.add_hook(**_kwargs)[source]¶
Creates and automatically adds the import hook in sys.meta_path
- ideas.included.confused_math_bc.create_new_co(code_object)[source]¶
Recursively creates new code objects from old ones, swapping BINARY_ADD and BINARY_MULTIPLY.
- ideas.included.confused_math_bc.swap_add_mul(bytecode)[source]¶
Interchange BINARY_ADD and BINARY_MULTIPLY
- ideas.included.confused_math_bc.transform_bytecode(code_object, **_kwargs)[source]¶
Transforms the code object into a new code object