This example shows how to create an import hook that mutates a bytecode object.
This demonstrates what happens if we swap the meaning of
> 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.
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.
Creates and automatically adds the import hook in sys.meta_path
Recursively creates new code objects from old ones, swapping BINARY_ADD and BINARY_MULTIPLY.
Interchange BINARY_ADD and BINARY_MULTIPLY
- ideas.examples.confused_math_bc.transform_bytecode(code_object, **_kwargs)
Transforms the code object into a new code object