Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extracting body from function at runtime

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
like image 920
user2515310 Avatar asked Jun 30 '13 13:06

user2515310


1 Answers

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.

like image 190
Martijn Pieters Avatar answered Sep 28 '22 03:09

Martijn Pieters