__doc__ in compiled script

Fredrik Lundh fredrik at pythonware.com
Thu Nov 2 21:59:05 CET 2006


Gabriel Genellina wrote:

> I have a script starting with a docstring. After compiling it with 
> compile(), is there any way I could get the docstring? __doc__ on the 
> code object doesn't work.
 >
> I can't use __import__ because the script has top-level statements that 
> have to be executed only once (it's not supposed to be used as a module).

the __doc__ variable is set when you execute the code, so you probably 
have to do something like

from opcode import opmap, HAVE_ARGUMENT, EXTENDED_ARG

globals().update(opmap) # get opcode names

def getdoc(co):
     # get __doc__ attribute for code object
     value = None
     code = map(ord, co.co_code)
     i = 0
     while i < len(code):
         opcode = code[i]
         if opcode == LOAD_CONST:
             oparg = code[i+1] + (code[i+2] << 8)
	    value = co.co_consts[oparg]
         elif opcode == STORE_NAME:
             oparg = code[i+1] + (code[i+2] << 8)
             name = co.co_names[oparg]
	    if name == "__doc__":
		return value
         i += 1
         if opcode >= HAVE_ARGUMENT:
             i += 2

(or you can just look in co.co_consts[0] and hope for the best)

</F>




More information about the Python-list mailing list