Given a function in Python defined as follows:
a = 3
b = 4
c = 5
def add():
d = a+b+c
is it possible to get a code object or similar that gives me:
a = 3
b = 4
c = 5
d = a+b+c
The function object has a code object associated with it; you can exec
that code object:
>>> a = 3
>>> b = 4
>>> c = 5
>>> def add():
... d = a+b+c
...
>>> exec add.func_code
This will not however set d
in the local namespace, because it is compiled to create a local name only, using the STORE_FAST
opcode. You'd have to transform this bytecode to use STORE_DEREF
opcodes instead, requiring you to learn AST transformations.
If you did want to go down this route, then read Exploring Dynamic Scoping in Python, which teaches you the ins and outs of Python scoping and byte code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With