5

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
user2515310
  • 357
  • 3
  • 8
  • 4
    Maybe, but why? What are you trying to achieve here? – Lennart Regebro Jun 30 '13 at 13:26
  • @LennartRegebro http://stackoverflow.com/questions/17388438/python-functools-partial-efficiency/17388981#comment25245627_17388981 – warvariuc Jun 30 '13 at 13:27
  • OK, so you want to get rid of the function call. I would think there is a better way (but admittedly, I'm not sure). – Lennart Regebro Jun 30 '13 at 13:31
  • 2
    I second @lennart on this - the answer is yes - what problem are you actually trying to solve though? – Jon Clements Jun 30 '13 at 13:34
  • With the real problem, I am developing an API where a developer can define a function on each pixel in an image sequence, and I can then pass the function body to a wrapper function which runs the body in an optimised loop. If I can't manage it any other way, it is always possible to just have developers write the inner code in a string I can execute, but it seems ugly. Any alternatives are welcome. – user2515310 Jun 30 '13 at 14:15

2 Answers2

6

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I like this approach to the problem; I don't necessarily need to worry about compiling time of byte-code, just the end performance. However, I am working on an implementation of Python 2.7 which is restricted to the standard modules only, so Byteplay is unavailable. Is it possible to iterate over bytecode from straight Python? – user2515310 Jun 30 '13 at 14:21
  • Never mind; just saw [link](http://code.activestate.com/recipes/498242/). This would work well. Thanks. – user2515310 Jun 30 '13 at 14:26
  • @user2515310: There is, using the `ast` module. – Martijn Pieters Jun 30 '13 at 14:27
0

You can use the global command, which is the most simple way in my opinion

>>> a = 3
>>> b = 4
>>> c = 5
>>> def add():
        global d
...     d = a+b+c