[capi-sig] Code for a Python function

Stefan Behnel python_capi at behnel.de
Sat Jul 16 06:54:31 CEST 2011


Enrico Granata, 16.07.2011 02:44:
> for my current task I have a Python interpreter embedded in a C++ program.
> There are several ways through which the user can interact with this interpreter, typing code into it, and possibly also def-fining functions.
> I need to be able to look into all defined functions, find one given its name and (here comes the hard part) read whatever code it currently contains.
> I looked into the API and there is a PyCodeObject class, but it is subject to change at any time and I do not want to start using code that might just change the next time the user upgrades Python. Is there any documented and portable-across-versions way to read the code into a Python function just given its name?

Hi,

as this question refers to Python's introspection capabilities in general, 
this isn't the perfect place to ask. The general Python list would be a 
better place.

That being said, PyCodeObject doesn't actually contain the source code but 
the compiled byte code. You didn't state what you wanted to do with the 
code, so this may or may not be what you want. In fact, you didn't state 
your actual goals at all, so it's not obvious to me that you will really 
need the source code for what you are trying to achieve.

The code object also contains references to the place the source code 
originated from (file path and source lines). However, given that you 
expect users to "type code into the interpreter", instead of loading code 
from files, this will not allow you to get at the source code when the 
function originated in the interpreter.

Stefan


More information about the capi-sig mailing list